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": " than prefix notation\"\n :url \"https://github.com/rm-hull/infix\"\n :license {\n :name \"The MIT License (M",
"end": 178,
"score": 0.9995942115783691,
"start": 171,
"tag": "USERNAME",
"value": "rm-hull"
},
{
"context": "s [\n [rm-hull/jasentaa \"0.2.5\"]]\n :scm {:url \"git@github.com:rm-hull/infix.git\"}\n :vcs :git\n :source-paths [",
"end": 358,
"score": 0.9982746839523315,
"start": 344,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": "l/jasentaa \"0.2.5\"]]\n :scm {:url \"git@github.com:rm-hull/infix.git\"}\n :vcs :git\n :source-paths [\"src\"]\n ",
"end": 366,
"score": 0.9994186758995056,
"start": 359,
"tag": "USERNAME",
"value": "rm-hull"
},
{
"context": "path \"doc/api\"\n :source-uri \"http://github.com/rm-hull/infix/blob/master/{filepath}#L{line}\"\n :themes",
"end": 651,
"score": 0.9994843006134033,
"start": 644,
"tag": "USERNAME",
"value": "rm-hull"
}
] | project.clj | bpindelski/infix | 81 | (defproject rm-hull/infix "0.4.0"
:description "A small Clojure library for expressing LISP expressions as infix rather than prefix notation"
:url "https://github.com/rm-hull/infix"
:license {
:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"}
:dependencies [
[rm-hull/jasentaa "0.2.5"]]
:scm {:url "git@github.com:rm-hull/infix.git"}
:vcs :git
:source-paths ["src"]
:jar-exclusions [#"(?:^|/).git"]
:codox {
:source-paths ["src"]
:doc-files [
"doc/basic-usage.md"
"doc/references.md"
"LICENSE.md"
]
:output-path "doc/api"
:source-uri "http://github.com/rm-hull/infix/blob/master/{filepath}#L{line}"
:themes [:default [:google-analytics {:tracking-code "UA-39680853-6" }]]}
:min-lein-version "2.8.1"
:profiles {
:dev {
:global-vars {*warn-on-reflection* true}
:plugins [
[lein-codox "0.10.5"]
[lein-cljfmt "0.6.1"]
[lein-cloverage "1.0.13"]]
:dependencies [
[org.clojure/clojure "1.9.0"]
[google-analytics-codox-theme "0.1.0"]]}})
| 87578 | (defproject rm-hull/infix "0.4.0"
:description "A small Clojure library for expressing LISP expressions as infix rather than prefix notation"
:url "https://github.com/rm-hull/infix"
:license {
:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"}
:dependencies [
[rm-hull/jasentaa "0.2.5"]]
:scm {:url "<EMAIL>:rm-hull/infix.git"}
:vcs :git
:source-paths ["src"]
:jar-exclusions [#"(?:^|/).git"]
:codox {
:source-paths ["src"]
:doc-files [
"doc/basic-usage.md"
"doc/references.md"
"LICENSE.md"
]
:output-path "doc/api"
:source-uri "http://github.com/rm-hull/infix/blob/master/{filepath}#L{line}"
:themes [:default [:google-analytics {:tracking-code "UA-39680853-6" }]]}
:min-lein-version "2.8.1"
:profiles {
:dev {
:global-vars {*warn-on-reflection* true}
:plugins [
[lein-codox "0.10.5"]
[lein-cljfmt "0.6.1"]
[lein-cloverage "1.0.13"]]
:dependencies [
[org.clojure/clojure "1.9.0"]
[google-analytics-codox-theme "0.1.0"]]}})
| true | (defproject rm-hull/infix "0.4.0"
:description "A small Clojure library for expressing LISP expressions as infix rather than prefix notation"
:url "https://github.com/rm-hull/infix"
:license {
:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"}
:dependencies [
[rm-hull/jasentaa "0.2.5"]]
:scm {:url "PI:EMAIL:<EMAIL>END_PI:rm-hull/infix.git"}
:vcs :git
:source-paths ["src"]
:jar-exclusions [#"(?:^|/).git"]
:codox {
:source-paths ["src"]
:doc-files [
"doc/basic-usage.md"
"doc/references.md"
"LICENSE.md"
]
:output-path "doc/api"
:source-uri "http://github.com/rm-hull/infix/blob/master/{filepath}#L{line}"
:themes [:default [:google-analytics {:tracking-code "UA-39680853-6" }]]}
:min-lein-version "2.8.1"
:profiles {
:dev {
:global-vars {*warn-on-reflection* true}
:plugins [
[lein-codox "0.10.5"]
[lein-cljfmt "0.6.1"]
[lein-cloverage "1.0.13"]]
:dependencies [
[org.clojure/clojure "1.9.0"]
[google-analytics-codox-theme "0.1.0"]]}})
|
[
{
"context": "00\" \"€100,00\" \"€200,00\"])\n(def transaction-keys [\"11,11\" \"23,23\" \"34,89\" \"99,99\" \"210,78\"])\n(def transact",
"end": 351,
"score": 0.7778159379959106,
"start": 346,
"tag": "KEY",
"value": "11,11"
},
{
"context": "0,00\" \"€200,00\"])\n(def transaction-keys [\"11,11\" \"23,23\" \"34,89\" \"99,99\" \"210,78\"])\n(def transaction-desc",
"end": 359,
"score": 0.9716986417770386,
"start": 354,
"tag": "KEY",
"value": "23,23"
},
{
"context": "200,00\"])\n(def transaction-keys [\"11,11\" \"23,23\" \"34,89\" \"99,99\" \"210,78\"])\n(def transaction-descriptions",
"end": 367,
"score": 0.9550051689147949,
"start": 362,
"tag": "KEY",
"value": "34,89"
},
{
"context": ")\n(def transaction-keys [\"11,11\" \"23,23\" \"34,89\" \"99,99\" \"210,78\"])\n(def transaction-descriptions [\"drink",
"end": 375,
"score": 0.9384413957595825,
"start": 370,
"tag": "KEY",
"value": "99,99"
},
{
"context": "ransaction-keys [\"11,11\" \"23,23\" \"34,89\" \"99,99\" \"210,78\"])\n(def transaction-descriptions [\"drinks\" \"parki",
"end": 384,
"score": 0.8754404187202454,
"start": 378,
"tag": "KEY",
"value": "210,78"
},
{
"context": "fill {:css \"#login-form div:nth-child(1) input\"} \"testuser\" k/enter)\n (a/fill {:css \"#login-form div:nth-",
"end": 2399,
"score": 0.9996336102485657,
"start": 2391,
"tag": "USERNAME",
"value": "testuser"
}
] | test/src/nl/openweb/test/interactions.clj | gklijs/kafka-protobuf-rust | 52 | (ns nl.openweb.test.interactions
(:require [etaoin.api :as a]
[etaoin.keys :as k])
(:import (java.time Instant)))
(defonce driver (atom nil))
(def deposit-keys [:deposit-1000 :deposit-2000 :deposit-5000 :deposit-10000 :deposit-20000])
(def deposit-values ["€10,00" "€20,00" "€50,00" "€100,00" "€200,00"])
(def transaction-keys ["11,11" "23,23" "34,89" "99,99" "210,78"])
(def transaction-descriptions ["drinks" "parking" "groceries" "present" "fine"])
(def transaction-values ["€11,11" "€23,23" "€34,89" "€99,99" "€210,78"])
(def time-out (atom 5))
(defn wait-till-value
[expected-value interaction-interval]
(let [start (inst-ms (Instant/now))]
(a/wait-has-text
@driver
{:css "#transactions div:nth-child(1) div div:nth-child(1) p:nth-child(1) span:nth-child(2)"}
expected-value
{:interval interaction-interval :timeout @time-out})
(- (inst-ms (Instant/now)) start)))
(defn run-deposit
[m]
(a/click @driver (nth deposit-keys m))
(nth deposit-values m))
(defn run-transaction
[m]
(let [k (nth transaction-keys m)
d (nth transaction-descriptions m)]
(doto @driver
(a/fill {:css "#transfer-form div:nth-child(1) input"} k k/enter)
(a/fill {:css "#transfer-form div:nth-child(2) input"} "NL66OPEN0000000000" k/enter)
(a/fill {:css "#transfer-form div:nth-child(3) input"} d k/enter)
(a/click {:css "#transfer-form div:nth-child(4) div a"}))
(nth transaction-values m)))
(defn run
[loop-number interaction-interval]
(let [m (mod loop-number 10)
v (if (< m 5)
(run-deposit m)
(run-transaction (- m 5)))]
(wait-till-value v interaction-interval)))
(defn safe-run
[loop-number interaction-interval]
(try
(run loop-number interaction-interval)
(catch Exception error
(println "An error occurred" (.toString error))
Integer/MAX_VALUE)))
(defn wait-till-button
[]
(let [start (inst-ms (Instant/now))]
(a/wait-exists @driver :deposit-1000 {:interval 0.2 :timeout 30})
(println "waited for" (- (inst-ms (Instant/now)) start) "ms to log in and see the deposit 10 button")))
(defn login
[]
(doto @driver
(a/set-window-size 1920 1080)
(a/go "http://localhost:8181/")
(a/wait 2)
(a/click {:css "#flex-main-menu a:nth-child(2)"})
(a/wait 2)
(a/fill {:css "#login-form div:nth-child(1) input"} "testuser" k/enter)
(a/fill {:css "#login-form div:nth-child(2) input"} "password" k/enter)
(a/wait 1)
(a/click {:css "#login-form div:nth-child(3)"})))
(defn prep
[max-interaction-time]
(reset! time-out (int (Math/ceil (/ max-interaction-time 1000))))
(reset! driver (a/chrome-headless))
(login)
(wait-till-button))
(defn close
[]
(a/delete-session @driver))
| 109158 | (ns nl.openweb.test.interactions
(:require [etaoin.api :as a]
[etaoin.keys :as k])
(:import (java.time Instant)))
(defonce driver (atom nil))
(def deposit-keys [:deposit-1000 :deposit-2000 :deposit-5000 :deposit-10000 :deposit-20000])
(def deposit-values ["€10,00" "€20,00" "€50,00" "€100,00" "€200,00"])
(def transaction-keys ["<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>"])
(def transaction-descriptions ["drinks" "parking" "groceries" "present" "fine"])
(def transaction-values ["€11,11" "€23,23" "€34,89" "€99,99" "€210,78"])
(def time-out (atom 5))
(defn wait-till-value
[expected-value interaction-interval]
(let [start (inst-ms (Instant/now))]
(a/wait-has-text
@driver
{:css "#transactions div:nth-child(1) div div:nth-child(1) p:nth-child(1) span:nth-child(2)"}
expected-value
{:interval interaction-interval :timeout @time-out})
(- (inst-ms (Instant/now)) start)))
(defn run-deposit
[m]
(a/click @driver (nth deposit-keys m))
(nth deposit-values m))
(defn run-transaction
[m]
(let [k (nth transaction-keys m)
d (nth transaction-descriptions m)]
(doto @driver
(a/fill {:css "#transfer-form div:nth-child(1) input"} k k/enter)
(a/fill {:css "#transfer-form div:nth-child(2) input"} "NL66OPEN0000000000" k/enter)
(a/fill {:css "#transfer-form div:nth-child(3) input"} d k/enter)
(a/click {:css "#transfer-form div:nth-child(4) div a"}))
(nth transaction-values m)))
(defn run
[loop-number interaction-interval]
(let [m (mod loop-number 10)
v (if (< m 5)
(run-deposit m)
(run-transaction (- m 5)))]
(wait-till-value v interaction-interval)))
(defn safe-run
[loop-number interaction-interval]
(try
(run loop-number interaction-interval)
(catch Exception error
(println "An error occurred" (.toString error))
Integer/MAX_VALUE)))
(defn wait-till-button
[]
(let [start (inst-ms (Instant/now))]
(a/wait-exists @driver :deposit-1000 {:interval 0.2 :timeout 30})
(println "waited for" (- (inst-ms (Instant/now)) start) "ms to log in and see the deposit 10 button")))
(defn login
[]
(doto @driver
(a/set-window-size 1920 1080)
(a/go "http://localhost:8181/")
(a/wait 2)
(a/click {:css "#flex-main-menu a:nth-child(2)"})
(a/wait 2)
(a/fill {:css "#login-form div:nth-child(1) input"} "testuser" k/enter)
(a/fill {:css "#login-form div:nth-child(2) input"} "password" k/enter)
(a/wait 1)
(a/click {:css "#login-form div:nth-child(3)"})))
(defn prep
[max-interaction-time]
(reset! time-out (int (Math/ceil (/ max-interaction-time 1000))))
(reset! driver (a/chrome-headless))
(login)
(wait-till-button))
(defn close
[]
(a/delete-session @driver))
| true | (ns nl.openweb.test.interactions
(:require [etaoin.api :as a]
[etaoin.keys :as k])
(:import (java.time Instant)))
(defonce driver (atom nil))
(def deposit-keys [:deposit-1000 :deposit-2000 :deposit-5000 :deposit-10000 :deposit-20000])
(def deposit-values ["€10,00" "€20,00" "€50,00" "€100,00" "€200,00"])
(def transaction-keys ["PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI"])
(def transaction-descriptions ["drinks" "parking" "groceries" "present" "fine"])
(def transaction-values ["€11,11" "€23,23" "€34,89" "€99,99" "€210,78"])
(def time-out (atom 5))
(defn wait-till-value
[expected-value interaction-interval]
(let [start (inst-ms (Instant/now))]
(a/wait-has-text
@driver
{:css "#transactions div:nth-child(1) div div:nth-child(1) p:nth-child(1) span:nth-child(2)"}
expected-value
{:interval interaction-interval :timeout @time-out})
(- (inst-ms (Instant/now)) start)))
(defn run-deposit
[m]
(a/click @driver (nth deposit-keys m))
(nth deposit-values m))
(defn run-transaction
[m]
(let [k (nth transaction-keys m)
d (nth transaction-descriptions m)]
(doto @driver
(a/fill {:css "#transfer-form div:nth-child(1) input"} k k/enter)
(a/fill {:css "#transfer-form div:nth-child(2) input"} "NL66OPEN0000000000" k/enter)
(a/fill {:css "#transfer-form div:nth-child(3) input"} d k/enter)
(a/click {:css "#transfer-form div:nth-child(4) div a"}))
(nth transaction-values m)))
(defn run
[loop-number interaction-interval]
(let [m (mod loop-number 10)
v (if (< m 5)
(run-deposit m)
(run-transaction (- m 5)))]
(wait-till-value v interaction-interval)))
(defn safe-run
[loop-number interaction-interval]
(try
(run loop-number interaction-interval)
(catch Exception error
(println "An error occurred" (.toString error))
Integer/MAX_VALUE)))
(defn wait-till-button
[]
(let [start (inst-ms (Instant/now))]
(a/wait-exists @driver :deposit-1000 {:interval 0.2 :timeout 30})
(println "waited for" (- (inst-ms (Instant/now)) start) "ms to log in and see the deposit 10 button")))
(defn login
[]
(doto @driver
(a/set-window-size 1920 1080)
(a/go "http://localhost:8181/")
(a/wait 2)
(a/click {:css "#flex-main-menu a:nth-child(2)"})
(a/wait 2)
(a/fill {:css "#login-form div:nth-child(1) input"} "testuser" k/enter)
(a/fill {:css "#login-form div:nth-child(2) input"} "password" k/enter)
(a/wait 1)
(a/click {:css "#login-form div:nth-child(3)"})))
(defn prep
[max-interaction-time]
(reset! time-out (int (Math/ceil (/ max-interaction-time 1000))))
(reset! driver (a/chrome-headless))
(login)
(wait-till-button))
(defn close
[]
(a/delete-session @driver))
|
[
{
"context": ";; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2016 Alejand",
"end": 40,
"score": 0.9998935461044312,
"start": 27,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2016 Alejandro Gómez <alej",
"end": 54,
"score": 0.9999300837516785,
"start": 42,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
},
{
"context": "y Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2016 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved.\n;",
"end": 98,
"score": 0.9998888373374939,
"start": 83,
"tag": "NAME",
"value": "Alejandro Gómez"
},
{
"context": "i.nz>\n;; Copyright (c) 2014-2016 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved.\n;;\n;; Redistribution and",
"end": 121,
"score": 0.9999346137046814,
"start": 100,
"tag": "EMAIL",
"value": "alejandro@dialelo.com"
}
] | src/cats/monad/identity.cljc | klausharbo/cats | 896 | ;; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>
;; Copyright (c) 2014-2016 Alejandro Gómez <alejandro@dialelo.com>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. 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 AUTHOR ``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 AUTHOR 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 cats.monad.identity
"The Identity Monad."
(:refer-clojure :exclude [identity])
(:require [cats.protocols :as p]
[cats.context :as ctx]
[cats.util :as util]))
(declare context)
;; --- Type constructors
(defrecord Identity [v]
p/Contextual
(-get-context [_] context)
p/Extract
(-extract [_] v)
p/Printable
(-repr [_]
(str "#<Identity " (pr-str v) ">"))
#?@(:cljs [cljs.core/IDeref
(-deref [_] v)]
:clj [clojure.lang.IDeref
(deref [_] v)]))
(alter-meta! #'->Identity assoc :private true)
(util/make-printable Identity)
(defn identity
"The Identity type constructor."
[v]
(Identity. v))
(defn identity?
"Return true in case of `v` is instance
of Identity monad."
[v]
(instance? Identity v))
;; --- Monad definition
(def ^{:no-doc true}
context
(reify
p/Context
p/Functor
(-fmap [_ f iv]
(Identity. (f (.-v ^Identity iv))))
p/Applicative
(-pure [_ v]
(Identity. v))
(-fapply [_ af av]
(Identity. ((.-v ^Identity af) (.-v ^Identity av))))
p/Monad
(-mreturn [_ v]
(Identity. v))
(-mbind [_ mv f]
(f (.-v ^Identity mv)))
p/Printable
(-repr [_]
"#<Identity>")))
(util/make-printable (type context))
| 106188 | ;; Copyright (c) 2014-2016 <NAME> <<EMAIL>>
;; Copyright (c) 2014-2016 <NAME> <<EMAIL>>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. 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 AUTHOR ``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 AUTHOR 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 cats.monad.identity
"The Identity Monad."
(:refer-clojure :exclude [identity])
(:require [cats.protocols :as p]
[cats.context :as ctx]
[cats.util :as util]))
(declare context)
;; --- Type constructors
(defrecord Identity [v]
p/Contextual
(-get-context [_] context)
p/Extract
(-extract [_] v)
p/Printable
(-repr [_]
(str "#<Identity " (pr-str v) ">"))
#?@(:cljs [cljs.core/IDeref
(-deref [_] v)]
:clj [clojure.lang.IDeref
(deref [_] v)]))
(alter-meta! #'->Identity assoc :private true)
(util/make-printable Identity)
(defn identity
"The Identity type constructor."
[v]
(Identity. v))
(defn identity?
"Return true in case of `v` is instance
of Identity monad."
[v]
(instance? Identity v))
;; --- Monad definition
(def ^{:no-doc true}
context
(reify
p/Context
p/Functor
(-fmap [_ f iv]
(Identity. (f (.-v ^Identity iv))))
p/Applicative
(-pure [_ v]
(Identity. v))
(-fapply [_ af av]
(Identity. ((.-v ^Identity af) (.-v ^Identity av))))
p/Monad
(-mreturn [_ v]
(Identity. v))
(-mbind [_ mv f]
(f (.-v ^Identity mv)))
p/Printable
(-repr [_]
"#<Identity>")))
(util/make-printable (type context))
| true | ;; Copyright (c) 2014-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Copyright (c) 2014-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>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:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. 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 AUTHOR ``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 AUTHOR 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 cats.monad.identity
"The Identity Monad."
(:refer-clojure :exclude [identity])
(:require [cats.protocols :as p]
[cats.context :as ctx]
[cats.util :as util]))
(declare context)
;; --- Type constructors
(defrecord Identity [v]
p/Contextual
(-get-context [_] context)
p/Extract
(-extract [_] v)
p/Printable
(-repr [_]
(str "#<Identity " (pr-str v) ">"))
#?@(:cljs [cljs.core/IDeref
(-deref [_] v)]
:clj [clojure.lang.IDeref
(deref [_] v)]))
(alter-meta! #'->Identity assoc :private true)
(util/make-printable Identity)
(defn identity
"The Identity type constructor."
[v]
(Identity. v))
(defn identity?
"Return true in case of `v` is instance
of Identity monad."
[v]
(instance? Identity v))
;; --- Monad definition
(def ^{:no-doc true}
context
(reify
p/Context
p/Functor
(-fmap [_ f iv]
(Identity. (f (.-v ^Identity iv))))
p/Applicative
(-pure [_ v]
(Identity. v))
(-fapply [_ af av]
(Identity. ((.-v ^Identity af) (.-v ^Identity av))))
p/Monad
(-mreturn [_ v]
(Identity. v))
(-mbind [_ mv f]
(f (.-v ^Identity mv)))
p/Printable
(-repr [_]
"#<Identity>")))
(util/make-printable (type context))
|
[
{
"context": " ^{:doc \"Handy probability fns\"\n :author \"Sam Aaron\"}\n overtone.algo.chance\n (:use\n [overtone.alg",
"end": 63,
"score": 0.9998886585235596,
"start": 54,
"tag": "NAME",
"value": "Sam Aaron"
}
] | src/overtone/algo/chance.clj | rosejn/overtone | 4 | (ns
^{:doc "Handy probability fns"
:author "Sam Aaron"}
overtone.algo.chance
(:use
[overtone.algo.scaling]))
(defn choose
"Choose a random element from col."
[col]
(nth col (rand-int (count col))))
(defn choose-n
"Choose n random elements from col."
[n col]
(take n (shuffle col)))
(defn weighted-choose
"Returns an element from list vals based on the corresponding probabilities
list. The length of vals and probabilities should be similar and the sum
of all the probabilities should be 1. It is also possible to pass a map of
val -> prob pairs as a param.
The following will return one of the following vals with the corresponding
probabilities:
1 -> 50%
2 -> 30%
3 -> 12.5%
4 -> 7.5%
(weighted-choose [1 2 3 4] [0.5 0.3 0.125 0.075])
(weighted-choose {1 0.5, 2 0.3, 3 0.125, 4 0.075})"
([val-prob-map] (weighted-choose (keys val-prob-map) (vals val-prob-map)))
([vals probabilities]
(when-not (= (count vals) (count probabilities))
(throw (IllegalArgumentException. (str "Size of vals and probabilities don't match. Got "
(count vals)
" and "
(count probabilities)))))
(when-not (= (reduce + probabilities) 1.0)
(throw (IllegalArgumentException. (str "The sum of your probabilities is not 1.0"))))
(let [paired (map vector probabilities vals)
sorted (sort #(< (first %1) (first %2)) paired)
summed (loop [todo sorted
done []
cumulative 0]
(if (empty? todo)
done
(let [f-prob (ffirst todo)
f-val (second (first todo))
cumulative (+ cumulative f-prob)]
(recur (rest todo)
(conj done [cumulative f-val])
cumulative))))
rand-num (rand)]
(loop [summed summed]
(when (empty? summed)
(throw (Exception. (str "Error, Reached end of weighed choice options"))))
(if (< rand-num (ffirst summed))
(second (first summed))
(recur (rest summed)))))))
(defn weighted-coin
"Returns true or false. Probability of true is weighted by n which should be
within the range 0 - 1. n will be truncated to range 0 - 1 if it isn't"
[n]
(let [n (float n)
n (if (< n 0) 0 n)
n (if (> n 1) 1 n)]
(< (rand) n)))
(defn ranged-rand
"Returns a random value within the specified range"
[min max]
(scale-range (rand) 0 1 min max))
(defn chosen-from [notes]
(let [num-notes (count notes)]
(repeatedly #(get notes (rand-int num-notes)))))
(defn only
"Take only the specified notes from the given phrase."
([phrase notes] (only phrase notes []))
([phrase notes result]
(if notes
(recur phrase
(next notes)
(conj result (get phrase (first notes))))
result)))
| 14650 | (ns
^{:doc "Handy probability fns"
:author "<NAME>"}
overtone.algo.chance
(:use
[overtone.algo.scaling]))
(defn choose
"Choose a random element from col."
[col]
(nth col (rand-int (count col))))
(defn choose-n
"Choose n random elements from col."
[n col]
(take n (shuffle col)))
(defn weighted-choose
"Returns an element from list vals based on the corresponding probabilities
list. The length of vals and probabilities should be similar and the sum
of all the probabilities should be 1. It is also possible to pass a map of
val -> prob pairs as a param.
The following will return one of the following vals with the corresponding
probabilities:
1 -> 50%
2 -> 30%
3 -> 12.5%
4 -> 7.5%
(weighted-choose [1 2 3 4] [0.5 0.3 0.125 0.075])
(weighted-choose {1 0.5, 2 0.3, 3 0.125, 4 0.075})"
([val-prob-map] (weighted-choose (keys val-prob-map) (vals val-prob-map)))
([vals probabilities]
(when-not (= (count vals) (count probabilities))
(throw (IllegalArgumentException. (str "Size of vals and probabilities don't match. Got "
(count vals)
" and "
(count probabilities)))))
(when-not (= (reduce + probabilities) 1.0)
(throw (IllegalArgumentException. (str "The sum of your probabilities is not 1.0"))))
(let [paired (map vector probabilities vals)
sorted (sort #(< (first %1) (first %2)) paired)
summed (loop [todo sorted
done []
cumulative 0]
(if (empty? todo)
done
(let [f-prob (ffirst todo)
f-val (second (first todo))
cumulative (+ cumulative f-prob)]
(recur (rest todo)
(conj done [cumulative f-val])
cumulative))))
rand-num (rand)]
(loop [summed summed]
(when (empty? summed)
(throw (Exception. (str "Error, Reached end of weighed choice options"))))
(if (< rand-num (ffirst summed))
(second (first summed))
(recur (rest summed)))))))
(defn weighted-coin
"Returns true or false. Probability of true is weighted by n which should be
within the range 0 - 1. n will be truncated to range 0 - 1 if it isn't"
[n]
(let [n (float n)
n (if (< n 0) 0 n)
n (if (> n 1) 1 n)]
(< (rand) n)))
(defn ranged-rand
"Returns a random value within the specified range"
[min max]
(scale-range (rand) 0 1 min max))
(defn chosen-from [notes]
(let [num-notes (count notes)]
(repeatedly #(get notes (rand-int num-notes)))))
(defn only
"Take only the specified notes from the given phrase."
([phrase notes] (only phrase notes []))
([phrase notes result]
(if notes
(recur phrase
(next notes)
(conj result (get phrase (first notes))))
result)))
| true | (ns
^{:doc "Handy probability fns"
:author "PI:NAME:<NAME>END_PI"}
overtone.algo.chance
(:use
[overtone.algo.scaling]))
(defn choose
"Choose a random element from col."
[col]
(nth col (rand-int (count col))))
(defn choose-n
"Choose n random elements from col."
[n col]
(take n (shuffle col)))
(defn weighted-choose
"Returns an element from list vals based on the corresponding probabilities
list. The length of vals and probabilities should be similar and the sum
of all the probabilities should be 1. It is also possible to pass a map of
val -> prob pairs as a param.
The following will return one of the following vals with the corresponding
probabilities:
1 -> 50%
2 -> 30%
3 -> 12.5%
4 -> 7.5%
(weighted-choose [1 2 3 4] [0.5 0.3 0.125 0.075])
(weighted-choose {1 0.5, 2 0.3, 3 0.125, 4 0.075})"
([val-prob-map] (weighted-choose (keys val-prob-map) (vals val-prob-map)))
([vals probabilities]
(when-not (= (count vals) (count probabilities))
(throw (IllegalArgumentException. (str "Size of vals and probabilities don't match. Got "
(count vals)
" and "
(count probabilities)))))
(when-not (= (reduce + probabilities) 1.0)
(throw (IllegalArgumentException. (str "The sum of your probabilities is not 1.0"))))
(let [paired (map vector probabilities vals)
sorted (sort #(< (first %1) (first %2)) paired)
summed (loop [todo sorted
done []
cumulative 0]
(if (empty? todo)
done
(let [f-prob (ffirst todo)
f-val (second (first todo))
cumulative (+ cumulative f-prob)]
(recur (rest todo)
(conj done [cumulative f-val])
cumulative))))
rand-num (rand)]
(loop [summed summed]
(when (empty? summed)
(throw (Exception. (str "Error, Reached end of weighed choice options"))))
(if (< rand-num (ffirst summed))
(second (first summed))
(recur (rest summed)))))))
(defn weighted-coin
"Returns true or false. Probability of true is weighted by n which should be
within the range 0 - 1. n will be truncated to range 0 - 1 if it isn't"
[n]
(let [n (float n)
n (if (< n 0) 0 n)
n (if (> n 1) 1 n)]
(< (rand) n)))
(defn ranged-rand
"Returns a random value within the specified range"
[min max]
(scale-range (rand) 0 1 min max))
(defn chosen-from [notes]
(let [num-notes (count notes)]
(repeatedly #(get notes (rand-int num-notes)))))
(defn only
"Take only the specified notes from the given phrase."
([phrase notes] (only phrase notes []))
([phrase notes result]
(if notes
(recur phrase
(next notes)
(conj result (get phrase (first notes))))
result)))
|
[
{
"context": "te items-count 14)\n\nitems-count\n\n(def admin-name \"John\")\n\n(defn greet-player [player]\n (println admin-n",
"end": 1416,
"score": 0.9997191429138184,
"start": 1412,
"tag": "NAME",
"value": "John"
},
{
"context": " admin-name \" welcomes \" player))\n\n(greet-player \"Alice\")\n\n(greet-player \"Zack\")\n\n(def admin-name \"Terry\"",
"end": 1513,
"score": 0.9982210993766785,
"start": 1508,
"tag": "NAME",
"value": "Alice"
},
{
"context": " player))\n\n(greet-player \"Alice\")\n\n(greet-player \"Zack\")\n\n(def admin-name \"Terry\")\n\n(greet-player \"Zack\"",
"end": 1536,
"score": 0.9919960498809814,
"start": 1532,
"tag": "NAME",
"value": "Zack"
},
{
"context": "\"Alice\")\n\n(greet-player \"Zack\")\n\n(def admin-name \"Terry\")\n\n(greet-player \"Zack\")\n\n(def ^:const support-na",
"end": 1562,
"score": 0.9996757507324219,
"start": 1557,
"tag": "NAME",
"value": "Terry"
},
{
"context": "\"Zack\")\n\n(def admin-name \"Terry\")\n\n(greet-player \"Zack\")\n\n(def ^:const support-name \"Stu\")\n\n(defn suppor",
"end": 1585,
"score": 0.9888730645179749,
"start": 1581,
"tag": "NAME",
"value": "Zack"
},
{
"context": "(greet-player \"Zack\")\n\n(def ^:const support-name \"Stu\")\n\n(defn support-player [player]\n (println \"Hi\" ",
"end": 1619,
"score": 0.9965367317199707,
"start": 1616,
"tag": "NAME",
"value": "Stu"
},
{
"context": "\" support-name \"from support\"))\n\n(support-player \"Zack\")\n\n(def support-name \"Debbie\")\n\n(support-player \"",
"end": 1736,
"score": 0.9886038303375244,
"start": 1732,
"tag": "NAME",
"value": "Zack"
},
{
"context": "t\"))\n\n(support-player \"Zack\")\n\n(def support-name \"Debbie\")\n\n(support-player \"Zack\")\n\n;;; Futures\n\n(defn ge",
"end": 1765,
"score": 0.9996910095214844,
"start": 1759,
"tag": "NAME",
"value": "Debbie"
},
{
"context": "\")\n\n(def support-name \"Debbie\")\n\n(support-player \"Zack\")\n\n;;; Futures\n\n(defn get-user-accounts []\n (Thr",
"end": 1790,
"score": 0.9789783954620361,
"start": 1786,
"tag": "NAME",
"value": "Zack"
},
{
"context": "user-accounts []\n (Thread/sleep 5000)\n [{:user \"John\"}{:user \"Debbie\"}])\n\n(defn get-recent-purchases [",
"end": 1871,
"score": 0.9997496008872986,
"start": 1867,
"tag": "NAME",
"value": "John"
},
{
"context": "[]\n (Thread/sleep 5000)\n [{:user \"John\"}{:user \"Debbie\"}])\n\n(defn get-recent-purchases []\n (Thread/slee",
"end": 1887,
"score": 0.9997265934944153,
"start": 1881,
"tag": "NAME",
"value": "Debbie"
}
] | Chapter12/concurrency/src/concurrency/core.clj | srufle/Hands-On-Reactive-Programming-with-Clojure-Second-Edition | 15 | (ns concurrency.core)
;;; Atoms
(def basket-counter (atom 0))
(deref basket-counter)
@basket-counter
(reset! basket-counter 3)
@basket-counter
(swap! basket-counter + 1)
@basket-counter
(swap! basket-counter (fn [existing-value] (+ existing-value 3)))
@basket-counter
(compare-and-set! basket-counter 7 8)
@basket-counter
;;; Agents
(def play-time (agent 0))
(deref play-time)
@play-time
(send play-time + 2)
@play-time
(send-off play-time - 1)
@play-time
;;; Refs
(def basket-items (ref []))
(deref basket-items)
@basket-items
(comment
(ref-set basket-items ["vegetables"]))
(dosync
(ref-set basket-items ["vegetables"]))
@basket-items
(dosync
(alter basket-items (fn [current-value]
(conj current-value "fruits"))))
@basket-items
(def players-count (ref 0))
@players-count
(dosync
(commute players-count
(fn [current-value] (+ current-value 1))))
@players-count
(dosync
(commute players-count
(fn [current-value] (+ current-value 2))))
@players-count
;;; Vars
(def player-max-level 100)
player-max-level
(comment
(binding [player-max-level 101]
(println "player max level is: " player-max-level)))
(def ^:dynamic player-max-health 50)
player-max-health
(binding [player-max-health 55]
(println "player max health is: " player-max-health))
(def ^:private items-count 14)
items-count
(def admin-name "John")
(defn greet-player [player]
(println admin-name " welcomes " player))
(greet-player "Alice")
(greet-player "Zack")
(def admin-name "Terry")
(greet-player "Zack")
(def ^:const support-name "Stu")
(defn support-player [player]
(println "Hi" player "it is" support-name "from support"))
(support-player "Zack")
(def support-name "Debbie")
(support-player "Zack")
;;; Futures
(defn get-user-accounts []
(Thread/sleep 5000)
[{:user "John"}{:user "Debbie"}])
(defn get-recent-purchases []
(Thread/sleep 5000)
["vegetables" "fruits"])
(defn long-process []
(let [users (get-user-accounts)
purchases (get-recent-purchases)]
{:purchases purchases
:users users}))
(time (long-process))
(defn fast-process []
(let [users (future (get-user-accounts))
purchases (future (get-recent-purchases))]
{:purchases @purchases
:users @users}))
(time (fast-process))
;;; Promises
(let [prom (promise)]
(future
;; do some work in the future
(deliver prom :finished))
@prom)
| 410 | (ns concurrency.core)
;;; Atoms
(def basket-counter (atom 0))
(deref basket-counter)
@basket-counter
(reset! basket-counter 3)
@basket-counter
(swap! basket-counter + 1)
@basket-counter
(swap! basket-counter (fn [existing-value] (+ existing-value 3)))
@basket-counter
(compare-and-set! basket-counter 7 8)
@basket-counter
;;; Agents
(def play-time (agent 0))
(deref play-time)
@play-time
(send play-time + 2)
@play-time
(send-off play-time - 1)
@play-time
;;; Refs
(def basket-items (ref []))
(deref basket-items)
@basket-items
(comment
(ref-set basket-items ["vegetables"]))
(dosync
(ref-set basket-items ["vegetables"]))
@basket-items
(dosync
(alter basket-items (fn [current-value]
(conj current-value "fruits"))))
@basket-items
(def players-count (ref 0))
@players-count
(dosync
(commute players-count
(fn [current-value] (+ current-value 1))))
@players-count
(dosync
(commute players-count
(fn [current-value] (+ current-value 2))))
@players-count
;;; Vars
(def player-max-level 100)
player-max-level
(comment
(binding [player-max-level 101]
(println "player max level is: " player-max-level)))
(def ^:dynamic player-max-health 50)
player-max-health
(binding [player-max-health 55]
(println "player max health is: " player-max-health))
(def ^:private items-count 14)
items-count
(def admin-name "<NAME>")
(defn greet-player [player]
(println admin-name " welcomes " player))
(greet-player "<NAME>")
(greet-player "<NAME>")
(def admin-name "<NAME>")
(greet-player "<NAME>")
(def ^:const support-name "<NAME>")
(defn support-player [player]
(println "Hi" player "it is" support-name "from support"))
(support-player "<NAME>")
(def support-name "<NAME>")
(support-player "<NAME>")
;;; Futures
(defn get-user-accounts []
(Thread/sleep 5000)
[{:user "<NAME>"}{:user "<NAME>"}])
(defn get-recent-purchases []
(Thread/sleep 5000)
["vegetables" "fruits"])
(defn long-process []
(let [users (get-user-accounts)
purchases (get-recent-purchases)]
{:purchases purchases
:users users}))
(time (long-process))
(defn fast-process []
(let [users (future (get-user-accounts))
purchases (future (get-recent-purchases))]
{:purchases @purchases
:users @users}))
(time (fast-process))
;;; Promises
(let [prom (promise)]
(future
;; do some work in the future
(deliver prom :finished))
@prom)
| true | (ns concurrency.core)
;;; Atoms
(def basket-counter (atom 0))
(deref basket-counter)
@basket-counter
(reset! basket-counter 3)
@basket-counter
(swap! basket-counter + 1)
@basket-counter
(swap! basket-counter (fn [existing-value] (+ existing-value 3)))
@basket-counter
(compare-and-set! basket-counter 7 8)
@basket-counter
;;; Agents
(def play-time (agent 0))
(deref play-time)
@play-time
(send play-time + 2)
@play-time
(send-off play-time - 1)
@play-time
;;; Refs
(def basket-items (ref []))
(deref basket-items)
@basket-items
(comment
(ref-set basket-items ["vegetables"]))
(dosync
(ref-set basket-items ["vegetables"]))
@basket-items
(dosync
(alter basket-items (fn [current-value]
(conj current-value "fruits"))))
@basket-items
(def players-count (ref 0))
@players-count
(dosync
(commute players-count
(fn [current-value] (+ current-value 1))))
@players-count
(dosync
(commute players-count
(fn [current-value] (+ current-value 2))))
@players-count
;;; Vars
(def player-max-level 100)
player-max-level
(comment
(binding [player-max-level 101]
(println "player max level is: " player-max-level)))
(def ^:dynamic player-max-health 50)
player-max-health
(binding [player-max-health 55]
(println "player max health is: " player-max-health))
(def ^:private items-count 14)
items-count
(def admin-name "PI:NAME:<NAME>END_PI")
(defn greet-player [player]
(println admin-name " welcomes " player))
(greet-player "PI:NAME:<NAME>END_PI")
(greet-player "PI:NAME:<NAME>END_PI")
(def admin-name "PI:NAME:<NAME>END_PI")
(greet-player "PI:NAME:<NAME>END_PI")
(def ^:const support-name "PI:NAME:<NAME>END_PI")
(defn support-player [player]
(println "Hi" player "it is" support-name "from support"))
(support-player "PI:NAME:<NAME>END_PI")
(def support-name "PI:NAME:<NAME>END_PI")
(support-player "PI:NAME:<NAME>END_PI")
;;; Futures
(defn get-user-accounts []
(Thread/sleep 5000)
[{:user "PI:NAME:<NAME>END_PI"}{:user "PI:NAME:<NAME>END_PI"}])
(defn get-recent-purchases []
(Thread/sleep 5000)
["vegetables" "fruits"])
(defn long-process []
(let [users (get-user-accounts)
purchases (get-recent-purchases)]
{:purchases purchases
:users users}))
(time (long-process))
(defn fast-process []
(let [users (future (get-user-accounts))
purchases (future (get-recent-purchases))]
{:purchases @purchases
:users @users}))
(time (fast-process))
;;; Promises
(let [prom (promise)]
(future
;; do some work in the future
(deliver prom :finished))
@prom)
|
[
{
"context": "c License - Version 1.0\" :url \"https://github.com/nathanmarz/storm/blob/master/LICENSE.html\"}\n :mailing-list ",
"end": 1477,
"score": 0.9995089769363403,
"start": 1467,
"tag": "USERNAME",
"value": "nathanmarz"
},
{
"context": " :archive \"https://groups.google.com/group/storm-user\"\n :post \"storm-user@googlegr",
"end": 1624,
"score": 0.5050603151321411,
"start": 1619,
"tag": "USERNAME",
"value": "storm"
},
{
"context": " :archive \"https://groups.google.com/group/storm-user\"\n :post \"storm-user@googlegroups.",
"end": 1629,
"score": 0.7812520265579224,
"start": 1625,
"tag": "USERNAME",
"value": "user"
},
{
"context": "gle.com/group/storm-user\"\n :post \"storm-user@googlegroups.com\"}\n :dependencies [~@DEPENDENCIES]\n :min-lein-ve",
"end": 1682,
"score": 0.9998921155929565,
"start": 1655,
"tag": "EMAIL",
"value": "storm-user@googlegroups.com"
}
] | storm-lib/project.clj | desmorto/storm | 1,655 | ;; 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.
(def ROOT-DIR (subs *file* 0 (- (count *file*) (count "project.clj"))))
(def VERSION (-> ROOT-DIR (str "/../VERSION") slurp (.trim)))
(def MODULES (-> ROOT-DIR (str "/../MODULES") slurp (.split "\n") (#(filter (fn [m] (not= m "storm-console-logging")) %)) ))
(def DEPENDENCIES (for [m MODULES] [(symbol (str "storm/" m)) VERSION]))
;; for lib pom.xml, change the symbol to storm/storm-liba and filter out storm-console-logging from modules
(eval `(defproject storm/storm-lib ~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]
:min-lein-version "2.0.0"
:target-path "target"
))
| 112350 | ;; 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.
(def ROOT-DIR (subs *file* 0 (- (count *file*) (count "project.clj"))))
(def VERSION (-> ROOT-DIR (str "/../VERSION") slurp (.trim)))
(def MODULES (-> ROOT-DIR (str "/../MODULES") slurp (.split "\n") (#(filter (fn [m] (not= m "storm-console-logging")) %)) ))
(def DEPENDENCIES (for [m MODULES] [(symbol (str "storm/" m)) VERSION]))
;; for lib pom.xml, change the symbol to storm/storm-liba and filter out storm-console-logging from modules
(eval `(defproject storm/storm-lib ~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]
:min-lein-version "2.0.0"
:target-path "target"
))
| 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.
(def ROOT-DIR (subs *file* 0 (- (count *file*) (count "project.clj"))))
(def VERSION (-> ROOT-DIR (str "/../VERSION") slurp (.trim)))
(def MODULES (-> ROOT-DIR (str "/../MODULES") slurp (.split "\n") (#(filter (fn [m] (not= m "storm-console-logging")) %)) ))
(def DEPENDENCIES (for [m MODULES] [(symbol (str "storm/" m)) VERSION]))
;; for lib pom.xml, change the symbol to storm/storm-liba and filter out storm-console-logging from modules
(eval `(defproject storm/storm-lib ~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]
:min-lein-version "2.0.0"
:target-path "target"
))
|
[
{
"context": "rzuVHMA==\"))))\n\n(deftest load-config\n (let [key \"xTKVqrYHvOjR1NeoAZ4z0Q==:2WJe1eIGVT3/SItftl0MuA==\"]\n (with-redefs [util/get-env (fn [%]\n ",
"end": 423,
"score": 0.9997292757034302,
"start": 373,
"tag": "KEY",
"value": "xTKVqrYHvOjR1NeoAZ4z0Q==:2WJe1eIGVT3/SItftl0MuA==\""
},
{
"context": "29r65ht1kmf\"\n :client-secret \"ctraumfqr6t2i1uhojppks044t9eskmg7tfsn2almacgc1pebl\"\n :user-pool-id \"eu-central-",
"end": 655,
"score": 0.9996923804283142,
"start": 605,
"tag": "KEY",
"value": "ctraumfqr6t2i1uhojppks044t9eskmg7tfsn2almacgc1pebl"
},
{
"context": "ral-1_0c2u3Gtmg\"}\n :db {:password \"mypostgres\"\n :username \"postgres\"}\n ",
"end": 761,
"score": 0.9993106126785278,
"start": 751,
"tag": "PASSWORD",
"value": "mypostgres"
},
{
"context": "word \"mypostgres\"\n :username \"postgres\"}\n :svc {:password \"AA33test-svc\"\n ",
"end": 803,
"score": 0.7479028701782227,
"start": 795,
"tag": "USERNAME",
"value": "postgres"
},
{
"context": "rname \"postgres\"}\n :svc {:password \"AA33test-svc\"\n :username \"test-svc@interna",
"end": 850,
"score": 0.9967427253723145,
"start": 838,
"tag": "PASSWORD",
"value": "AA33test-svc"
}
] | test/lambda/aes_test.clj | raiffeisenbankinternational/edd-core | 4 | (ns lambda.aes-test
(:require [clojure.test :refer :all]
[lambda.aes :as aes]
[lambda.util :as util]))
(deftest test-decrypt
(is (= "a\n"
(aes/decrypt "U2FsdGVkX19KJlvYRICc9tWdHMAo3tWvPbRFqF9proQ="
"BFJN4gx80sZunDT9hDLLLA=="
"xEgLZisyV2bTh/QrzuVHMA=="))))
(deftest load-config
(let [key "xTKVqrYHvOjR1NeoAZ4z0Q==:2WJe1eIGVT3/SItftl0MuA=="]
(with-redefs [util/get-env (fn [%]
key)]
(is (= {:auth {:client-id "1gof0uh5h7pcqat29r65ht1kmf"
:client-secret "ctraumfqr6t2i1uhojppks044t9eskmg7tfsn2almacgc1pebl"
:user-pool-id "eu-central-1_0c2u3Gtmg"}
:db {:password "mypostgres"
:username "postgres"}
:svc {:password "AA33test-svc"
:username "test-svc@internal"}}
(util/load-config "secret-enc.json"))))))
| 89860 | (ns lambda.aes-test
(:require [clojure.test :refer :all]
[lambda.aes :as aes]
[lambda.util :as util]))
(deftest test-decrypt
(is (= "a\n"
(aes/decrypt "U2FsdGVkX19KJlvYRICc9tWdHMAo3tWvPbRFqF9proQ="
"BFJN4gx80sZunDT9hDLLLA=="
"xEgLZisyV2bTh/QrzuVHMA=="))))
(deftest load-config
(let [key "<KEY>]
(with-redefs [util/get-env (fn [%]
key)]
(is (= {:auth {:client-id "1gof0uh5h7pcqat29r65ht1kmf"
:client-secret "<KEY>"
:user-pool-id "eu-central-1_0c2u3Gtmg"}
:db {:password "<PASSWORD>"
:username "postgres"}
:svc {:password "<PASSWORD>"
:username "test-svc@internal"}}
(util/load-config "secret-enc.json"))))))
| true | (ns lambda.aes-test
(:require [clojure.test :refer :all]
[lambda.aes :as aes]
[lambda.util :as util]))
(deftest test-decrypt
(is (= "a\n"
(aes/decrypt "U2FsdGVkX19KJlvYRICc9tWdHMAo3tWvPbRFqF9proQ="
"BFJN4gx80sZunDT9hDLLLA=="
"xEgLZisyV2bTh/QrzuVHMA=="))))
(deftest load-config
(let [key "PI:KEY:<KEY>END_PI]
(with-redefs [util/get-env (fn [%]
key)]
(is (= {:auth {:client-id "1gof0uh5h7pcqat29r65ht1kmf"
:client-secret "PI:KEY:<KEY>END_PI"
:user-pool-id "eu-central-1_0c2u3Gtmg"}
:db {:password "PI:PASSWORD:<PASSWORD>END_PI"
:username "postgres"}
:svc {:password "PI:PASSWORD:<PASSWORD>END_PI"
:username "test-svc@internal"}}
(util/load-config "secret-enc.json"))))))
|
[
{
"context": ":name \"User\"}))\n\n;; (swap! app-state assoc :name \"Andrea\")\n\n(defn on-js-reload []\n (.info js/console \"Rel",
"end": 185,
"score": 0.9995444416999817,
"start": 179,
"tag": "NAME",
"value": "Andrea"
}
] | src/figreload_demo/core.cljs | arichiardi/fig-boot-reload | 0 | (ns ^:figwheel-load figreload-demo.core
(:require [dommy.core :as dommy]))
(enable-console-print!)
(defonce app-state (atom {:name "User"}))
;; (swap! app-state assoc :name "Andrea")
(defn on-js-reload []
(.info js/console "Reloading Javascript...")
(dommy/set-text! (dommy/sel1 ".greetee-name") (:name @app-state)))
| 49681 | (ns ^:figwheel-load figreload-demo.core
(:require [dommy.core :as dommy]))
(enable-console-print!)
(defonce app-state (atom {:name "User"}))
;; (swap! app-state assoc :name "<NAME>")
(defn on-js-reload []
(.info js/console "Reloading Javascript...")
(dommy/set-text! (dommy/sel1 ".greetee-name") (:name @app-state)))
| true | (ns ^:figwheel-load figreload-demo.core
(:require [dommy.core :as dommy]))
(enable-console-print!)
(defonce app-state (atom {:name "User"}))
;; (swap! app-state assoc :name "PI:NAME:<NAME>END_PI")
(defn on-js-reload []
(.info js/console "Reloading Javascript...")
(dommy/set-text! (dommy/sel1 ".greetee-name") (:name @app-state)))
|
[
{
"context": "person)))\n\n(fact\n (fullname ...person...) => \"Mr. Brian Marick\"\n (provided\n ...person... =contains=> {:given",
"end": 3128,
"score": 0.9996922612190247,
"start": 3116,
"tag": "NAME",
"value": "Brian Marick"
},
{
"context": " (provided\n ...person... =contains=> {:given \"Brian\", :family \"Marick\"}\n (salutation ...person...)",
"end": 3185,
"score": 0.999740719795227,
"start": 3180,
"tag": "NAME",
"value": "Brian"
},
{
"context": "..person... =contains=> {:given \"Brian\", :family \"Marick\"}\n (salutation ...person...) => \"Mr. \"))\n\n;; H",
"end": 3203,
"score": 0.7590490579605103,
"start": 3197,
"tag": "NAME",
"value": "Marick"
}
] | test/as_documentation/metaconstants.clj | MerelyAPseudonym/shallow-Midje | 0 | (ns as-documentation.metaconstants
(:use [midje sweet test-util]))
;;; THE BASICS
;;; Tests that specify too much detail about data are fragile and hard to read. Metaconstants
;;; are used to describe only the minimal information about some data. Here's the way you say
;;; that properties of the data are completely irrelevant.
(fact (vector ..a.. ..b..) => [..a.. ..b..])
;; Metaconstants can also be defined with dashes:
(fact (vector --a-- --b--) => [--a-- --b--])
;; The number of dots or dashes doesn't matter. As a convenience, you're allowed to
;; mistype metaconstants. Midje won't whine about unequal metaconstants so long as the
;; you've got some number of prefix and suffix characters:
(fact (vector --a-- --b--) => [--a- ----------------------b--])
;; It's often the case that metaconstants appear in quoted lists on the right-hand-side of
;; an example. In that case, they're not really metaconstants; they're actually symbols.
;; But the comparison still works:
(fact (vector ..a.. ..b..) => '(..a.. ..b..))
;; Metaconstants that appear more than once refer to equal metaconstants. There's nothing like
;; unification going on.
(fact (vector ..a.. ..a..) =not=> [..a.. ..b..])
;;; METACONSTANTS AND PREREQUISITES
;; You can use metaconstants in prerequisites.
(unfinished interesting?)
(defn choose-interesting-arg [& args]
(first (filter interesting? args)))
(fact
(choose-interesting-arg ..first.. ..second..) => ..second..
(provided
(interesting? ..first..) => false
(interesting? ..second..) => true))
;; The prerequisites above say "I know nothing about ..first.. except
;; that it's not interesting" and "All I know about ..second.. is that
;; it's interesting. This can be clearer and cheaper than conjuring up
;; some uninteresting and interesting data.
;; You may be wondering why there's both a `..` and a `--` notation. The reason is that
;; Clojure's reader will interpret a `..` metaconstant at the head of a list as a Java method
;; call. Consequently, the following will only work with dashes:
(defn my-apply [fun & args]
(apply fun args))
(fact
(my-apply --v-- 1 2 3) => 8
(provided
(--v-- 1 2 3) => 8))
;; Metaconstants can also be used in background prerequisites, like this:
(future-fact "This is a design flaw: background and 'local' prerequisites should be merged"
(against-background (interesting? ..first..) => false
(interesting? ..second..) => false
(interesting? ..third..) => false)
(choose-interesting-arg ..first.. ..second..) => ..second..
(provided
(interesting? ..second..) => true))
;;; METACONSTANTS AS PARTIAL DESCRIPTIONS OF MAP-LIKE OBJECTS
;; Your function might be passed a map or a record. You want to describe the minimal
;; map that will work. That is, you'll mention only the keys that are required.
(unfinished salutation)
(defn fullname [person]
(str (salutation person) (:given person) " " (:family person)))
(fact
(fullname ...person...) => "Mr. Brian Marick"
(provided
...person... =contains=> {:given "Brian", :family "Marick"}
(salutation ...person...) => "Mr. "))
;; How useful is this, compared to just passing in a map? It has the
;; slight advantage that you've identified the role of the argument
;; ("person"). It's more verbose, though, and you'll find that there
;; are some operations that don't (yet) work on metaconstants:
(defn function-under-test [thing]
(merge-with + thing {:counter 1}))
(future-fact "This doesn't work yet. Should it?"
(function-under-test ..thing..) => (contains {:counter 2})
(provided ..thing.. =contains=> {:counter 1}))
;; Metaconstans can be mentioned multiple times in a `provided` clause.
;; The key-value pairs are merged.
(fact "metaconstants can be mentioned multiple times"
(+ (:a ..m..) (:b ..m..)) => 3
(provided
..m.. =contains=> {:a 1}
..m.. =contains=> {:b 2}))
(fact "Later mentions take precedence over earlier"
(+ (:a ..m..) (:b ..m..)) => 3
(provided
..m.. =contains=> {:a 1, :b 333333}
..m.. =contains=> {:b 2}))
(fact "You can describe the metaconstant in a background prerequisite"
(fact "Here's one within a fact"
(against-background ..m.. =contains=> {:a 1})
(:a ..m..) => 1)
(against-background [--mc-- =contains=> {:b 20}]
(fact "Here's one around a fact"
(:b --mc--) => 20))
(against-background [--mc-- =contains=> {:c 300}]
(fact "background and local prerequisites have their key/value pairs merged"
(against-background --mc-- =contains=> {:d 4000})
(+ (:c --mc--) (:d --mc--) (:e --mc--)) => 54300
(provided
--mc-- =contains=> {:e 50000})))
(fact "when merging happens, the more local prerequisite takes precedence"
(against-background --mc-- =contains=> {:c 4})
(:c --mc--) => 50000
(provided
--mc-- =contains=> {:c 50000})))
;;;;
;;; Use with prerequisite functions
| 50284 | (ns as-documentation.metaconstants
(:use [midje sweet test-util]))
;;; THE BASICS
;;; Tests that specify too much detail about data are fragile and hard to read. Metaconstants
;;; are used to describe only the minimal information about some data. Here's the way you say
;;; that properties of the data are completely irrelevant.
(fact (vector ..a.. ..b..) => [..a.. ..b..])
;; Metaconstants can also be defined with dashes:
(fact (vector --a-- --b--) => [--a-- --b--])
;; The number of dots or dashes doesn't matter. As a convenience, you're allowed to
;; mistype metaconstants. Midje won't whine about unequal metaconstants so long as the
;; you've got some number of prefix and suffix characters:
(fact (vector --a-- --b--) => [--a- ----------------------b--])
;; It's often the case that metaconstants appear in quoted lists on the right-hand-side of
;; an example. In that case, they're not really metaconstants; they're actually symbols.
;; But the comparison still works:
(fact (vector ..a.. ..b..) => '(..a.. ..b..))
;; Metaconstants that appear more than once refer to equal metaconstants. There's nothing like
;; unification going on.
(fact (vector ..a.. ..a..) =not=> [..a.. ..b..])
;;; METACONSTANTS AND PREREQUISITES
;; You can use metaconstants in prerequisites.
(unfinished interesting?)
(defn choose-interesting-arg [& args]
(first (filter interesting? args)))
(fact
(choose-interesting-arg ..first.. ..second..) => ..second..
(provided
(interesting? ..first..) => false
(interesting? ..second..) => true))
;; The prerequisites above say "I know nothing about ..first.. except
;; that it's not interesting" and "All I know about ..second.. is that
;; it's interesting. This can be clearer and cheaper than conjuring up
;; some uninteresting and interesting data.
;; You may be wondering why there's both a `..` and a `--` notation. The reason is that
;; Clojure's reader will interpret a `..` metaconstant at the head of a list as a Java method
;; call. Consequently, the following will only work with dashes:
(defn my-apply [fun & args]
(apply fun args))
(fact
(my-apply --v-- 1 2 3) => 8
(provided
(--v-- 1 2 3) => 8))
;; Metaconstants can also be used in background prerequisites, like this:
(future-fact "This is a design flaw: background and 'local' prerequisites should be merged"
(against-background (interesting? ..first..) => false
(interesting? ..second..) => false
(interesting? ..third..) => false)
(choose-interesting-arg ..first.. ..second..) => ..second..
(provided
(interesting? ..second..) => true))
;;; METACONSTANTS AS PARTIAL DESCRIPTIONS OF MAP-LIKE OBJECTS
;; Your function might be passed a map or a record. You want to describe the minimal
;; map that will work. That is, you'll mention only the keys that are required.
(unfinished salutation)
(defn fullname [person]
(str (salutation person) (:given person) " " (:family person)))
(fact
(fullname ...person...) => "Mr. <NAME>"
(provided
...person... =contains=> {:given "<NAME>", :family "<NAME>"}
(salutation ...person...) => "Mr. "))
;; How useful is this, compared to just passing in a map? It has the
;; slight advantage that you've identified the role of the argument
;; ("person"). It's more verbose, though, and you'll find that there
;; are some operations that don't (yet) work on metaconstants:
(defn function-under-test [thing]
(merge-with + thing {:counter 1}))
(future-fact "This doesn't work yet. Should it?"
(function-under-test ..thing..) => (contains {:counter 2})
(provided ..thing.. =contains=> {:counter 1}))
;; Metaconstans can be mentioned multiple times in a `provided` clause.
;; The key-value pairs are merged.
(fact "metaconstants can be mentioned multiple times"
(+ (:a ..m..) (:b ..m..)) => 3
(provided
..m.. =contains=> {:a 1}
..m.. =contains=> {:b 2}))
(fact "Later mentions take precedence over earlier"
(+ (:a ..m..) (:b ..m..)) => 3
(provided
..m.. =contains=> {:a 1, :b 333333}
..m.. =contains=> {:b 2}))
(fact "You can describe the metaconstant in a background prerequisite"
(fact "Here's one within a fact"
(against-background ..m.. =contains=> {:a 1})
(:a ..m..) => 1)
(against-background [--mc-- =contains=> {:b 20}]
(fact "Here's one around a fact"
(:b --mc--) => 20))
(against-background [--mc-- =contains=> {:c 300}]
(fact "background and local prerequisites have their key/value pairs merged"
(against-background --mc-- =contains=> {:d 4000})
(+ (:c --mc--) (:d --mc--) (:e --mc--)) => 54300
(provided
--mc-- =contains=> {:e 50000})))
(fact "when merging happens, the more local prerequisite takes precedence"
(against-background --mc-- =contains=> {:c 4})
(:c --mc--) => 50000
(provided
--mc-- =contains=> {:c 50000})))
;;;;
;;; Use with prerequisite functions
| true | (ns as-documentation.metaconstants
(:use [midje sweet test-util]))
;;; THE BASICS
;;; Tests that specify too much detail about data are fragile and hard to read. Metaconstants
;;; are used to describe only the minimal information about some data. Here's the way you say
;;; that properties of the data are completely irrelevant.
(fact (vector ..a.. ..b..) => [..a.. ..b..])
;; Metaconstants can also be defined with dashes:
(fact (vector --a-- --b--) => [--a-- --b--])
;; The number of dots or dashes doesn't matter. As a convenience, you're allowed to
;; mistype metaconstants. Midje won't whine about unequal metaconstants so long as the
;; you've got some number of prefix and suffix characters:
(fact (vector --a-- --b--) => [--a- ----------------------b--])
;; It's often the case that metaconstants appear in quoted lists on the right-hand-side of
;; an example. In that case, they're not really metaconstants; they're actually symbols.
;; But the comparison still works:
(fact (vector ..a.. ..b..) => '(..a.. ..b..))
;; Metaconstants that appear more than once refer to equal metaconstants. There's nothing like
;; unification going on.
(fact (vector ..a.. ..a..) =not=> [..a.. ..b..])
;;; METACONSTANTS AND PREREQUISITES
;; You can use metaconstants in prerequisites.
(unfinished interesting?)
(defn choose-interesting-arg [& args]
(first (filter interesting? args)))
(fact
(choose-interesting-arg ..first.. ..second..) => ..second..
(provided
(interesting? ..first..) => false
(interesting? ..second..) => true))
;; The prerequisites above say "I know nothing about ..first.. except
;; that it's not interesting" and "All I know about ..second.. is that
;; it's interesting. This can be clearer and cheaper than conjuring up
;; some uninteresting and interesting data.
;; You may be wondering why there's both a `..` and a `--` notation. The reason is that
;; Clojure's reader will interpret a `..` metaconstant at the head of a list as a Java method
;; call. Consequently, the following will only work with dashes:
(defn my-apply [fun & args]
(apply fun args))
(fact
(my-apply --v-- 1 2 3) => 8
(provided
(--v-- 1 2 3) => 8))
;; Metaconstants can also be used in background prerequisites, like this:
(future-fact "This is a design flaw: background and 'local' prerequisites should be merged"
(against-background (interesting? ..first..) => false
(interesting? ..second..) => false
(interesting? ..third..) => false)
(choose-interesting-arg ..first.. ..second..) => ..second..
(provided
(interesting? ..second..) => true))
;;; METACONSTANTS AS PARTIAL DESCRIPTIONS OF MAP-LIKE OBJECTS
;; Your function might be passed a map or a record. You want to describe the minimal
;; map that will work. That is, you'll mention only the keys that are required.
(unfinished salutation)
(defn fullname [person]
(str (salutation person) (:given person) " " (:family person)))
(fact
(fullname ...person...) => "Mr. PI:NAME:<NAME>END_PI"
(provided
...person... =contains=> {:given "PI:NAME:<NAME>END_PI", :family "PI:NAME:<NAME>END_PI"}
(salutation ...person...) => "Mr. "))
;; How useful is this, compared to just passing in a map? It has the
;; slight advantage that you've identified the role of the argument
;; ("person"). It's more verbose, though, and you'll find that there
;; are some operations that don't (yet) work on metaconstants:
(defn function-under-test [thing]
(merge-with + thing {:counter 1}))
(future-fact "This doesn't work yet. Should it?"
(function-under-test ..thing..) => (contains {:counter 2})
(provided ..thing.. =contains=> {:counter 1}))
;; Metaconstans can be mentioned multiple times in a `provided` clause.
;; The key-value pairs are merged.
(fact "metaconstants can be mentioned multiple times"
(+ (:a ..m..) (:b ..m..)) => 3
(provided
..m.. =contains=> {:a 1}
..m.. =contains=> {:b 2}))
(fact "Later mentions take precedence over earlier"
(+ (:a ..m..) (:b ..m..)) => 3
(provided
..m.. =contains=> {:a 1, :b 333333}
..m.. =contains=> {:b 2}))
(fact "You can describe the metaconstant in a background prerequisite"
(fact "Here's one within a fact"
(against-background ..m.. =contains=> {:a 1})
(:a ..m..) => 1)
(against-background [--mc-- =contains=> {:b 20}]
(fact "Here's one around a fact"
(:b --mc--) => 20))
(against-background [--mc-- =contains=> {:c 300}]
(fact "background and local prerequisites have their key/value pairs merged"
(against-background --mc-- =contains=> {:d 4000})
(+ (:c --mc--) (:d --mc--) (:e --mc--)) => 54300
(provided
--mc-- =contains=> {:e 50000})))
(fact "when merging happens, the more local prerequisite takes precedence"
(against-background --mc-- =contains=> {:c 4})
(:c --mc--) => 50000
(provided
--mc-- =contains=> {:c 50000})))
;;;;
;;; Use with prerequisite functions
|
[
{
"context": " https://adventofcode.com/2020/day/7\n;; author: Vitor SRG (vitorssrg@gmail.com)\n;; date: 2021-01-04\n;;",
"end": 226,
"score": 0.9998973608016968,
"start": 217,
"tag": "NAME",
"value": "Vitor SRG"
},
{
"context": "entofcode.com/2020/day/7\n;; author: Vitor SRG (vitorssrg@gmail.com)\n;; date: 2021-01-04\n;; execution: $ bash ./",
"end": 247,
"score": 0.9999297857284546,
"start": 228,
"tag": "EMAIL",
"value": "vitorssrg@gmail.com"
}
] | aoc2020/d07/main.clj | vitorsrg/advent-of-code | 0 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; domain: Advent of Code 2020
;; challenge: Day 7: Handy Haversacks
;; url: https://adventofcode.com/2020/day/7
;; author: Vitor SRG (vitorssrg@gmail.com)
;; date: 2021-01-04
;; execution: $ bash ./aoc2020/run.sh d07 < [INPUT_FILE]
;; example:
;; $ bash ./aoc2020/run.sh d07 < ./aoc2020/d07/input.txt
;; part 1 248
;; part 2 57281
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns d07.main)
(defn parse-rule
[rule-raw]
(let [[_ outer-bag inner-bags-raw] (re-matches #"^(.*) bags contain (.*)$"
rule-raw)
inner-bags (->> inner-bags-raw
(re-seq #"(\d+) (.*?) bags?[\.\,]")
(map reverse)
(map (fn [[k v]] [k (Integer/parseInt v)]))
(into {}))]
{:rule-raw rule-raw, :outer-bag outer-bag, :inner-bags inner-bags}))
(defn build-adjacent-list
[arcs]
(->> arcs
(group-by first)
(map (fn [[k v]] [k (map second v)]))
(into {})))
(defn build-bag-weighted-digraph
[rules]
(let [vertices (set (concat (map :outer-bag rules)
(->> rules
(map :inner-bags)
(apply concat)
(map first))))
weights
(->> rules
(map
(fn [rule]
(map vector (repeat (:outer-bag rule)) (:inner-bags rule))))
(apply concat)
(map (fn [[outer-bag [inner-bag count]]] [[outer-bag inner-bag]
count]))
(into {}))
arcs (->> weights
(map first)
(set))
adjacent (build-adjacent-list arcs)]
{:vertices vertices, :arcs arcs, :weights weights, :adjacent adjacent}))
(defn reverse-weighted-digraph
[digraph]
(let [vertices (:vertices digraph)
arcs (->> digraph
(:arcs)
(map reverse)
(set))
weights (->> digraph
(:weights)
(map (fn [[k v]] [(reverse k) v]))
(into {}))
adjacent (build-adjacent-list arcs)]
{:vertices vertices, :arcs arcs, :adjacent adjacent}))
(defn digraph-dfs-reachable-step
[digraph current visited]
(if (contains? visited current)
#{current}
(let [next-visited (conj visited current)
adj (get (:adjacent digraph) current)
rec-reachable
(for [next adj]
(digraph-dfs-reachable-step digraph next next-visited))
reachable (apply clojure.set/union (conj rec-reachable (set adj)))]
reachable)))
(defn digraph-dfs-reachable
[digraph source]
(digraph-dfs-reachable-step digraph source #{}))
(defn digraph-tree-size
[digraph current]
(let [adj (get (:adjacent digraph) current)
rec-values (for [next adj
:let [weight (get (:weights digraph)
[current next])]]
(* weight (+ (digraph-tree-size digraph next) 1)))
subtree-size (apply + rec-values)]
subtree-size))
(defn -main
[& args]
(let [rules (->> *in*
(slurp)
(clojure.string/split-lines)
(map parse-rule)
(vec))
bag-weighted-digraph (build-bag-weighted-digraph rules)]
;; (clojure.pprint/pprint bag-weighted-digraph)
;; part 1
(let [reversed-bag-digraph (reverse-weighted-digraph bag-weighted-digraph)
reachable (digraph-dfs-reachable reversed-bag-digraph "shiny gold")]
(println "part 1" (count reachable)))
;; part 2
(let [shiny-gold-tree-size (digraph-tree-size bag-weighted-digraph
"shiny gold")]
(println "part 2" shiny-gold-tree-size))))
| 114156 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; domain: Advent of Code 2020
;; challenge: Day 7: Handy Haversacks
;; url: https://adventofcode.com/2020/day/7
;; author: <NAME> (<EMAIL>)
;; date: 2021-01-04
;; execution: $ bash ./aoc2020/run.sh d07 < [INPUT_FILE]
;; example:
;; $ bash ./aoc2020/run.sh d07 < ./aoc2020/d07/input.txt
;; part 1 248
;; part 2 57281
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns d07.main)
(defn parse-rule
[rule-raw]
(let [[_ outer-bag inner-bags-raw] (re-matches #"^(.*) bags contain (.*)$"
rule-raw)
inner-bags (->> inner-bags-raw
(re-seq #"(\d+) (.*?) bags?[\.\,]")
(map reverse)
(map (fn [[k v]] [k (Integer/parseInt v)]))
(into {}))]
{:rule-raw rule-raw, :outer-bag outer-bag, :inner-bags inner-bags}))
(defn build-adjacent-list
[arcs]
(->> arcs
(group-by first)
(map (fn [[k v]] [k (map second v)]))
(into {})))
(defn build-bag-weighted-digraph
[rules]
(let [vertices (set (concat (map :outer-bag rules)
(->> rules
(map :inner-bags)
(apply concat)
(map first))))
weights
(->> rules
(map
(fn [rule]
(map vector (repeat (:outer-bag rule)) (:inner-bags rule))))
(apply concat)
(map (fn [[outer-bag [inner-bag count]]] [[outer-bag inner-bag]
count]))
(into {}))
arcs (->> weights
(map first)
(set))
adjacent (build-adjacent-list arcs)]
{:vertices vertices, :arcs arcs, :weights weights, :adjacent adjacent}))
(defn reverse-weighted-digraph
[digraph]
(let [vertices (:vertices digraph)
arcs (->> digraph
(:arcs)
(map reverse)
(set))
weights (->> digraph
(:weights)
(map (fn [[k v]] [(reverse k) v]))
(into {}))
adjacent (build-adjacent-list arcs)]
{:vertices vertices, :arcs arcs, :adjacent adjacent}))
(defn digraph-dfs-reachable-step
[digraph current visited]
(if (contains? visited current)
#{current}
(let [next-visited (conj visited current)
adj (get (:adjacent digraph) current)
rec-reachable
(for [next adj]
(digraph-dfs-reachable-step digraph next next-visited))
reachable (apply clojure.set/union (conj rec-reachable (set adj)))]
reachable)))
(defn digraph-dfs-reachable
[digraph source]
(digraph-dfs-reachable-step digraph source #{}))
(defn digraph-tree-size
[digraph current]
(let [adj (get (:adjacent digraph) current)
rec-values (for [next adj
:let [weight (get (:weights digraph)
[current next])]]
(* weight (+ (digraph-tree-size digraph next) 1)))
subtree-size (apply + rec-values)]
subtree-size))
(defn -main
[& args]
(let [rules (->> *in*
(slurp)
(clojure.string/split-lines)
(map parse-rule)
(vec))
bag-weighted-digraph (build-bag-weighted-digraph rules)]
;; (clojure.pprint/pprint bag-weighted-digraph)
;; part 1
(let [reversed-bag-digraph (reverse-weighted-digraph bag-weighted-digraph)
reachable (digraph-dfs-reachable reversed-bag-digraph "shiny gold")]
(println "part 1" (count reachable)))
;; part 2
(let [shiny-gold-tree-size (digraph-tree-size bag-weighted-digraph
"shiny gold")]
(println "part 2" shiny-gold-tree-size))))
| true | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; domain: Advent of Code 2020
;; challenge: Day 7: Handy Haversacks
;; url: https://adventofcode.com/2020/day/7
;; author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;; date: 2021-01-04
;; execution: $ bash ./aoc2020/run.sh d07 < [INPUT_FILE]
;; example:
;; $ bash ./aoc2020/run.sh d07 < ./aoc2020/d07/input.txt
;; part 1 248
;; part 2 57281
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns d07.main)
(defn parse-rule
[rule-raw]
(let [[_ outer-bag inner-bags-raw] (re-matches #"^(.*) bags contain (.*)$"
rule-raw)
inner-bags (->> inner-bags-raw
(re-seq #"(\d+) (.*?) bags?[\.\,]")
(map reverse)
(map (fn [[k v]] [k (Integer/parseInt v)]))
(into {}))]
{:rule-raw rule-raw, :outer-bag outer-bag, :inner-bags inner-bags}))
(defn build-adjacent-list
[arcs]
(->> arcs
(group-by first)
(map (fn [[k v]] [k (map second v)]))
(into {})))
(defn build-bag-weighted-digraph
[rules]
(let [vertices (set (concat (map :outer-bag rules)
(->> rules
(map :inner-bags)
(apply concat)
(map first))))
weights
(->> rules
(map
(fn [rule]
(map vector (repeat (:outer-bag rule)) (:inner-bags rule))))
(apply concat)
(map (fn [[outer-bag [inner-bag count]]] [[outer-bag inner-bag]
count]))
(into {}))
arcs (->> weights
(map first)
(set))
adjacent (build-adjacent-list arcs)]
{:vertices vertices, :arcs arcs, :weights weights, :adjacent adjacent}))
(defn reverse-weighted-digraph
[digraph]
(let [vertices (:vertices digraph)
arcs (->> digraph
(:arcs)
(map reverse)
(set))
weights (->> digraph
(:weights)
(map (fn [[k v]] [(reverse k) v]))
(into {}))
adjacent (build-adjacent-list arcs)]
{:vertices vertices, :arcs arcs, :adjacent adjacent}))
(defn digraph-dfs-reachable-step
[digraph current visited]
(if (contains? visited current)
#{current}
(let [next-visited (conj visited current)
adj (get (:adjacent digraph) current)
rec-reachable
(for [next adj]
(digraph-dfs-reachable-step digraph next next-visited))
reachable (apply clojure.set/union (conj rec-reachable (set adj)))]
reachable)))
(defn digraph-dfs-reachable
[digraph source]
(digraph-dfs-reachable-step digraph source #{}))
(defn digraph-tree-size
[digraph current]
(let [adj (get (:adjacent digraph) current)
rec-values (for [next adj
:let [weight (get (:weights digraph)
[current next])]]
(* weight (+ (digraph-tree-size digraph next) 1)))
subtree-size (apply + rec-values)]
subtree-size))
(defn -main
[& args]
(let [rules (->> *in*
(slurp)
(clojure.string/split-lines)
(map parse-rule)
(vec))
bag-weighted-digraph (build-bag-weighted-digraph rules)]
;; (clojure.pprint/pprint bag-weighted-digraph)
;; part 1
(let [reversed-bag-digraph (reverse-weighted-digraph bag-weighted-digraph)
reachable (digraph-dfs-reachable reversed-bag-digraph "shiny gold")]
(println "part 1" (count reachable)))
;; part 2
(let [shiny-gold-tree-size (digraph-tree-size bag-weighted-digraph
"shiny gold")]
(println "part 2" shiny-gold-tree-size))))
|
[
{
"context": " \"fineants\"\n :password \"YhTv2ejHdtK9f6i3q6bq2hCeRK\"\n :host \"localhost\"\n ",
"end": 248,
"score": 0.9992030262947083,
"start": 222,
"tag": "PASSWORD",
"value": "YhTv2ejHdtK9f6i3q6bq2hCeRK"
}
] | src/fineants/db/db.clj | aippisch/fineants-clj | 0 | (ns fineants.db.db
(:refer-clojure :exclude [update])
(:require [korma.db :refer :all]))
(defdb fadb (postgres {:db "fineants"
:user "fineants"
:password "YhTv2ejHdtK9f6i3q6bq2hCeRK"
:host "localhost"
:port "5432"
:delimiters ""}))
| 60795 | (ns fineants.db.db
(:refer-clojure :exclude [update])
(:require [korma.db :refer :all]))
(defdb fadb (postgres {:db "fineants"
:user "fineants"
:password "<PASSWORD>"
:host "localhost"
:port "5432"
:delimiters ""}))
| true | (ns fineants.db.db
(:refer-clojure :exclude [update])
(:require [korma.db :refer :all]))
(defdb fadb (postgres {:db "fineants"
:user "fineants"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:host "localhost"
:port "5432"
:delimiters ""}))
|
[
{
"context": "server server\n :namespace namespace\n :username username\n :password password})\n\n(defn- state-watch-loop-",
"end": 1565,
"score": 0.9852107763290405,
"start": 1557,
"tag": "USERNAME",
"value": "username"
},
{
"context": "space namespace\n :username username\n :password password})\n\n(defn- state-watch-loop-init!\n \"Start updatin",
"end": 1587,
"score": 0.9981418251991272,
"start": 1579,
"tag": "PASSWORD",
"value": "password"
}
] | src/rube/core.clj | blak3mill3r/keenest-rube | 57 | (ns rube.core
(:require [clojure.string :as str]
[clojure.core.async :as a :refer [<!! timeout]]
[rube.lens :refer [resource-lens]]
[rube.api.swagger :as api]
[rube.request :refer [request watch-request]]
[rube.state :refer [update-from-snapshot update-from-event]]))
(declare state-watch-loop! watch-init!)
(defn cluster
"Make a kube atom"
[ctx]
(let [kill-ch (a/chan)
kube-atom (atom {:kill-ch kill-ch :context ctx})]
(doseq [resource-name api/supported-resources]
(let [o (watch-init! kube-atom resource-name kill-ch)]
(or (get #{:connected} o) (throw (ex-info "Could not initialize resource watchers" {:e o})))))
kube-atom))
(defn disconnect!
"Tear down a kube atom"
[kube-atom]
(if-let [ch (-> @kube-atom :kill-ch)]
(do (println "Closing kill chan") (a/close! ch))
(println "Hmm, there's no kill chan?"))
(reset! kube-atom {:state :disconnected}))
(defn intern-resources
"Intern in the current namespace a symbol named after each kind of k8s resource.
These are lenses with side-effects including making requests to the k8s API."
([kube-atom]
(intern-resources kube-atom *ns*))
([kube-atom ns]
(doseq [resource-name api/supported-resources :let [lens (resource-lens resource-name kube-atom)]]
(intern ns (symbol resource-name) lens))
kube-atom))
(defn context
"Helper function to create a kube context"
[server namespace & {:keys [username password]}]
{:server server
:namespace namespace
:username username
:password password})
(defn- state-watch-loop-init!
"Start updating the state with a k8s watch stream. `body` is the response with the current list of items and the `resourceVersion`."
[kube-atom resource-name {{v :resourceVersion} :metadata items :items :as body} kill-ch]
(swap! kube-atom (update-from-snapshot resource-name items))
(let [ctx (:context @kube-atom)]
(state-watch-loop! kube-atom
resource-name
(watch-request ctx v {:method :get :path (api/path-pattern resource-name) :kill-ch kill-ch})
kill-ch))
:connected)
(defn- watch-init!
"Do an initial GET request to list the existing resources of the given kind, then start tailing the watch stream."
[kube-atom resource-name kill-ch]
(let [resource-name (keyword resource-name)
ctx (:context @kube-atom)
{:keys [body status] :as response} (<!! (request
ctx {:method :get :path (api/path-pattern resource-name)}))]
(case status 200
(state-watch-loop-init! kube-atom resource-name body kill-ch)
response)))
(defn- reconnect-or-bust
"Called when the watch channel closes (network problem?)."
[kube-atom resource-name kill-ch & {:keys [max-wait] :or {max-wait 8000}}]
(loop [wait 500]
(or (get #{:connected} (watch-init! kube-atom resource-name kill-ch))
(do (<!! (timeout wait))
(if (> wait max-wait) :gave-up (recur (* 2 wait)))))))
(defn- state-watch-loop! [kube-atom resource-name watch-ch kill-ch]
(a/thread
(loop []
(let [{:keys [type object] :as msg} (<!! watch-ch)]
(case msg nil (case (reconnect-or-bust kube-atom resource-name kill-ch)
:connected (println "Reconnected!")
:gave-up (println "Gave up!"))
(do
(swap! kube-atom (update-from-event resource-name (-> object :metadata :name keyword) type object))
(recur)))))))
| 75437 | (ns rube.core
(:require [clojure.string :as str]
[clojure.core.async :as a :refer [<!! timeout]]
[rube.lens :refer [resource-lens]]
[rube.api.swagger :as api]
[rube.request :refer [request watch-request]]
[rube.state :refer [update-from-snapshot update-from-event]]))
(declare state-watch-loop! watch-init!)
(defn cluster
"Make a kube atom"
[ctx]
(let [kill-ch (a/chan)
kube-atom (atom {:kill-ch kill-ch :context ctx})]
(doseq [resource-name api/supported-resources]
(let [o (watch-init! kube-atom resource-name kill-ch)]
(or (get #{:connected} o) (throw (ex-info "Could not initialize resource watchers" {:e o})))))
kube-atom))
(defn disconnect!
"Tear down a kube atom"
[kube-atom]
(if-let [ch (-> @kube-atom :kill-ch)]
(do (println "Closing kill chan") (a/close! ch))
(println "Hmm, there's no kill chan?"))
(reset! kube-atom {:state :disconnected}))
(defn intern-resources
"Intern in the current namespace a symbol named after each kind of k8s resource.
These are lenses with side-effects including making requests to the k8s API."
([kube-atom]
(intern-resources kube-atom *ns*))
([kube-atom ns]
(doseq [resource-name api/supported-resources :let [lens (resource-lens resource-name kube-atom)]]
(intern ns (symbol resource-name) lens))
kube-atom))
(defn context
"Helper function to create a kube context"
[server namespace & {:keys [username password]}]
{:server server
:namespace namespace
:username username
:password <PASSWORD>})
(defn- state-watch-loop-init!
"Start updating the state with a k8s watch stream. `body` is the response with the current list of items and the `resourceVersion`."
[kube-atom resource-name {{v :resourceVersion} :metadata items :items :as body} kill-ch]
(swap! kube-atom (update-from-snapshot resource-name items))
(let [ctx (:context @kube-atom)]
(state-watch-loop! kube-atom
resource-name
(watch-request ctx v {:method :get :path (api/path-pattern resource-name) :kill-ch kill-ch})
kill-ch))
:connected)
(defn- watch-init!
"Do an initial GET request to list the existing resources of the given kind, then start tailing the watch stream."
[kube-atom resource-name kill-ch]
(let [resource-name (keyword resource-name)
ctx (:context @kube-atom)
{:keys [body status] :as response} (<!! (request
ctx {:method :get :path (api/path-pattern resource-name)}))]
(case status 200
(state-watch-loop-init! kube-atom resource-name body kill-ch)
response)))
(defn- reconnect-or-bust
"Called when the watch channel closes (network problem?)."
[kube-atom resource-name kill-ch & {:keys [max-wait] :or {max-wait 8000}}]
(loop [wait 500]
(or (get #{:connected} (watch-init! kube-atom resource-name kill-ch))
(do (<!! (timeout wait))
(if (> wait max-wait) :gave-up (recur (* 2 wait)))))))
(defn- state-watch-loop! [kube-atom resource-name watch-ch kill-ch]
(a/thread
(loop []
(let [{:keys [type object] :as msg} (<!! watch-ch)]
(case msg nil (case (reconnect-or-bust kube-atom resource-name kill-ch)
:connected (println "Reconnected!")
:gave-up (println "Gave up!"))
(do
(swap! kube-atom (update-from-event resource-name (-> object :metadata :name keyword) type object))
(recur)))))))
| true | (ns rube.core
(:require [clojure.string :as str]
[clojure.core.async :as a :refer [<!! timeout]]
[rube.lens :refer [resource-lens]]
[rube.api.swagger :as api]
[rube.request :refer [request watch-request]]
[rube.state :refer [update-from-snapshot update-from-event]]))
(declare state-watch-loop! watch-init!)
(defn cluster
"Make a kube atom"
[ctx]
(let [kill-ch (a/chan)
kube-atom (atom {:kill-ch kill-ch :context ctx})]
(doseq [resource-name api/supported-resources]
(let [o (watch-init! kube-atom resource-name kill-ch)]
(or (get #{:connected} o) (throw (ex-info "Could not initialize resource watchers" {:e o})))))
kube-atom))
(defn disconnect!
"Tear down a kube atom"
[kube-atom]
(if-let [ch (-> @kube-atom :kill-ch)]
(do (println "Closing kill chan") (a/close! ch))
(println "Hmm, there's no kill chan?"))
(reset! kube-atom {:state :disconnected}))
(defn intern-resources
"Intern in the current namespace a symbol named after each kind of k8s resource.
These are lenses with side-effects including making requests to the k8s API."
([kube-atom]
(intern-resources kube-atom *ns*))
([kube-atom ns]
(doseq [resource-name api/supported-resources :let [lens (resource-lens resource-name kube-atom)]]
(intern ns (symbol resource-name) lens))
kube-atom))
(defn context
"Helper function to create a kube context"
[server namespace & {:keys [username password]}]
{:server server
:namespace namespace
:username username
:password PI:PASSWORD:<PASSWORD>END_PI})
(defn- state-watch-loop-init!
"Start updating the state with a k8s watch stream. `body` is the response with the current list of items and the `resourceVersion`."
[kube-atom resource-name {{v :resourceVersion} :metadata items :items :as body} kill-ch]
(swap! kube-atom (update-from-snapshot resource-name items))
(let [ctx (:context @kube-atom)]
(state-watch-loop! kube-atom
resource-name
(watch-request ctx v {:method :get :path (api/path-pattern resource-name) :kill-ch kill-ch})
kill-ch))
:connected)
(defn- watch-init!
"Do an initial GET request to list the existing resources of the given kind, then start tailing the watch stream."
[kube-atom resource-name kill-ch]
(let [resource-name (keyword resource-name)
ctx (:context @kube-atom)
{:keys [body status] :as response} (<!! (request
ctx {:method :get :path (api/path-pattern resource-name)}))]
(case status 200
(state-watch-loop-init! kube-atom resource-name body kill-ch)
response)))
(defn- reconnect-or-bust
"Called when the watch channel closes (network problem?)."
[kube-atom resource-name kill-ch & {:keys [max-wait] :or {max-wait 8000}}]
(loop [wait 500]
(or (get #{:connected} (watch-init! kube-atom resource-name kill-ch))
(do (<!! (timeout wait))
(if (> wait max-wait) :gave-up (recur (* 2 wait)))))))
(defn- state-watch-loop! [kube-atom resource-name watch-ch kill-ch]
(a/thread
(loop []
(let [{:keys [type object] :as msg} (<!! watch-ch)]
(case msg nil (case (reconnect-or-bust kube-atom resource-name kill-ch)
:connected (println "Reconnected!")
:gave-up (println "Gave up!"))
(do
(swap! kube-atom (update-from-event resource-name (-> object :metadata :name keyword) type object))
(recur)))))))
|
[
{
"context": "let [now (time/now)\n profile {:username \"tester\", :hashed-password \"a long hash\",\n ",
"end": 493,
"score": 0.9940567016601562,
"start": 487,
"tag": "USERNAME",
"value": "tester"
},
{
"context": " profile {:username \"tester\", :hashed-password \"a long hash\",\n :id (java.util.UUID/randomUU",
"end": 525,
"score": 0.9993224740028381,
"start": 514,
"tag": "PASSWORD",
"value": "a long hash"
}
] | test/zanmi/view/profile_view_test.clj | zonotope/zanmi | 35 | (ns zanmi.view.profile-view-test
(:require [zanmi.boundary.signer :as signer]
[zanmi.component.signer.sha :refer [sha-signer]]
[zanmi.data.profile :refer [create]]
[zanmi.test-config :refer [config]]
[zanmi.util.time :as time]
[zanmi.view.profile-view :refer :all]
[clojure.test :refer :all]))
(deftest render-auth-token-test
(testing "render-auth-token"
(let [now (time/now)
profile {:username "tester", :hashed-password "a long hash",
:id (java.util.UUID/randomUUID), :created now, :modified now}
secret "nobody knows this!"
signer (sha-signer {:secret secret, :size 256, :auth-exp 1,
:reset-exp 1})
subject (:auth-token (render-auth-token profile signer))]
(is (not (nil? subject))
"renders the token")
(testing "signs the data"
(let [unsigned (signer/unsign signer subject)]
(is (not (nil? (:username unsigned)))
"includes the username")
(is (not (nil? (:id unsigned)))
"includes the id")
(is (not (nil? (:modified unsigned)))
"includes the modified time")
(is (nil? (:hashed-password unsigned))
"does not include the hashed password"))))))
(deftest render-message-test
(testing "render-message"
(let [msg "important message"
subject (render-message msg)]
(is (= (:message subject) msg)
"renders the message"))))
(deftest render-error-test
(testing "render-error"
(let [e "bad news"
subject (render-error e)]
(is (= (:error subject) e)
"renders the error"))))
| 11308 | (ns zanmi.view.profile-view-test
(:require [zanmi.boundary.signer :as signer]
[zanmi.component.signer.sha :refer [sha-signer]]
[zanmi.data.profile :refer [create]]
[zanmi.test-config :refer [config]]
[zanmi.util.time :as time]
[zanmi.view.profile-view :refer :all]
[clojure.test :refer :all]))
(deftest render-auth-token-test
(testing "render-auth-token"
(let [now (time/now)
profile {:username "tester", :hashed-password "<PASSWORD>",
:id (java.util.UUID/randomUUID), :created now, :modified now}
secret "nobody knows this!"
signer (sha-signer {:secret secret, :size 256, :auth-exp 1,
:reset-exp 1})
subject (:auth-token (render-auth-token profile signer))]
(is (not (nil? subject))
"renders the token")
(testing "signs the data"
(let [unsigned (signer/unsign signer subject)]
(is (not (nil? (:username unsigned)))
"includes the username")
(is (not (nil? (:id unsigned)))
"includes the id")
(is (not (nil? (:modified unsigned)))
"includes the modified time")
(is (nil? (:hashed-password unsigned))
"does not include the hashed password"))))))
(deftest render-message-test
(testing "render-message"
(let [msg "important message"
subject (render-message msg)]
(is (= (:message subject) msg)
"renders the message"))))
(deftest render-error-test
(testing "render-error"
(let [e "bad news"
subject (render-error e)]
(is (= (:error subject) e)
"renders the error"))))
| true | (ns zanmi.view.profile-view-test
(:require [zanmi.boundary.signer :as signer]
[zanmi.component.signer.sha :refer [sha-signer]]
[zanmi.data.profile :refer [create]]
[zanmi.test-config :refer [config]]
[zanmi.util.time :as time]
[zanmi.view.profile-view :refer :all]
[clojure.test :refer :all]))
(deftest render-auth-token-test
(testing "render-auth-token"
(let [now (time/now)
profile {:username "tester", :hashed-password "PI:PASSWORD:<PASSWORD>END_PI",
:id (java.util.UUID/randomUUID), :created now, :modified now}
secret "nobody knows this!"
signer (sha-signer {:secret secret, :size 256, :auth-exp 1,
:reset-exp 1})
subject (:auth-token (render-auth-token profile signer))]
(is (not (nil? subject))
"renders the token")
(testing "signs the data"
(let [unsigned (signer/unsign signer subject)]
(is (not (nil? (:username unsigned)))
"includes the username")
(is (not (nil? (:id unsigned)))
"includes the id")
(is (not (nil? (:modified unsigned)))
"includes the modified time")
(is (nil? (:hashed-password unsigned))
"does not include the hashed password"))))))
(deftest render-message-test
(testing "render-message"
(let [msg "important message"
subject (render-message msg)]
(is (= (:message subject) msg)
"renders the message"))))
(deftest render-error-test
(testing "render-error"
(let [e "bad news"
subject (render-error e)]
(is (= (:error subject) e)
"renders the error"))))
|
[
{
"context": "(range 99)))))\n\n(def prose (string/split \"Hereupon Legrand arose, with a grave and stately air, and brought ",
"end": 5205,
"score": 0.7117770910263062,
"start": 5198,
"tag": "NAME",
"value": "Legrand"
}
] | test/causal/collections/list_test.cljc | smothers/causal-tree | 114 | (ns causal.collections.list-test
(:require [causal.collections.shared :as s]
[causal.core :as c]
[causal.collections.list :as c.list]
[clojure.string :as string]
[clojure.test :refer [deftest is]])
#? (:clj (:require [criterium.core :as criterium])))
(def simple-values
(concat [c/hide c/hide :causal/h.hide :causal/h.hide :s/h.show :s/h.show \ , \ , \ , \ , \newline] (map char (take 26 (iterate inc 97)))))
; (def site-ids [0 1 2])
(def site-ids [(s/new-site-id) (s/new-site-id) (s/new-site-id) (s/new-site-id) (s/new-site-id)])
(defn rand-node
([causal-list] (rand-node causal-list (rand-nth site-ids)))
([causal-list site-id] (rand-node causal-list site-id
(rand-nth simple-values)))
; (char (+ (rand 52) 65))
; (gen/generate (spec/gen ::s/value))
([causal-list site-id value]
(let [causal-tree (.-ct causal-list)
cause (rand-nth (keys (::s/nodes causal-tree)))
lamport-ts (inc (max
(first cause)
(or (ffirst (peek (get-in causal-tree
[::s/yarns site-id])))
0)))]
(c/node lamport-ts site-id cause value))))
(defn insert-rand-node
([causal-list] (c/insert causal-list (rand-node causal-list))))
(defn idempotent? [causal-list]
(let [causal-tree (.-ct causal-list)
refreshed-ct (s/refresh-caches c.list/weave causal-tree)]
(is (= (::s/site-id causal-tree) (::s/site-id refreshed-ct)))
(is (= (::s/lamport-ts causal-tree) (::s/lamport-ts refreshed-ct)))
(is (= (::s/nodes causal-tree) (::s/nodes refreshed-ct)))
(is (= (::s/yarns causal-tree) (::s/yarns refreshed-ct)))
(is (= (::s/weave causal-tree) (::s/weave refreshed-ct)))))
; (is (= causal-tree refreshed-ct))))
(deftest known-idempotent-insert-edge-cases
(let [nodes [[[1 "xT_odlTBwTRNU" 0] [0 "0" 0] c/hide]
[[2 "9FyYzf9pum6E4" 0] [1 "xT_odlTBwTRNU" 0] \d]
[[3 "9FyYzf9pum6E4" 0] [0 "0" 0] \r]
[[4 "NwudSBdQg3Ru2" 0] [3 "9FyYzf9pum6E4" 0] \space]
[[4 "9FyYzf9pum6E4" 0] [0 "0" 0] \d]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "xT_odlTBwTRNU" 0] [0 "0" 0] \space]
[[2 "xT_odlTBwTRNU" 0] [0 "0" 0] \b]
[[2 "NwudSBdQg3Ru2" 0] [1 "xT_odlTBwTRNU" 0] \q]
[[2 "9FyYzf9pum6E4" 0] [1 "xT_odlTBwTRNU" 0] \space]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "Pz8iuNCXvVsYN" 0] [0 "0" 0] \o]
[[2 "Pz8iuNCXvVsYN" 0] [1 "Pz8iuNCXvVsYN" 0] c/hide]
[[3 "9FyYzf9pum6E4" 0] [2 "Pz8iuNCXvVsYN" 0] \u]
[[2 "NwudSBdQg3Ru2" 0] [1 "Pz8iuNCXvVsYN" 0] \space]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "W7XhooU1Hsw7E" 0] [0 "0" 0] \j]
[[1 "VdIJLRISw~zgo" 0] [0 "0" 0] \w]
[[1 "A~iIXinAXkGX7" 0] [0 "0" 0] c/hide]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "W7XhooU1Hsw7E" 0] [0 "0" 0] \u]
[[2 "W7XhooU1Hsw7E" 0] [1 "W7XhooU1Hsw7E" 0] \space]
[[2 "7hLbMKLvcll_4" 0] [1 "W7XhooU1Hsw7E" 0] c/hide]
[[1 "VdIJLRISw~zgo" 0] [0 "0" 0] \m]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "Ftbpo0oG7ZnpR" 0] [0 "0" 0] c/hide]
[[1 "A~iIXinAXkGX7" 0] [0 "0" 0] c/hide]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "VdIJLRISw~zgo" 0] [0 "0" 0] c/hide]
[[2 "A~iIXinAXkGX7" 0] [1 "VdIJLRISw~zgo" 0] "j"]
[[3 "A~iIXinAXkGX7" 0] [0 "0" 0] "i"]
[[1 "W7XhooU1Hsw7E" 0] [0 "0" 0] "s"]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 " f " 0] [0 "0" 0] c/hide]
[[2 " z " 0] [1 " f " 0] " "]
[[2 " f " 0] [0 "0" 0] "l"]
[[2 " a " 0] [1 " f " 0] "v"]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 " f " 0] [0 "0" 0] c/hide]
[[2 " f " 0] [0 "0" 0] c/hide]
[[3 " a " 0] [2 " f " 0] "c"]
[[2 " z " 0] [1 " f " 0] "r"]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl)))
(defn find-weave-inconsistencies
([] (find-weave-inconsistencies 9))
([max-steps]
(loop [cl (c/list)
insertions (c/get-weave cl)
step 0]
(if (>= step max-steps)
nil
(if (is (= (c/get-weave cl) (::s/weave (c.list/weave (.-ct cl)))))
(let [node (rand-node cl)]
(recur (c/insert cl node) (conj insertions node) (inc step)))
{:insertions insertions
:step step
:initial (c/causal->edn cl)
:reweave (c/causal->edn (c.list/weave cl))})))))
(deftest try-to-find-new-idempotent-edge-cases
(is (empty? (keep (fn [_] (find-weave-inconsistencies 9))
(range 99)))))
(def prose (string/split "Hereupon Legrand arose, with a grave and stately air, and brought me the beetle
from a glass case in which it was enclosed. It was a beautiful scarabaeus, and, at
that time, unknown to naturalists—of course a great prize in a scientific point
of view. There were two round black spots near one extremity of the back, and a
long one near the other. The scales were exceedingly hard and glossy, with all the
appearance of burnished gold. The weight of the insect was very remarkable, and,
taking all things into consideration, I could hardly blame Jupiter for his opinion
respecting it." #" "))
(defn rand-phrase []
(let [t (+ 2 (rand-int 6))
d (- (rand-int (count prose)) t)]
(string/join " " (take t (drop d prose)))))
(defn rand-weave-of-phrases
([] (rand-weave-of-phrases 3))
([n-phrases]
(let [starting-phrases (map #(str " <" % "> ") (repeatedly n-phrases rand-phrase))]
(loop [cl (c/list)
insertions []
phrase (first starting-phrases)
phrases (rest starting-phrases)
site-id (s/new-site-id)]
(if (not-empty phrase)
(let [cause (peek (get-in (.-ct cl) [::s/yarns site-id]))
node (c/node (inc (or (ffirst cause) 1)) site-id
(or (first cause) s/root-id) (first phrase))]
; (rand-node cl site-id (first phrase))]
(recur (c/insert cl node)
(conj insertions node)
(if (not-empty (rest phrase)) (rest phrase) (first phrases))
(if (not-empty (rest phrase)) phrases (rest phrases))
(if (not-empty (rest phrase)) site-id (s/new-site-id))))
{:cl cl
:insertions insertions
:phrases starting-phrases
:materialized-weave (apply str (c/causal->edn cl))
:materialized-reweave (apply str (c/causal->edn (c.list/weave (.-ct cl))))})))))
(deftest concurrent-runs-stick-together
(let [result (rand-weave-of-phrases 5)]
(doall (map #(is (string/includes? (:materialized-weave result) %))
(:phrases result)))))
(deftest hide-and-show-and-hide-and-show
(let [cl (atom (c/list "a" "b" "c"))
a-node (second (c/get-weave @cl))]
(is (= '("a" "b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) c/hide)
(is (= '("b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) :causal/h.show)
(is (= '("a" "b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) c/hide)
(is (= '("b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) :causal/h.show)
(is (= '("a" "b" "c") (c/causal->edn @cl)))))
(deftest core-cljc-list-protocol-test
; empty? conj count seq first
; last next rest map seq hash
; TODO: str get get-in nth mapv reduce reduce-kv update update-in cons
(is (empty? (c/list)))
(is (seq (c/list :foo "bar")))
(is (empty? (-> (c/list :foo) (conj c/hide))))
(let [ct (c/list :foo)
n (first ct)]
(is (seq (-> (c/append ct (first n) c/hide)
(c/append (first n) :causal/h.show)))))
(is (= 0 (count (c/list))))
(is (= 1 (count (c/list :foo))))
(is (= 0 (count (-> (c/list :foo) (conj c/hide)))))
(let [ct (c/list :foo)
n (first ct)]
(is (= 1 (count (-> (c/append ct (first n) c/hide)
(c/append (first n) :causal/h.show))))))
(let [node [[1 "site-id" 0] s/root-id :foo]]
(is (= (list node) (seq (-> (c/list) (c/insert node)))))
(is (= node (first (-> (c/list) (c/insert node)))))
(is (= node (last (-> (c/list) (c/insert node)))))
(is (= nil (next (-> (c/list) (c/insert node)))))
(is (= (list node) (next (-> (c/list) (c/insert node) (c/append s/root-id "bar")))))
(is (= '() (rest (-> (c/list) (c/insert node)))))
(is (= (list node) (rest (-> (c/list) (c/insert node) (c/append s/root-id "bar")))))
(is (= (list node) (map #(do %) (-> (c/list) (c/insert node))))))
(is (int? (hash (c/list :foo)))))
(comment
(do
(known-idempotent-insert-edge-cases)
(try-to-find-new-idempotent-edge-cases)
(concurrent-runs-stick-together)
(hide-and-show-and-hide-and-show)
(core-cljc-list-protocol-test))
(time
(keep (fn [_] (find-weave-inconsistencies 9))
(range 999)))
(rand-phrase)
(dissoc (rand-weave-of-phrases 3) :cl :insertions)
(def cl (atom (c/list)))
(time (do (doall (repeatedly 200 #(swap! cl insert-rand-node))) nil))
(criterium/quick-bench (do (insert-rand-node @cl) nil))
(criterium/quick-bench (do (c/causal->edn @cl) nil))
(def cl2 (atom (c/list)))
(time (do (doall (repeatedly 5 #(swap! cl2 insert-rand-node))) nil))
(swap! cl2 c/append (first (second (c/get-weave @cl2))) c/hide)
(swap! cl2 c/append (first (second (c/get-weave @cl2))) :causal/h.show)
(c/causal->edn @cl2))
| 81192 | (ns causal.collections.list-test
(:require [causal.collections.shared :as s]
[causal.core :as c]
[causal.collections.list :as c.list]
[clojure.string :as string]
[clojure.test :refer [deftest is]])
#? (:clj (:require [criterium.core :as criterium])))
(def simple-values
(concat [c/hide c/hide :causal/h.hide :causal/h.hide :s/h.show :s/h.show \ , \ , \ , \ , \newline] (map char (take 26 (iterate inc 97)))))
; (def site-ids [0 1 2])
(def site-ids [(s/new-site-id) (s/new-site-id) (s/new-site-id) (s/new-site-id) (s/new-site-id)])
(defn rand-node
([causal-list] (rand-node causal-list (rand-nth site-ids)))
([causal-list site-id] (rand-node causal-list site-id
(rand-nth simple-values)))
; (char (+ (rand 52) 65))
; (gen/generate (spec/gen ::s/value))
([causal-list site-id value]
(let [causal-tree (.-ct causal-list)
cause (rand-nth (keys (::s/nodes causal-tree)))
lamport-ts (inc (max
(first cause)
(or (ffirst (peek (get-in causal-tree
[::s/yarns site-id])))
0)))]
(c/node lamport-ts site-id cause value))))
(defn insert-rand-node
([causal-list] (c/insert causal-list (rand-node causal-list))))
(defn idempotent? [causal-list]
(let [causal-tree (.-ct causal-list)
refreshed-ct (s/refresh-caches c.list/weave causal-tree)]
(is (= (::s/site-id causal-tree) (::s/site-id refreshed-ct)))
(is (= (::s/lamport-ts causal-tree) (::s/lamport-ts refreshed-ct)))
(is (= (::s/nodes causal-tree) (::s/nodes refreshed-ct)))
(is (= (::s/yarns causal-tree) (::s/yarns refreshed-ct)))
(is (= (::s/weave causal-tree) (::s/weave refreshed-ct)))))
; (is (= causal-tree refreshed-ct))))
(deftest known-idempotent-insert-edge-cases
(let [nodes [[[1 "xT_odlTBwTRNU" 0] [0 "0" 0] c/hide]
[[2 "9FyYzf9pum6E4" 0] [1 "xT_odlTBwTRNU" 0] \d]
[[3 "9FyYzf9pum6E4" 0] [0 "0" 0] \r]
[[4 "NwudSBdQg3Ru2" 0] [3 "9FyYzf9pum6E4" 0] \space]
[[4 "9FyYzf9pum6E4" 0] [0 "0" 0] \d]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "xT_odlTBwTRNU" 0] [0 "0" 0] \space]
[[2 "xT_odlTBwTRNU" 0] [0 "0" 0] \b]
[[2 "NwudSBdQg3Ru2" 0] [1 "xT_odlTBwTRNU" 0] \q]
[[2 "9FyYzf9pum6E4" 0] [1 "xT_odlTBwTRNU" 0] \space]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "Pz8iuNCXvVsYN" 0] [0 "0" 0] \o]
[[2 "Pz8iuNCXvVsYN" 0] [1 "Pz8iuNCXvVsYN" 0] c/hide]
[[3 "9FyYzf9pum6E4" 0] [2 "Pz8iuNCXvVsYN" 0] \u]
[[2 "NwudSBdQg3Ru2" 0] [1 "Pz8iuNCXvVsYN" 0] \space]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "W7XhooU1Hsw7E" 0] [0 "0" 0] \j]
[[1 "VdIJLRISw~zgo" 0] [0 "0" 0] \w]
[[1 "A~iIXinAXkGX7" 0] [0 "0" 0] c/hide]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "W7XhooU1Hsw7E" 0] [0 "0" 0] \u]
[[2 "W7XhooU1Hsw7E" 0] [1 "W7XhooU1Hsw7E" 0] \space]
[[2 "7hLbMKLvcll_4" 0] [1 "W7XhooU1Hsw7E" 0] c/hide]
[[1 "VdIJLRISw~zgo" 0] [0 "0" 0] \m]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "Ftbpo0oG7ZnpR" 0] [0 "0" 0] c/hide]
[[1 "A~iIXinAXkGX7" 0] [0 "0" 0] c/hide]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "VdIJLRISw~zgo" 0] [0 "0" 0] c/hide]
[[2 "A~iIXinAXkGX7" 0] [1 "VdIJLRISw~zgo" 0] "j"]
[[3 "A~iIXinAXkGX7" 0] [0 "0" 0] "i"]
[[1 "W7XhooU1Hsw7E" 0] [0 "0" 0] "s"]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 " f " 0] [0 "0" 0] c/hide]
[[2 " z " 0] [1 " f " 0] " "]
[[2 " f " 0] [0 "0" 0] "l"]
[[2 " a " 0] [1 " f " 0] "v"]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 " f " 0] [0 "0" 0] c/hide]
[[2 " f " 0] [0 "0" 0] c/hide]
[[3 " a " 0] [2 " f " 0] "c"]
[[2 " z " 0] [1 " f " 0] "r"]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl)))
(defn find-weave-inconsistencies
([] (find-weave-inconsistencies 9))
([max-steps]
(loop [cl (c/list)
insertions (c/get-weave cl)
step 0]
(if (>= step max-steps)
nil
(if (is (= (c/get-weave cl) (::s/weave (c.list/weave (.-ct cl)))))
(let [node (rand-node cl)]
(recur (c/insert cl node) (conj insertions node) (inc step)))
{:insertions insertions
:step step
:initial (c/causal->edn cl)
:reweave (c/causal->edn (c.list/weave cl))})))))
(deftest try-to-find-new-idempotent-edge-cases
(is (empty? (keep (fn [_] (find-weave-inconsistencies 9))
(range 99)))))
(def prose (string/split "Hereupon <NAME> arose, with a grave and stately air, and brought me the beetle
from a glass case in which it was enclosed. It was a beautiful scarabaeus, and, at
that time, unknown to naturalists—of course a great prize in a scientific point
of view. There were two round black spots near one extremity of the back, and a
long one near the other. The scales were exceedingly hard and glossy, with all the
appearance of burnished gold. The weight of the insect was very remarkable, and,
taking all things into consideration, I could hardly blame Jupiter for his opinion
respecting it." #" "))
(defn rand-phrase []
(let [t (+ 2 (rand-int 6))
d (- (rand-int (count prose)) t)]
(string/join " " (take t (drop d prose)))))
(defn rand-weave-of-phrases
([] (rand-weave-of-phrases 3))
([n-phrases]
(let [starting-phrases (map #(str " <" % "> ") (repeatedly n-phrases rand-phrase))]
(loop [cl (c/list)
insertions []
phrase (first starting-phrases)
phrases (rest starting-phrases)
site-id (s/new-site-id)]
(if (not-empty phrase)
(let [cause (peek (get-in (.-ct cl) [::s/yarns site-id]))
node (c/node (inc (or (ffirst cause) 1)) site-id
(or (first cause) s/root-id) (first phrase))]
; (rand-node cl site-id (first phrase))]
(recur (c/insert cl node)
(conj insertions node)
(if (not-empty (rest phrase)) (rest phrase) (first phrases))
(if (not-empty (rest phrase)) phrases (rest phrases))
(if (not-empty (rest phrase)) site-id (s/new-site-id))))
{:cl cl
:insertions insertions
:phrases starting-phrases
:materialized-weave (apply str (c/causal->edn cl))
:materialized-reweave (apply str (c/causal->edn (c.list/weave (.-ct cl))))})))))
(deftest concurrent-runs-stick-together
(let [result (rand-weave-of-phrases 5)]
(doall (map #(is (string/includes? (:materialized-weave result) %))
(:phrases result)))))
(deftest hide-and-show-and-hide-and-show
(let [cl (atom (c/list "a" "b" "c"))
a-node (second (c/get-weave @cl))]
(is (= '("a" "b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) c/hide)
(is (= '("b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) :causal/h.show)
(is (= '("a" "b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) c/hide)
(is (= '("b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) :causal/h.show)
(is (= '("a" "b" "c") (c/causal->edn @cl)))))
(deftest core-cljc-list-protocol-test
; empty? conj count seq first
; last next rest map seq hash
; TODO: str get get-in nth mapv reduce reduce-kv update update-in cons
(is (empty? (c/list)))
(is (seq (c/list :foo "bar")))
(is (empty? (-> (c/list :foo) (conj c/hide))))
(let [ct (c/list :foo)
n (first ct)]
(is (seq (-> (c/append ct (first n) c/hide)
(c/append (first n) :causal/h.show)))))
(is (= 0 (count (c/list))))
(is (= 1 (count (c/list :foo))))
(is (= 0 (count (-> (c/list :foo) (conj c/hide)))))
(let [ct (c/list :foo)
n (first ct)]
(is (= 1 (count (-> (c/append ct (first n) c/hide)
(c/append (first n) :causal/h.show))))))
(let [node [[1 "site-id" 0] s/root-id :foo]]
(is (= (list node) (seq (-> (c/list) (c/insert node)))))
(is (= node (first (-> (c/list) (c/insert node)))))
(is (= node (last (-> (c/list) (c/insert node)))))
(is (= nil (next (-> (c/list) (c/insert node)))))
(is (= (list node) (next (-> (c/list) (c/insert node) (c/append s/root-id "bar")))))
(is (= '() (rest (-> (c/list) (c/insert node)))))
(is (= (list node) (rest (-> (c/list) (c/insert node) (c/append s/root-id "bar")))))
(is (= (list node) (map #(do %) (-> (c/list) (c/insert node))))))
(is (int? (hash (c/list :foo)))))
(comment
(do
(known-idempotent-insert-edge-cases)
(try-to-find-new-idempotent-edge-cases)
(concurrent-runs-stick-together)
(hide-and-show-and-hide-and-show)
(core-cljc-list-protocol-test))
(time
(keep (fn [_] (find-weave-inconsistencies 9))
(range 999)))
(rand-phrase)
(dissoc (rand-weave-of-phrases 3) :cl :insertions)
(def cl (atom (c/list)))
(time (do (doall (repeatedly 200 #(swap! cl insert-rand-node))) nil))
(criterium/quick-bench (do (insert-rand-node @cl) nil))
(criterium/quick-bench (do (c/causal->edn @cl) nil))
(def cl2 (atom (c/list)))
(time (do (doall (repeatedly 5 #(swap! cl2 insert-rand-node))) nil))
(swap! cl2 c/append (first (second (c/get-weave @cl2))) c/hide)
(swap! cl2 c/append (first (second (c/get-weave @cl2))) :causal/h.show)
(c/causal->edn @cl2))
| true | (ns causal.collections.list-test
(:require [causal.collections.shared :as s]
[causal.core :as c]
[causal.collections.list :as c.list]
[clojure.string :as string]
[clojure.test :refer [deftest is]])
#? (:clj (:require [criterium.core :as criterium])))
(def simple-values
(concat [c/hide c/hide :causal/h.hide :causal/h.hide :s/h.show :s/h.show \ , \ , \ , \ , \newline] (map char (take 26 (iterate inc 97)))))
; (def site-ids [0 1 2])
(def site-ids [(s/new-site-id) (s/new-site-id) (s/new-site-id) (s/new-site-id) (s/new-site-id)])
(defn rand-node
([causal-list] (rand-node causal-list (rand-nth site-ids)))
([causal-list site-id] (rand-node causal-list site-id
(rand-nth simple-values)))
; (char (+ (rand 52) 65))
; (gen/generate (spec/gen ::s/value))
([causal-list site-id value]
(let [causal-tree (.-ct causal-list)
cause (rand-nth (keys (::s/nodes causal-tree)))
lamport-ts (inc (max
(first cause)
(or (ffirst (peek (get-in causal-tree
[::s/yarns site-id])))
0)))]
(c/node lamport-ts site-id cause value))))
(defn insert-rand-node
([causal-list] (c/insert causal-list (rand-node causal-list))))
(defn idempotent? [causal-list]
(let [causal-tree (.-ct causal-list)
refreshed-ct (s/refresh-caches c.list/weave causal-tree)]
(is (= (::s/site-id causal-tree) (::s/site-id refreshed-ct)))
(is (= (::s/lamport-ts causal-tree) (::s/lamport-ts refreshed-ct)))
(is (= (::s/nodes causal-tree) (::s/nodes refreshed-ct)))
(is (= (::s/yarns causal-tree) (::s/yarns refreshed-ct)))
(is (= (::s/weave causal-tree) (::s/weave refreshed-ct)))))
; (is (= causal-tree refreshed-ct))))
(deftest known-idempotent-insert-edge-cases
(let [nodes [[[1 "xT_odlTBwTRNU" 0] [0 "0" 0] c/hide]
[[2 "9FyYzf9pum6E4" 0] [1 "xT_odlTBwTRNU" 0] \d]
[[3 "9FyYzf9pum6E4" 0] [0 "0" 0] \r]
[[4 "NwudSBdQg3Ru2" 0] [3 "9FyYzf9pum6E4" 0] \space]
[[4 "9FyYzf9pum6E4" 0] [0 "0" 0] \d]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "xT_odlTBwTRNU" 0] [0 "0" 0] \space]
[[2 "xT_odlTBwTRNU" 0] [0 "0" 0] \b]
[[2 "NwudSBdQg3Ru2" 0] [1 "xT_odlTBwTRNU" 0] \q]
[[2 "9FyYzf9pum6E4" 0] [1 "xT_odlTBwTRNU" 0] \space]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "Pz8iuNCXvVsYN" 0] [0 "0" 0] \o]
[[2 "Pz8iuNCXvVsYN" 0] [1 "Pz8iuNCXvVsYN" 0] c/hide]
[[3 "9FyYzf9pum6E4" 0] [2 "Pz8iuNCXvVsYN" 0] \u]
[[2 "NwudSBdQg3Ru2" 0] [1 "Pz8iuNCXvVsYN" 0] \space]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "W7XhooU1Hsw7E" 0] [0 "0" 0] \j]
[[1 "VdIJLRISw~zgo" 0] [0 "0" 0] \w]
[[1 "A~iIXinAXkGX7" 0] [0 "0" 0] c/hide]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "W7XhooU1Hsw7E" 0] [0 "0" 0] \u]
[[2 "W7XhooU1Hsw7E" 0] [1 "W7XhooU1Hsw7E" 0] \space]
[[2 "7hLbMKLvcll_4" 0] [1 "W7XhooU1Hsw7E" 0] c/hide]
[[1 "VdIJLRISw~zgo" 0] [0 "0" 0] \m]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "Ftbpo0oG7ZnpR" 0] [0 "0" 0] c/hide]
[[1 "A~iIXinAXkGX7" 0] [0 "0" 0] c/hide]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 "VdIJLRISw~zgo" 0] [0 "0" 0] c/hide]
[[2 "A~iIXinAXkGX7" 0] [1 "VdIJLRISw~zgo" 0] "j"]
[[3 "A~iIXinAXkGX7" 0] [0 "0" 0] "i"]
[[1 "W7XhooU1Hsw7E" 0] [0 "0" 0] "s"]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 " f " 0] [0 "0" 0] c/hide]
[[2 " z " 0] [1 " f " 0] " "]
[[2 " f " 0] [0 "0" 0] "l"]
[[2 " a " 0] [1 " f " 0] "v"]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl))
(let [nodes [[[1 " f " 0] [0 "0" 0] c/hide]
[[2 " f " 0] [0 "0" 0] c/hide]
[[3 " a " 0] [2 " f " 0] "c"]
[[2 " z " 0] [1 " f " 0] "r"]]
cl (reduce c/insert (c/list) nodes)]
(idempotent? cl)))
(defn find-weave-inconsistencies
([] (find-weave-inconsistencies 9))
([max-steps]
(loop [cl (c/list)
insertions (c/get-weave cl)
step 0]
(if (>= step max-steps)
nil
(if (is (= (c/get-weave cl) (::s/weave (c.list/weave (.-ct cl)))))
(let [node (rand-node cl)]
(recur (c/insert cl node) (conj insertions node) (inc step)))
{:insertions insertions
:step step
:initial (c/causal->edn cl)
:reweave (c/causal->edn (c.list/weave cl))})))))
(deftest try-to-find-new-idempotent-edge-cases
(is (empty? (keep (fn [_] (find-weave-inconsistencies 9))
(range 99)))))
(def prose (string/split "Hereupon PI:NAME:<NAME>END_PI arose, with a grave and stately air, and brought me the beetle
from a glass case in which it was enclosed. It was a beautiful scarabaeus, and, at
that time, unknown to naturalists—of course a great prize in a scientific point
of view. There were two round black spots near one extremity of the back, and a
long one near the other. The scales were exceedingly hard and glossy, with all the
appearance of burnished gold. The weight of the insect was very remarkable, and,
taking all things into consideration, I could hardly blame Jupiter for his opinion
respecting it." #" "))
(defn rand-phrase []
(let [t (+ 2 (rand-int 6))
d (- (rand-int (count prose)) t)]
(string/join " " (take t (drop d prose)))))
(defn rand-weave-of-phrases
([] (rand-weave-of-phrases 3))
([n-phrases]
(let [starting-phrases (map #(str " <" % "> ") (repeatedly n-phrases rand-phrase))]
(loop [cl (c/list)
insertions []
phrase (first starting-phrases)
phrases (rest starting-phrases)
site-id (s/new-site-id)]
(if (not-empty phrase)
(let [cause (peek (get-in (.-ct cl) [::s/yarns site-id]))
node (c/node (inc (or (ffirst cause) 1)) site-id
(or (first cause) s/root-id) (first phrase))]
; (rand-node cl site-id (first phrase))]
(recur (c/insert cl node)
(conj insertions node)
(if (not-empty (rest phrase)) (rest phrase) (first phrases))
(if (not-empty (rest phrase)) phrases (rest phrases))
(if (not-empty (rest phrase)) site-id (s/new-site-id))))
{:cl cl
:insertions insertions
:phrases starting-phrases
:materialized-weave (apply str (c/causal->edn cl))
:materialized-reweave (apply str (c/causal->edn (c.list/weave (.-ct cl))))})))))
(deftest concurrent-runs-stick-together
(let [result (rand-weave-of-phrases 5)]
(doall (map #(is (string/includes? (:materialized-weave result) %))
(:phrases result)))))
(deftest hide-and-show-and-hide-and-show
(let [cl (atom (c/list "a" "b" "c"))
a-node (second (c/get-weave @cl))]
(is (= '("a" "b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) c/hide)
(is (= '("b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) :causal/h.show)
(is (= '("a" "b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) c/hide)
(is (= '("b" "c") (c/causal->edn @cl)))
(swap! cl c/append (first a-node) :causal/h.show)
(is (= '("a" "b" "c") (c/causal->edn @cl)))))
(deftest core-cljc-list-protocol-test
; empty? conj count seq first
; last next rest map seq hash
; TODO: str get get-in nth mapv reduce reduce-kv update update-in cons
(is (empty? (c/list)))
(is (seq (c/list :foo "bar")))
(is (empty? (-> (c/list :foo) (conj c/hide))))
(let [ct (c/list :foo)
n (first ct)]
(is (seq (-> (c/append ct (first n) c/hide)
(c/append (first n) :causal/h.show)))))
(is (= 0 (count (c/list))))
(is (= 1 (count (c/list :foo))))
(is (= 0 (count (-> (c/list :foo) (conj c/hide)))))
(let [ct (c/list :foo)
n (first ct)]
(is (= 1 (count (-> (c/append ct (first n) c/hide)
(c/append (first n) :causal/h.show))))))
(let [node [[1 "site-id" 0] s/root-id :foo]]
(is (= (list node) (seq (-> (c/list) (c/insert node)))))
(is (= node (first (-> (c/list) (c/insert node)))))
(is (= node (last (-> (c/list) (c/insert node)))))
(is (= nil (next (-> (c/list) (c/insert node)))))
(is (= (list node) (next (-> (c/list) (c/insert node) (c/append s/root-id "bar")))))
(is (= '() (rest (-> (c/list) (c/insert node)))))
(is (= (list node) (rest (-> (c/list) (c/insert node) (c/append s/root-id "bar")))))
(is (= (list node) (map #(do %) (-> (c/list) (c/insert node))))))
(is (int? (hash (c/list :foo)))))
(comment
(do
(known-idempotent-insert-edge-cases)
(try-to-find-new-idempotent-edge-cases)
(concurrent-runs-stick-together)
(hide-and-show-and-hide-and-show)
(core-cljc-list-protocol-test))
(time
(keep (fn [_] (find-weave-inconsistencies 9))
(range 999)))
(rand-phrase)
(dissoc (rand-weave-of-phrases 3) :cl :insertions)
(def cl (atom (c/list)))
(time (do (doall (repeatedly 200 #(swap! cl insert-rand-node))) nil))
(criterium/quick-bench (do (insert-rand-node @cl) nil))
(criterium/quick-bench (do (c/causal->edn @cl) nil))
(def cl2 (atom (c/list)))
(time (do (doall (repeatedly 5 #(swap! cl2 insert-rand-node))) nil))
(swap! cl2 c/append (first (second (c/get-weave @cl2))) c/hide)
(swap! cl2 c/append (first (second (c/get-weave @cl2))) :causal/h.show)
(c/causal->edn @cl2))
|
[
{
"context": "e.core/quote\")\n (m \"https://8thlight.com/blog/colin-jones/2012/05/22/quoting-without-confusion.html\")\n (m ",
"end": 1320,
"score": 0.704882800579071,
"start": 1312,
"tag": "USERNAME",
"value": "in-jones"
},
{
"context": " (a (def john (merge person-class {:first-name \"John\" :last-name \"Smith\"})))\r\n (a \"(defmacro call [th",
"end": 5817,
"score": 0.9998388886451721,
"start": 5813,
"tag": "NAME",
"value": "John"
},
{
"context": "rge person-class {:first-name \"John\" :last-name \"Smith\"})))\r\n (a \"(defmacro call [this method & xs] `(l",
"end": 5836,
"score": 0.9997263550758362,
"start": 5831,
"tag": "NAME",
"value": "Smith"
},
{
"context": "s# ~@xs)))\")\r\n (a (= (call john :get-full-name) \"John Smith\"))\r\n (m \"https://stackoverflow.com/questions/502",
"end": 5983,
"score": 0.9985960721969604,
"start": 5973,
"tag": "NAME",
"value": "John Smith"
}
] | src/test/clojure/pl/tomaszgigiel/quizzes/packs/macro_test.clj | tomaszgigiel/quizzes | 1 | (ns pl.tomaszgigiel.quizzes.packs.macro-test
(:require [clojure.test :as tst])
(:require [pl.tomaszgigiel.quizzes.test-config :as test-config])
(:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a at m]])
(:require [pl.tomaszgigiel.utils.misc :as misc]))
(tst/use-fixtures :once test-config/once-fixture)
(tst/use-fixtures :each test-config/each-fixture)
(qam
(q "What is the difference between a quote and a syntax quote?")
(q "What is the difference between \"'\" and \"`\"?")
(a "the single-quote operator:")
(a (= '(+ 1 2) (read-string "(+ 1 2)")) "1. yields the unevaluated form")
(a (= (let [x 1] '(+ ~x 2)) (read-string "(+ (clojure.core/unquote x) 2)")) "2. is not canceled out by the syntax-unquote operator")
(a (= (read-string "'(+ 1 2)") (read-string "(quote (+ 1 2))")) "3. syntax sugar")
(a "the syntax-quote operator:")
(a (= `(+ 1 2) (read-string "(clojure.core/+ 1 2)")) "1. yields the unevaluated form (with namespaces added)")
(a (= (let [x 1] `(+ ~x 2)) (read-string "(clojure.core/+ 1 2)")) "2. is canceled out by the syntax-unquote operator")
(a "3. no syntax sugar")
(m "https://cljs.github.io/api/syntax/quote")
(m "https://cljs.github.io/api/syntax/syntax-quote")
(m "https://clojuredocs.org/clojure.core/quote")
(m "https://8thlight.com/blog/colin-jones/2012/05/22/quoting-without-confusion.html")
(m "https://stackoverflow.com/questions/26485514/clojure-difference-between-quote-and-syntax-quote"))
(qam
(q "Discuss unquote.")
(q "Discuss \"~\".")
(a (= (let [x 1] `(+ ~x ~(dec 2))) (read-string "(clojure.core/+ 1 1)")) "is canceled out only by the syntax-unquote operator")
(m "https://clojuredocs.org/clojure.core/unquote"))
(qam
(q "Discuss unquote-splicing.")
(q "Discuss \"@\" (vector).")
(a (= (let [x `(2 3)] `(1 ~x)) (read-string "(1 (2 3))")))
(a (= (let [x `(2 3)] `(1 ~@x)) (read-string "(1 2 3)")))
(a (= `(1 ~@{2 3 4 5} 6) (read-string "(1 [2 3] [4 5] 6)")))
(m "https://clojuredocs.org/clojure.core/unquote-splicing"))
(qam
(q "Discuss unquote-splicing (map, e.g. `{1 2 ~@[3 4]}).")
(q "Discuss \"@\" (map).")
(a (= (try (eval (read-string "`{1 2 ~@[3 4]}")) (catch java.lang.RuntimeException e "error in clojure")) "error in clojure"))
(a (= `(hash-map 1 2 ~@[3 4]) (read-string "(clojure.core/hash-map 1 2 3 4)")) "workaround")
(a (= `{1 ~@[2 3] 4 ~@[5 6]} {1 2 3 4 5 6}) "ok, an even number of forms")
(m "https://clojuredocs.org/clojure.core/unquote-splicing"))
(qam
(q "List the macro hidden arguments.")
(a "&env")
(a "&form")
(a "inside the body of defmacro you can call it to get an information")
(m "https://dzone.com/articles/clojure-env-and-form"))
(defmacro show-env-keyword [] (mapv (fn [x] [(keyword x) x]) (keys &env)))
(defmacro show-env-string [] (mapv (fn [x] [(.name x) (.sym x)]) (vals &env)))
(qam
(q "Discuss the macro hidden argument &env.")
(a "(defmacro show-env-keyword [] (mapv (fn [x] [(keyword x) x]) (keys &env)))")
(a (= (show-env-keyword) []))
(a (= (let [foo 1 boo 2] (show-env-keyword)) [[:foo 1] [:boo 2]]))
(a "(defmacro show-env-string [] (mapv (fn [x] [(.name x) (.sym x)]) (vals &env)))")
(a (= (let [foo 1 boo 2] (show-env-string)) [["foo" 1] ["boo" 2]]))
(m "https://dzone.com/articles/clojure-env-and-form")
(m "https://www.javadoc.io/doc/org.clojure/clojure/latest/clojure/lang/Compiler.LocalBinding.html"))
(defmacro show-env [] (mapv (fn [x] [(class x) (name x) x]) (keys &env)))
(qam
(q "Discuss the macro hidden argument &env (how to return symbol?).")
(a "(defmacro show-env [] (mapv (fn [x] [(class x) (name x) x]) (keys &env)))")
(a (= (let [foo 1 boo 2] (show-env)) [[clojure.lang.Symbol "foo" 1] [clojure.lang.Symbol "boo" 2]]))
(m "https://dzone.com/articles/clojure-env-and-form"))
(defmacro show-form [x y z] (reduce conj [(name (first &form))] (rest &form)))
(qam
(q "Discuss the macro hidden argument &form.")
(a "(defmacro show-form [x y z] (reduce conj [(name (first &form))] (rest &form)))")
(a (= (show-form 1 2 3) ["show-form" 1 2 3]))
(m "https://dzone.com/articles/clojure-env-and-form"))
(defmacro multi-arity-macro
([] `(multi-arity-macro 0))
([a] `(multi-arity-macro ~a 1))
([a b] `(multi-arity-macro ~a ~b 2))
([a b c] `[~a ~b ~c 3]))
(qam
(q "Discuss the multi-arity macro. (macro)")
(a "(defmacro multi-arity-macro")
(a "([] `(multi-arity-macro 0))")
(a "([a] `(multi-arity-macro ~a 1))")
(a "([a b] `(multi-arity-macro ~a ~b 2))")
(a "([a b c] `[~a ~b ~c 3]))")
(a ( = (multi-arity-macro) [0 1 2 3]))
(a ( = (multi-arity-macro \a) [\a 1 2 3]))
(m "https://stackoverflow.com/questions/25566146/multiple-arity-in-defmacro-of-clojure/25569059"))
(defn- multi-arity-function
([] (multi-arity-function 0))
([a] (multi-arity-function a 1))
([a b] (multi-arity-function a b 2))
([a b c] `[ ~a ~b ~c 3]))
(defmacro multi-arity-macro [& args] (apply multi-arity-function args))
(qam
(q "Discuss the multi-arity macro. (fun)")
(a "(defn- multi-arity-function")
(a "([] (multi-arity-function 0))")
(a "([a] (multi-arity-function a 1))")
(a "([a b] (multi-arity-function a b 2))")
(a "([a b c] `[ ~a ~b ~c 3]))")
(a "(defmacro multi-arity-macro [& args] (apply multi-arity-function args))")
(a ( = (multi-arity-macro) [0 1 2 3]))
(a ( = (multi-arity-macro \a) [\a 1 2 3]))
(m "https://stackoverflow.com/questions/25566146/multiple-arity-in-defmacro-of-clojure/25569059"))
(a (defmacro call [this method & xs] `(let [this# ~this] ((~method this#) this# ~@xs))))
(qam
(q "Why did the exception occur?")
(a (def person-class {:get-full-name (fn [this] (str (:first-name this) " " (:last-name this)))}))
(a (def john (merge person-class {:first-name "John" :last-name "Smith"})))
(a "(defmacro call [this method & xs] `(let [this# ~this] ((~method this#) this# ~@xs)))")
(a (= (call john :get-full-name) "John Smith"))
(m "https://stackoverflow.com/questions/5024211/clojure-adding-functions-to-defrecord-without-defining-a-new-protocol"))
(qam
(q "Discuss the macro and clojure.test.")
(a "dfine macro outside clojure.test/deftest"))
| 27806 | (ns pl.tomaszgigiel.quizzes.packs.macro-test
(:require [clojure.test :as tst])
(:require [pl.tomaszgigiel.quizzes.test-config :as test-config])
(:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a at m]])
(:require [pl.tomaszgigiel.utils.misc :as misc]))
(tst/use-fixtures :once test-config/once-fixture)
(tst/use-fixtures :each test-config/each-fixture)
(qam
(q "What is the difference between a quote and a syntax quote?")
(q "What is the difference between \"'\" and \"`\"?")
(a "the single-quote operator:")
(a (= '(+ 1 2) (read-string "(+ 1 2)")) "1. yields the unevaluated form")
(a (= (let [x 1] '(+ ~x 2)) (read-string "(+ (clojure.core/unquote x) 2)")) "2. is not canceled out by the syntax-unquote operator")
(a (= (read-string "'(+ 1 2)") (read-string "(quote (+ 1 2))")) "3. syntax sugar")
(a "the syntax-quote operator:")
(a (= `(+ 1 2) (read-string "(clojure.core/+ 1 2)")) "1. yields the unevaluated form (with namespaces added)")
(a (= (let [x 1] `(+ ~x 2)) (read-string "(clojure.core/+ 1 2)")) "2. is canceled out by the syntax-unquote operator")
(a "3. no syntax sugar")
(m "https://cljs.github.io/api/syntax/quote")
(m "https://cljs.github.io/api/syntax/syntax-quote")
(m "https://clojuredocs.org/clojure.core/quote")
(m "https://8thlight.com/blog/colin-jones/2012/05/22/quoting-without-confusion.html")
(m "https://stackoverflow.com/questions/26485514/clojure-difference-between-quote-and-syntax-quote"))
(qam
(q "Discuss unquote.")
(q "Discuss \"~\".")
(a (= (let [x 1] `(+ ~x ~(dec 2))) (read-string "(clojure.core/+ 1 1)")) "is canceled out only by the syntax-unquote operator")
(m "https://clojuredocs.org/clojure.core/unquote"))
(qam
(q "Discuss unquote-splicing.")
(q "Discuss \"@\" (vector).")
(a (= (let [x `(2 3)] `(1 ~x)) (read-string "(1 (2 3))")))
(a (= (let [x `(2 3)] `(1 ~@x)) (read-string "(1 2 3)")))
(a (= `(1 ~@{2 3 4 5} 6) (read-string "(1 [2 3] [4 5] 6)")))
(m "https://clojuredocs.org/clojure.core/unquote-splicing"))
(qam
(q "Discuss unquote-splicing (map, e.g. `{1 2 ~@[3 4]}).")
(q "Discuss \"@\" (map).")
(a (= (try (eval (read-string "`{1 2 ~@[3 4]}")) (catch java.lang.RuntimeException e "error in clojure")) "error in clojure"))
(a (= `(hash-map 1 2 ~@[3 4]) (read-string "(clojure.core/hash-map 1 2 3 4)")) "workaround")
(a (= `{1 ~@[2 3] 4 ~@[5 6]} {1 2 3 4 5 6}) "ok, an even number of forms")
(m "https://clojuredocs.org/clojure.core/unquote-splicing"))
(qam
(q "List the macro hidden arguments.")
(a "&env")
(a "&form")
(a "inside the body of defmacro you can call it to get an information")
(m "https://dzone.com/articles/clojure-env-and-form"))
(defmacro show-env-keyword [] (mapv (fn [x] [(keyword x) x]) (keys &env)))
(defmacro show-env-string [] (mapv (fn [x] [(.name x) (.sym x)]) (vals &env)))
(qam
(q "Discuss the macro hidden argument &env.")
(a "(defmacro show-env-keyword [] (mapv (fn [x] [(keyword x) x]) (keys &env)))")
(a (= (show-env-keyword) []))
(a (= (let [foo 1 boo 2] (show-env-keyword)) [[:foo 1] [:boo 2]]))
(a "(defmacro show-env-string [] (mapv (fn [x] [(.name x) (.sym x)]) (vals &env)))")
(a (= (let [foo 1 boo 2] (show-env-string)) [["foo" 1] ["boo" 2]]))
(m "https://dzone.com/articles/clojure-env-and-form")
(m "https://www.javadoc.io/doc/org.clojure/clojure/latest/clojure/lang/Compiler.LocalBinding.html"))
(defmacro show-env [] (mapv (fn [x] [(class x) (name x) x]) (keys &env)))
(qam
(q "Discuss the macro hidden argument &env (how to return symbol?).")
(a "(defmacro show-env [] (mapv (fn [x] [(class x) (name x) x]) (keys &env)))")
(a (= (let [foo 1 boo 2] (show-env)) [[clojure.lang.Symbol "foo" 1] [clojure.lang.Symbol "boo" 2]]))
(m "https://dzone.com/articles/clojure-env-and-form"))
(defmacro show-form [x y z] (reduce conj [(name (first &form))] (rest &form)))
(qam
(q "Discuss the macro hidden argument &form.")
(a "(defmacro show-form [x y z] (reduce conj [(name (first &form))] (rest &form)))")
(a (= (show-form 1 2 3) ["show-form" 1 2 3]))
(m "https://dzone.com/articles/clojure-env-and-form"))
(defmacro multi-arity-macro
([] `(multi-arity-macro 0))
([a] `(multi-arity-macro ~a 1))
([a b] `(multi-arity-macro ~a ~b 2))
([a b c] `[~a ~b ~c 3]))
(qam
(q "Discuss the multi-arity macro. (macro)")
(a "(defmacro multi-arity-macro")
(a "([] `(multi-arity-macro 0))")
(a "([a] `(multi-arity-macro ~a 1))")
(a "([a b] `(multi-arity-macro ~a ~b 2))")
(a "([a b c] `[~a ~b ~c 3]))")
(a ( = (multi-arity-macro) [0 1 2 3]))
(a ( = (multi-arity-macro \a) [\a 1 2 3]))
(m "https://stackoverflow.com/questions/25566146/multiple-arity-in-defmacro-of-clojure/25569059"))
(defn- multi-arity-function
([] (multi-arity-function 0))
([a] (multi-arity-function a 1))
([a b] (multi-arity-function a b 2))
([a b c] `[ ~a ~b ~c 3]))
(defmacro multi-arity-macro [& args] (apply multi-arity-function args))
(qam
(q "Discuss the multi-arity macro. (fun)")
(a "(defn- multi-arity-function")
(a "([] (multi-arity-function 0))")
(a "([a] (multi-arity-function a 1))")
(a "([a b] (multi-arity-function a b 2))")
(a "([a b c] `[ ~a ~b ~c 3]))")
(a "(defmacro multi-arity-macro [& args] (apply multi-arity-function args))")
(a ( = (multi-arity-macro) [0 1 2 3]))
(a ( = (multi-arity-macro \a) [\a 1 2 3]))
(m "https://stackoverflow.com/questions/25566146/multiple-arity-in-defmacro-of-clojure/25569059"))
(a (defmacro call [this method & xs] `(let [this# ~this] ((~method this#) this# ~@xs))))
(qam
(q "Why did the exception occur?")
(a (def person-class {:get-full-name (fn [this] (str (:first-name this) " " (:last-name this)))}))
(a (def john (merge person-class {:first-name "<NAME>" :last-name "<NAME>"})))
(a "(defmacro call [this method & xs] `(let [this# ~this] ((~method this#) this# ~@xs)))")
(a (= (call john :get-full-name) "<NAME>"))
(m "https://stackoverflow.com/questions/5024211/clojure-adding-functions-to-defrecord-without-defining-a-new-protocol"))
(qam
(q "Discuss the macro and clojure.test.")
(a "dfine macro outside clojure.test/deftest"))
| true | (ns pl.tomaszgigiel.quizzes.packs.macro-test
(:require [clojure.test :as tst])
(:require [pl.tomaszgigiel.quizzes.test-config :as test-config])
(:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a at m]])
(:require [pl.tomaszgigiel.utils.misc :as misc]))
(tst/use-fixtures :once test-config/once-fixture)
(tst/use-fixtures :each test-config/each-fixture)
(qam
(q "What is the difference between a quote and a syntax quote?")
(q "What is the difference between \"'\" and \"`\"?")
(a "the single-quote operator:")
(a (= '(+ 1 2) (read-string "(+ 1 2)")) "1. yields the unevaluated form")
(a (= (let [x 1] '(+ ~x 2)) (read-string "(+ (clojure.core/unquote x) 2)")) "2. is not canceled out by the syntax-unquote operator")
(a (= (read-string "'(+ 1 2)") (read-string "(quote (+ 1 2))")) "3. syntax sugar")
(a "the syntax-quote operator:")
(a (= `(+ 1 2) (read-string "(clojure.core/+ 1 2)")) "1. yields the unevaluated form (with namespaces added)")
(a (= (let [x 1] `(+ ~x 2)) (read-string "(clojure.core/+ 1 2)")) "2. is canceled out by the syntax-unquote operator")
(a "3. no syntax sugar")
(m "https://cljs.github.io/api/syntax/quote")
(m "https://cljs.github.io/api/syntax/syntax-quote")
(m "https://clojuredocs.org/clojure.core/quote")
(m "https://8thlight.com/blog/colin-jones/2012/05/22/quoting-without-confusion.html")
(m "https://stackoverflow.com/questions/26485514/clojure-difference-between-quote-and-syntax-quote"))
(qam
(q "Discuss unquote.")
(q "Discuss \"~\".")
(a (= (let [x 1] `(+ ~x ~(dec 2))) (read-string "(clojure.core/+ 1 1)")) "is canceled out only by the syntax-unquote operator")
(m "https://clojuredocs.org/clojure.core/unquote"))
(qam
(q "Discuss unquote-splicing.")
(q "Discuss \"@\" (vector).")
(a (= (let [x `(2 3)] `(1 ~x)) (read-string "(1 (2 3))")))
(a (= (let [x `(2 3)] `(1 ~@x)) (read-string "(1 2 3)")))
(a (= `(1 ~@{2 3 4 5} 6) (read-string "(1 [2 3] [4 5] 6)")))
(m "https://clojuredocs.org/clojure.core/unquote-splicing"))
(qam
(q "Discuss unquote-splicing (map, e.g. `{1 2 ~@[3 4]}).")
(q "Discuss \"@\" (map).")
(a (= (try (eval (read-string "`{1 2 ~@[3 4]}")) (catch java.lang.RuntimeException e "error in clojure")) "error in clojure"))
(a (= `(hash-map 1 2 ~@[3 4]) (read-string "(clojure.core/hash-map 1 2 3 4)")) "workaround")
(a (= `{1 ~@[2 3] 4 ~@[5 6]} {1 2 3 4 5 6}) "ok, an even number of forms")
(m "https://clojuredocs.org/clojure.core/unquote-splicing"))
(qam
(q "List the macro hidden arguments.")
(a "&env")
(a "&form")
(a "inside the body of defmacro you can call it to get an information")
(m "https://dzone.com/articles/clojure-env-and-form"))
(defmacro show-env-keyword [] (mapv (fn [x] [(keyword x) x]) (keys &env)))
(defmacro show-env-string [] (mapv (fn [x] [(.name x) (.sym x)]) (vals &env)))
(qam
(q "Discuss the macro hidden argument &env.")
(a "(defmacro show-env-keyword [] (mapv (fn [x] [(keyword x) x]) (keys &env)))")
(a (= (show-env-keyword) []))
(a (= (let [foo 1 boo 2] (show-env-keyword)) [[:foo 1] [:boo 2]]))
(a "(defmacro show-env-string [] (mapv (fn [x] [(.name x) (.sym x)]) (vals &env)))")
(a (= (let [foo 1 boo 2] (show-env-string)) [["foo" 1] ["boo" 2]]))
(m "https://dzone.com/articles/clojure-env-and-form")
(m "https://www.javadoc.io/doc/org.clojure/clojure/latest/clojure/lang/Compiler.LocalBinding.html"))
(defmacro show-env [] (mapv (fn [x] [(class x) (name x) x]) (keys &env)))
(qam
(q "Discuss the macro hidden argument &env (how to return symbol?).")
(a "(defmacro show-env [] (mapv (fn [x] [(class x) (name x) x]) (keys &env)))")
(a (= (let [foo 1 boo 2] (show-env)) [[clojure.lang.Symbol "foo" 1] [clojure.lang.Symbol "boo" 2]]))
(m "https://dzone.com/articles/clojure-env-and-form"))
(defmacro show-form [x y z] (reduce conj [(name (first &form))] (rest &form)))
(qam
(q "Discuss the macro hidden argument &form.")
(a "(defmacro show-form [x y z] (reduce conj [(name (first &form))] (rest &form)))")
(a (= (show-form 1 2 3) ["show-form" 1 2 3]))
(m "https://dzone.com/articles/clojure-env-and-form"))
(defmacro multi-arity-macro
([] `(multi-arity-macro 0))
([a] `(multi-arity-macro ~a 1))
([a b] `(multi-arity-macro ~a ~b 2))
([a b c] `[~a ~b ~c 3]))
(qam
(q "Discuss the multi-arity macro. (macro)")
(a "(defmacro multi-arity-macro")
(a "([] `(multi-arity-macro 0))")
(a "([a] `(multi-arity-macro ~a 1))")
(a "([a b] `(multi-arity-macro ~a ~b 2))")
(a "([a b c] `[~a ~b ~c 3]))")
(a ( = (multi-arity-macro) [0 1 2 3]))
(a ( = (multi-arity-macro \a) [\a 1 2 3]))
(m "https://stackoverflow.com/questions/25566146/multiple-arity-in-defmacro-of-clojure/25569059"))
(defn- multi-arity-function
([] (multi-arity-function 0))
([a] (multi-arity-function a 1))
([a b] (multi-arity-function a b 2))
([a b c] `[ ~a ~b ~c 3]))
(defmacro multi-arity-macro [& args] (apply multi-arity-function args))
(qam
(q "Discuss the multi-arity macro. (fun)")
(a "(defn- multi-arity-function")
(a "([] (multi-arity-function 0))")
(a "([a] (multi-arity-function a 1))")
(a "([a b] (multi-arity-function a b 2))")
(a "([a b c] `[ ~a ~b ~c 3]))")
(a "(defmacro multi-arity-macro [& args] (apply multi-arity-function args))")
(a ( = (multi-arity-macro) [0 1 2 3]))
(a ( = (multi-arity-macro \a) [\a 1 2 3]))
(m "https://stackoverflow.com/questions/25566146/multiple-arity-in-defmacro-of-clojure/25569059"))
(a (defmacro call [this method & xs] `(let [this# ~this] ((~method this#) this# ~@xs))))
(qam
(q "Why did the exception occur?")
(a (def person-class {:get-full-name (fn [this] (str (:first-name this) " " (:last-name this)))}))
(a (def john (merge person-class {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"})))
(a "(defmacro call [this method & xs] `(let [this# ~this] ((~method this#) this# ~@xs)))")
(a (= (call john :get-full-name) "PI:NAME:<NAME>END_PI"))
(m "https://stackoverflow.com/questions/5024211/clojure-adding-functions-to-defrecord-without-defining-a-new-protocol"))
(qam
(q "Discuss the macro and clojure.test.")
(a "dfine macro outside clojure.test/deftest"))
|
[
{
"context": " (fix/submit+await-tx [[::xt/fn :put-ivan {:name \"Ivan\"}]])\n\n (t/is (= {:xt/id :ivan, :name \"Ivan\"}",
"end": 2400,
"score": 0.9834529757499695,
"start": 2396,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " \"Ivan\"}]])\n\n (t/is (= {:xt/id :ivan, :name \"Ivan\"}\n (xt/entity (xt/db *api*) :ivan))",
"end": 2448,
"score": 0.9909305572509766,
"start": 2444,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "cluster-node\n (t/is (= {:xt/id :ivan, :name \"Ivan\"}\n (xt/entity (xt/db *api*) :ivan))",
"end": 2566,
"score": 0.9830586910247803,
"start": 2562,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "bmit+await-tx [[::xt/fn :put-bob-and-ivan {:name \"Bob\"} {:name \"Ivan2\"}]])\n\n (t/is (= {:xt/id :i",
"end": 3863,
"score": 0.999549925327301,
"start": 3860,
"tag": "NAME",
"value": "Bob"
},
{
"context": "[[::xt/fn :put-bob-and-ivan {:name \"Bob\"} {:name \"Ivan2\"}]])\n\n (t/is (= {:xt/id :ivan, :name \"Ivan",
"end": 3879,
"score": 0.9996010661125183,
"start": 3874,
"tag": "NAME",
"value": "Ivan2"
},
{
"context": "van2\"}]])\n\n (t/is (= {:xt/id :ivan, :name \"Ivan2\"}\n (xt/entity (xt/db *api*) :ivan",
"end": 3930,
"score": 0.9994626641273499,
"start": 3925,
"tag": "NAME",
"value": "Ivan2"
},
{
"context": ") :ivan)))\n\n (t/is (= {:xt/id :bob, :name \"Bob\"}\n (xt/entity (xt/db *api*) :bob)",
"end": 4026,
"score": 0.9995808601379395,
"start": 4023,
"tag": "NAME",
"value": "Bob"
},
{
"context": "uster-node\n (t/is (= {:xt/id :ivan, :name \"Ivan2\"}\n (xt/entity (xt/db *api*) :ivan",
"end": 4150,
"score": 0.9993720054626465,
"start": 4145,
"tag": "NAME",
"value": "Ivan2"
},
{
"context": ") :ivan)))\n\n (t/is (= {:xt/id :bob, :name \"Bob\"}\n (xt/entity (xt/db *api*) :bob)",
"end": 4246,
"score": 0.9996391534805298,
"start": 4243,
"tag": "NAME",
"value": "Bob"
},
{
"context": " (fix/submit+await-tx [[::xt/fn :put-petr {:name \"Petr\"}]])\n\n (t/is (nil? (xt/entity (xt/db *api*",
"end": 4435,
"score": 0.9928008913993835,
"start": 4431,
"tag": "NAME",
"value": "Petr"
}
] | test/test/xtdb/replay_test.clj | aleksandersumowski/xtdb | 1,500 | (ns xtdb.replay-test
(:require [clojure.java.io :as io]
[clojure.test :as t]
[xtdb.api :as xt]
[xtdb.db :as db]
[xtdb.fixtures :as fix :refer [*api*]]
[xtdb.rocksdb :as rocks]))
(def ^:private ^:dynamic *event-log-dir*)
(defn- with-cluster* [f]
(fix/with-tmp-dir "event-log-dir" [event-log-dir]
(binding [*event-log-dir* event-log-dir]
(f))))
(defmacro with-cluster [& body]
`(with-cluster* (fn [] ~@body)))
(defn- with-cluster-node* [f]
(fix/with-tmp-dir "db-dir" [db-dir]
(with-open [node (xt/start-node {:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store,
:db-dir (io/file *event-log-dir* "doc-store")}}
:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store,
:db-dir (io/file *event-log-dir* "tx-log")}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store,
:db-dir db-dir}}})]
(binding [*api* node]
(xt/sync node)
(f)))))
(defmacro with-cluster-node [& body]
`(with-cluster-node* (fn [] ~@body)))
(t/deftest drop-db
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :hello}]]))
(with-cluster-node
(t/is (= {::xt/tx-id 0}
(xt/latest-submitted-tx *api*)))
(t/is (= {:xt/id :hello}
(xt/entity (xt/db *api*) :hello))))))
(t/deftest test-more-txs
(let [n 1000]
(with-cluster
(with-cluster-node
(dotimes [x n]
(fix/submit+await-tx [[::xt/put {:xt/id (str "id-" x)}]])))
(with-cluster-node
(t/is (= {::xt/tx-id (dec n)}
(xt/latest-submitted-tx *api*)))
(t/is (= n
(count (xt/q (xt/db *api*) '{:find [?e]
:where [[?e :xt/id]]}))))))))
(t/deftest replaces-tx-fn-arg-docs
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :put-ivan
:xt/fn '(fn [ctx doc]
[[::xt/put (assoc doc :xt/id :ivan)]])}]])
(fix/submit+await-tx [[::xt/fn :put-ivan {:name "Ivan"}]])
(t/is (= {:xt/id :ivan, :name "Ivan"}
(xt/entity (xt/db *api*) :ivan))))
(with-cluster-node
(t/is (= {:xt/id :ivan, :name "Ivan"}
(xt/entity (xt/db *api*) :ivan)))))
(t/testing "replaces fn with no args"
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :no-args
:xt/fn '(fn [ctx]
[[::xt/put {:xt/id :no-fn-args-doc}]])}]])
(fix/submit+await-tx [[::xt/fn :no-args]])
(t/is (= {:xt/id :no-fn-args-doc}
(xt/entity (xt/db *api*) :no-fn-args-doc))))
(with-cluster-node
(t/is (= {:xt/id :no-fn-args-doc}
(xt/entity (xt/db *api*) :no-fn-args-doc))))))
(t/testing "nested tx-fn"
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :put-ivan
:xt/fn '(fn [ctx doc]
[[::xt/put (assoc doc :xt/id :ivan)]])}]])
(fix/submit+await-tx [[::xt/put {:xt/id :put-bob-and-ivan
:xt/fn '(fn [ctx bob ivan]
[[::xt/put (assoc bob :xt/id :bob)]
[::xt/fn :put-ivan ivan]])}]])
(fix/submit+await-tx [[::xt/fn :put-bob-and-ivan {:name "Bob"} {:name "Ivan2"}]])
(t/is (= {:xt/id :ivan, :name "Ivan2"}
(xt/entity (xt/db *api*) :ivan)))
(t/is (= {:xt/id :bob, :name "Bob"}
(xt/entity (xt/db *api*) :bob))))
(with-cluster-node
(t/is (= {:xt/id :ivan, :name "Ivan2"}
(xt/entity (xt/db *api*) :ivan)))
(t/is (= {:xt/id :bob, :name "Bob"}
(xt/entity (xt/db *api*) :bob))))))
(t/testing "failed tx-fn"
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/fn :put-petr {:name "Petr"}]])
(t/is (nil? (xt/entity (xt/db *api*) :petr)))
(fix/submit+await-tx [[::xt/put {:xt/id :foo}]])
(t/is (= {:xt/id :foo}
(xt/entity (xt/db *api*) :foo))))
(with-cluster-node
(t/is (nil? (xt/entity (xt/db *api*) :petr)))
(t/is (= {:xt/id :foo}
(xt/entity (xt/db *api*) :foo)))))))
| 94567 | (ns xtdb.replay-test
(:require [clojure.java.io :as io]
[clojure.test :as t]
[xtdb.api :as xt]
[xtdb.db :as db]
[xtdb.fixtures :as fix :refer [*api*]]
[xtdb.rocksdb :as rocks]))
(def ^:private ^:dynamic *event-log-dir*)
(defn- with-cluster* [f]
(fix/with-tmp-dir "event-log-dir" [event-log-dir]
(binding [*event-log-dir* event-log-dir]
(f))))
(defmacro with-cluster [& body]
`(with-cluster* (fn [] ~@body)))
(defn- with-cluster-node* [f]
(fix/with-tmp-dir "db-dir" [db-dir]
(with-open [node (xt/start-node {:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store,
:db-dir (io/file *event-log-dir* "doc-store")}}
:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store,
:db-dir (io/file *event-log-dir* "tx-log")}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store,
:db-dir db-dir}}})]
(binding [*api* node]
(xt/sync node)
(f)))))
(defmacro with-cluster-node [& body]
`(with-cluster-node* (fn [] ~@body)))
(t/deftest drop-db
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :hello}]]))
(with-cluster-node
(t/is (= {::xt/tx-id 0}
(xt/latest-submitted-tx *api*)))
(t/is (= {:xt/id :hello}
(xt/entity (xt/db *api*) :hello))))))
(t/deftest test-more-txs
(let [n 1000]
(with-cluster
(with-cluster-node
(dotimes [x n]
(fix/submit+await-tx [[::xt/put {:xt/id (str "id-" x)}]])))
(with-cluster-node
(t/is (= {::xt/tx-id (dec n)}
(xt/latest-submitted-tx *api*)))
(t/is (= n
(count (xt/q (xt/db *api*) '{:find [?e]
:where [[?e :xt/id]]}))))))))
(t/deftest replaces-tx-fn-arg-docs
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :put-ivan
:xt/fn '(fn [ctx doc]
[[::xt/put (assoc doc :xt/id :ivan)]])}]])
(fix/submit+await-tx [[::xt/fn :put-ivan {:name "<NAME>"}]])
(t/is (= {:xt/id :ivan, :name "<NAME>"}
(xt/entity (xt/db *api*) :ivan))))
(with-cluster-node
(t/is (= {:xt/id :ivan, :name "<NAME>"}
(xt/entity (xt/db *api*) :ivan)))))
(t/testing "replaces fn with no args"
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :no-args
:xt/fn '(fn [ctx]
[[::xt/put {:xt/id :no-fn-args-doc}]])}]])
(fix/submit+await-tx [[::xt/fn :no-args]])
(t/is (= {:xt/id :no-fn-args-doc}
(xt/entity (xt/db *api*) :no-fn-args-doc))))
(with-cluster-node
(t/is (= {:xt/id :no-fn-args-doc}
(xt/entity (xt/db *api*) :no-fn-args-doc))))))
(t/testing "nested tx-fn"
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :put-ivan
:xt/fn '(fn [ctx doc]
[[::xt/put (assoc doc :xt/id :ivan)]])}]])
(fix/submit+await-tx [[::xt/put {:xt/id :put-bob-and-ivan
:xt/fn '(fn [ctx bob ivan]
[[::xt/put (assoc bob :xt/id :bob)]
[::xt/fn :put-ivan ivan]])}]])
(fix/submit+await-tx [[::xt/fn :put-bob-and-ivan {:name "<NAME>"} {:name "<NAME>"}]])
(t/is (= {:xt/id :ivan, :name "<NAME>"}
(xt/entity (xt/db *api*) :ivan)))
(t/is (= {:xt/id :bob, :name "<NAME>"}
(xt/entity (xt/db *api*) :bob))))
(with-cluster-node
(t/is (= {:xt/id :ivan, :name "<NAME>"}
(xt/entity (xt/db *api*) :ivan)))
(t/is (= {:xt/id :bob, :name "<NAME>"}
(xt/entity (xt/db *api*) :bob))))))
(t/testing "failed tx-fn"
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/fn :put-petr {:name "<NAME>"}]])
(t/is (nil? (xt/entity (xt/db *api*) :petr)))
(fix/submit+await-tx [[::xt/put {:xt/id :foo}]])
(t/is (= {:xt/id :foo}
(xt/entity (xt/db *api*) :foo))))
(with-cluster-node
(t/is (nil? (xt/entity (xt/db *api*) :petr)))
(t/is (= {:xt/id :foo}
(xt/entity (xt/db *api*) :foo)))))))
| true | (ns xtdb.replay-test
(:require [clojure.java.io :as io]
[clojure.test :as t]
[xtdb.api :as xt]
[xtdb.db :as db]
[xtdb.fixtures :as fix :refer [*api*]]
[xtdb.rocksdb :as rocks]))
(def ^:private ^:dynamic *event-log-dir*)
(defn- with-cluster* [f]
(fix/with-tmp-dir "event-log-dir" [event-log-dir]
(binding [*event-log-dir* event-log-dir]
(f))))
(defmacro with-cluster [& body]
`(with-cluster* (fn [] ~@body)))
(defn- with-cluster-node* [f]
(fix/with-tmp-dir "db-dir" [db-dir]
(with-open [node (xt/start-node {:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store,
:db-dir (io/file *event-log-dir* "doc-store")}}
:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store,
:db-dir (io/file *event-log-dir* "tx-log")}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store,
:db-dir db-dir}}})]
(binding [*api* node]
(xt/sync node)
(f)))))
(defmacro with-cluster-node [& body]
`(with-cluster-node* (fn [] ~@body)))
(t/deftest drop-db
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :hello}]]))
(with-cluster-node
(t/is (= {::xt/tx-id 0}
(xt/latest-submitted-tx *api*)))
(t/is (= {:xt/id :hello}
(xt/entity (xt/db *api*) :hello))))))
(t/deftest test-more-txs
(let [n 1000]
(with-cluster
(with-cluster-node
(dotimes [x n]
(fix/submit+await-tx [[::xt/put {:xt/id (str "id-" x)}]])))
(with-cluster-node
(t/is (= {::xt/tx-id (dec n)}
(xt/latest-submitted-tx *api*)))
(t/is (= n
(count (xt/q (xt/db *api*) '{:find [?e]
:where [[?e :xt/id]]}))))))))
(t/deftest replaces-tx-fn-arg-docs
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :put-ivan
:xt/fn '(fn [ctx doc]
[[::xt/put (assoc doc :xt/id :ivan)]])}]])
(fix/submit+await-tx [[::xt/fn :put-ivan {:name "PI:NAME:<NAME>END_PI"}]])
(t/is (= {:xt/id :ivan, :name "PI:NAME:<NAME>END_PI"}
(xt/entity (xt/db *api*) :ivan))))
(with-cluster-node
(t/is (= {:xt/id :ivan, :name "PI:NAME:<NAME>END_PI"}
(xt/entity (xt/db *api*) :ivan)))))
(t/testing "replaces fn with no args"
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :no-args
:xt/fn '(fn [ctx]
[[::xt/put {:xt/id :no-fn-args-doc}]])}]])
(fix/submit+await-tx [[::xt/fn :no-args]])
(t/is (= {:xt/id :no-fn-args-doc}
(xt/entity (xt/db *api*) :no-fn-args-doc))))
(with-cluster-node
(t/is (= {:xt/id :no-fn-args-doc}
(xt/entity (xt/db *api*) :no-fn-args-doc))))))
(t/testing "nested tx-fn"
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/put {:xt/id :put-ivan
:xt/fn '(fn [ctx doc]
[[::xt/put (assoc doc :xt/id :ivan)]])}]])
(fix/submit+await-tx [[::xt/put {:xt/id :put-bob-and-ivan
:xt/fn '(fn [ctx bob ivan]
[[::xt/put (assoc bob :xt/id :bob)]
[::xt/fn :put-ivan ivan]])}]])
(fix/submit+await-tx [[::xt/fn :put-bob-and-ivan {:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}]])
(t/is (= {:xt/id :ivan, :name "PI:NAME:<NAME>END_PI"}
(xt/entity (xt/db *api*) :ivan)))
(t/is (= {:xt/id :bob, :name "PI:NAME:<NAME>END_PI"}
(xt/entity (xt/db *api*) :bob))))
(with-cluster-node
(t/is (= {:xt/id :ivan, :name "PI:NAME:<NAME>END_PI"}
(xt/entity (xt/db *api*) :ivan)))
(t/is (= {:xt/id :bob, :name "PI:NAME:<NAME>END_PI"}
(xt/entity (xt/db *api*) :bob))))))
(t/testing "failed tx-fn"
(with-cluster
(with-cluster-node
(fix/submit+await-tx [[::xt/fn :put-petr {:name "PI:NAME:<NAME>END_PI"}]])
(t/is (nil? (xt/entity (xt/db *api*) :petr)))
(fix/submit+await-tx [[::xt/put {:xt/id :foo}]])
(t/is (= {:xt/id :foo}
(xt/entity (xt/db *api*) :foo))))
(with-cluster-node
(t/is (nil? (xt/entity (xt/db *api*) :petr)))
(t/is (= {:xt/id :foo}
(xt/entity (xt/db *api*) :foo)))))))
|
[
{
"context": "on/address \"6\" :person/happy? true :person/email \"amiee@nowhere.com\"}\n {:db/id \"2\" :person/id 2 :p",
"end": 1347,
"score": 0.9999291896820068,
"start": 1330,
"tag": "EMAIL",
"value": "amiee@nowhere.com"
},
{
"context": "happy? true :person/children [\"3\"] :person/email \"sam@nowhere.com\"}\n {:db/id \"3\" :person/id 3 :p",
"end": 1468,
"score": 0.9999298453330994,
"start": 1453,
"tag": "EMAIL",
"value": "sam@nowhere.com"
},
{
"context": "on/address \"5\" :person/happy? true :person/email \"sally@nowhere.com\"}\n {:db/id \"4\" :person/id 4 :p",
"end": 1588,
"score": 0.9999302625656128,
"start": 1571,
"tag": "EMAIL",
"value": "sally@nowhere.com"
},
{
"context": "y? true :person/children [\"1\" \"2\"] :person/email \"grut@nowhere.com\"}\n {:db/id \"5\" :address/id 100",
"end": 1714,
"score": 0.9999298453330994,
"start": 1698,
"tag": "EMAIL",
"value": "grut@nowhere.com"
}
] | src/main/app/model/mock_database.clj | gmp26/fulcro-with-reframe | 0 | (ns app.model.mock-database
"This is a mock database implemented via Datascript, which runs completely in memory, has few deps, and requires
less setup than Datomic itself. Its API is very close to Datomics, and for a demo app makes it possible to have the
*look* of a real back-end without having quite the amount of setup to understand for a beginner."
(:require
[datascript.core :as d]
[mount.core :refer [defstate]]))
;; In datascript just about the only thing that needs schema
;; is lookup refs and entity refs. You can just wing it on
;; everything else.
(def schema {:person/id {:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity}
:address/id {:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity}
:person/address {:db/cardinality :db.cardinality/one
:db/valueType :db.type/ref}
:person/children {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}})
(defn new-database [] (d/create-conn schema))
(defstate conn :start
(let [c (new-database)]
;; Seed some data
(d/transact! c [{:db/id "1" :person/id 1 :person/address "6" :person/happy? true :person/email "amiee@nowhere.com"}
{:db/id "2" :person/id 2 :person/happy? true :person/children ["3"] :person/email "sam@nowhere.com"}
{:db/id "3" :person/id 3 :person/address "5" :person/happy? true :person/email "sally@nowhere.com"}
{:db/id "4" :person/id 4 :person/happy? true :person/children ["1" "2"] :person/email "grut@nowhere.com"}
{:db/id "5" :address/id 100 :address/street "123 Main St" :address/city "New York"}
{:db/id "6" :address/id 101 :address/street "999 Broadway" :address/city "Miami"}])
c))
| 15402 | (ns app.model.mock-database
"This is a mock database implemented via Datascript, which runs completely in memory, has few deps, and requires
less setup than Datomic itself. Its API is very close to Datomics, and for a demo app makes it possible to have the
*look* of a real back-end without having quite the amount of setup to understand for a beginner."
(:require
[datascript.core :as d]
[mount.core :refer [defstate]]))
;; In datascript just about the only thing that needs schema
;; is lookup refs and entity refs. You can just wing it on
;; everything else.
(def schema {:person/id {:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity}
:address/id {:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity}
:person/address {:db/cardinality :db.cardinality/one
:db/valueType :db.type/ref}
:person/children {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}})
(defn new-database [] (d/create-conn schema))
(defstate conn :start
(let [c (new-database)]
;; Seed some data
(d/transact! c [{:db/id "1" :person/id 1 :person/address "6" :person/happy? true :person/email "<EMAIL>"}
{:db/id "2" :person/id 2 :person/happy? true :person/children ["3"] :person/email "<EMAIL>"}
{:db/id "3" :person/id 3 :person/address "5" :person/happy? true :person/email "<EMAIL>"}
{:db/id "4" :person/id 4 :person/happy? true :person/children ["1" "2"] :person/email "<EMAIL>"}
{:db/id "5" :address/id 100 :address/street "123 Main St" :address/city "New York"}
{:db/id "6" :address/id 101 :address/street "999 Broadway" :address/city "Miami"}])
c))
| true | (ns app.model.mock-database
"This is a mock database implemented via Datascript, which runs completely in memory, has few deps, and requires
less setup than Datomic itself. Its API is very close to Datomics, and for a demo app makes it possible to have the
*look* of a real back-end without having quite the amount of setup to understand for a beginner."
(:require
[datascript.core :as d]
[mount.core :refer [defstate]]))
;; In datascript just about the only thing that needs schema
;; is lookup refs and entity refs. You can just wing it on
;; everything else.
(def schema {:person/id {:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity}
:address/id {:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity}
:person/address {:db/cardinality :db.cardinality/one
:db/valueType :db.type/ref}
:person/children {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}})
(defn new-database [] (d/create-conn schema))
(defstate conn :start
(let [c (new-database)]
;; Seed some data
(d/transact! c [{:db/id "1" :person/id 1 :person/address "6" :person/happy? true :person/email "PI:EMAIL:<EMAIL>END_PI"}
{:db/id "2" :person/id 2 :person/happy? true :person/children ["3"] :person/email "PI:EMAIL:<EMAIL>END_PI"}
{:db/id "3" :person/id 3 :person/address "5" :person/happy? true :person/email "PI:EMAIL:<EMAIL>END_PI"}
{:db/id "4" :person/id 4 :person/happy? true :person/children ["1" "2"] :person/email "PI:EMAIL:<EMAIL>END_PI"}
{:db/id "5" :address/id 100 :address/street "123 Main St" :address/city "New York"}
{:db/id "6" :address/id 101 :address/street "999 Broadway" :address/city "Miami"}])
c))
|
[
{
"context": " [& {:keys [character-name] :or {character-name \"Skuld\"}}]\n {:player (mc/new-character character-name\n ",
"end": 581,
"score": 0.7250679731369019,
"start": 576,
"tag": "USERNAME",
"value": "Skuld"
},
{
"context": " :max-hp 100)\n :enemy (mc/new-character \"Goblin\")\n :events [\"Begin!\"]})\n\n(defn alive?\n \"takes ",
"end": 746,
"score": 0.4791942536830902,
"start": 741,
"tag": "NAME",
"value": "oblin"
}
] | src/iron_aether/model/battle.cljs | cayennebob/iron-aether | 1 | (ns ^:figwheel-always iron-aether.model.battle
(:require [iron-aether.model.dice :as dice]
[iron-aether.model.character :as mc]))
;; state etc.
(def default-abilities
[:basic-attack #_:defend #_:heal #_:retreat :no-action #_:fight-again])
#_(defn new-character
[name & {:keys [friendly? max-hp attack defense abilities]}]
{:name name
:max-hp (or max-hp 70)
:hp (or max-hp 70)
:attack (or attack 10)
:defense (or defense 10)
:abilities (or abilities default-abilities)})
(defn new-battle
[& {:keys [character-name] :or {character-name "Skuld"}}]
{:player (mc/new-character character-name
:friendly? true
:max-hp 100)
:enemy (mc/new-character "Goblin")
:events ["Begin!"]})
(defn alive?
"takes a character map and indicates whether the character is alive"
[{:keys [hp]}]
(> hp 0))
(defn combat-state
"combat state of given battle state map"
[{:keys [player enemy]}]
(cond
(not (alive? player)) :lost
(not (alive? enemy)) :won
:else :in-progress))
;; abilities
(defn do-no-action
[battle actor _]
(update-in battle [:events]
#(conj % (str (-> battle actor :name) " does nothing"))))
(defn do-basic-attack
[battle actor target]
(let [roll (dice/basic-roll)
damage (max 0 (+ roll
(-> battle actor :attack)
(* -1 (:defense target))
5))
message (str (-> battle actor :name)
" attacks " (-> battle target :name)
" for " damage " damage")]
(-> battle
(update-in [target :hp] #(max 0 (- % damage)))
(update-in [:events] #(conj % message)))))
(defn do-heal-action
[battle actor target]
(let [roll (dice/basic-roll)
heal-amt roll
message (str (-> battle actor :name)
" heals " (-> battle target :name)
" for " heal-amt " health")]
(-> battle
(update-in [target :hp] #(min (-> battle target :max-hp) (+ % heal-amt)))
(update-in [:events] #(conj % message)))))
(defn do-heal-self
[battle actor]
(do-heal-action battle actor actor))
(def abilities
{:basic-attack {:fn do-basic-attack
:name "Basic Attack"
:is-available-fn #(= :in-progress (combat-state %))}
:no-action {:fn do-no-action
:name "Do Nothing"
:is-available-fn (constantly true)}
:heal-self {:fn do-heal-self
:name "Heal Self"
:is-available-fn #(constantly true)}})
(defn enemy-turn
[battle]
(if (-> battle :enemy alive?)
(do-basic-attack battle :enemy :player)
battle))
(defn available-abilities
"abilities currently available to the player"
; in the future this will take an additional argument for the character, but
; we don't know how multiple chararacters will be modeled/identified yet
[battle]
(->> battle
:player
:abilities
(filter #((-> % abilities :is-available-fn) battle))))
(defn available-abilities-character
[battle character]
(available-abilities battle))
| 96042 | (ns ^:figwheel-always iron-aether.model.battle
(:require [iron-aether.model.dice :as dice]
[iron-aether.model.character :as mc]))
;; state etc.
(def default-abilities
[:basic-attack #_:defend #_:heal #_:retreat :no-action #_:fight-again])
#_(defn new-character
[name & {:keys [friendly? max-hp attack defense abilities]}]
{:name name
:max-hp (or max-hp 70)
:hp (or max-hp 70)
:attack (or attack 10)
:defense (or defense 10)
:abilities (or abilities default-abilities)})
(defn new-battle
[& {:keys [character-name] :or {character-name "Skuld"}}]
{:player (mc/new-character character-name
:friendly? true
:max-hp 100)
:enemy (mc/new-character "G<NAME>")
:events ["Begin!"]})
(defn alive?
"takes a character map and indicates whether the character is alive"
[{:keys [hp]}]
(> hp 0))
(defn combat-state
"combat state of given battle state map"
[{:keys [player enemy]}]
(cond
(not (alive? player)) :lost
(not (alive? enemy)) :won
:else :in-progress))
;; abilities
(defn do-no-action
[battle actor _]
(update-in battle [:events]
#(conj % (str (-> battle actor :name) " does nothing"))))
(defn do-basic-attack
[battle actor target]
(let [roll (dice/basic-roll)
damage (max 0 (+ roll
(-> battle actor :attack)
(* -1 (:defense target))
5))
message (str (-> battle actor :name)
" attacks " (-> battle target :name)
" for " damage " damage")]
(-> battle
(update-in [target :hp] #(max 0 (- % damage)))
(update-in [:events] #(conj % message)))))
(defn do-heal-action
[battle actor target]
(let [roll (dice/basic-roll)
heal-amt roll
message (str (-> battle actor :name)
" heals " (-> battle target :name)
" for " heal-amt " health")]
(-> battle
(update-in [target :hp] #(min (-> battle target :max-hp) (+ % heal-amt)))
(update-in [:events] #(conj % message)))))
(defn do-heal-self
[battle actor]
(do-heal-action battle actor actor))
(def abilities
{:basic-attack {:fn do-basic-attack
:name "Basic Attack"
:is-available-fn #(= :in-progress (combat-state %))}
:no-action {:fn do-no-action
:name "Do Nothing"
:is-available-fn (constantly true)}
:heal-self {:fn do-heal-self
:name "Heal Self"
:is-available-fn #(constantly true)}})
(defn enemy-turn
[battle]
(if (-> battle :enemy alive?)
(do-basic-attack battle :enemy :player)
battle))
(defn available-abilities
"abilities currently available to the player"
; in the future this will take an additional argument for the character, but
; we don't know how multiple chararacters will be modeled/identified yet
[battle]
(->> battle
:player
:abilities
(filter #((-> % abilities :is-available-fn) battle))))
(defn available-abilities-character
[battle character]
(available-abilities battle))
| true | (ns ^:figwheel-always iron-aether.model.battle
(:require [iron-aether.model.dice :as dice]
[iron-aether.model.character :as mc]))
;; state etc.
(def default-abilities
[:basic-attack #_:defend #_:heal #_:retreat :no-action #_:fight-again])
#_(defn new-character
[name & {:keys [friendly? max-hp attack defense abilities]}]
{:name name
:max-hp (or max-hp 70)
:hp (or max-hp 70)
:attack (or attack 10)
:defense (or defense 10)
:abilities (or abilities default-abilities)})
(defn new-battle
[& {:keys [character-name] :or {character-name "Skuld"}}]
{:player (mc/new-character character-name
:friendly? true
:max-hp 100)
:enemy (mc/new-character "GPI:NAME:<NAME>END_PI")
:events ["Begin!"]})
(defn alive?
"takes a character map and indicates whether the character is alive"
[{:keys [hp]}]
(> hp 0))
(defn combat-state
"combat state of given battle state map"
[{:keys [player enemy]}]
(cond
(not (alive? player)) :lost
(not (alive? enemy)) :won
:else :in-progress))
;; abilities
(defn do-no-action
[battle actor _]
(update-in battle [:events]
#(conj % (str (-> battle actor :name) " does nothing"))))
(defn do-basic-attack
[battle actor target]
(let [roll (dice/basic-roll)
damage (max 0 (+ roll
(-> battle actor :attack)
(* -1 (:defense target))
5))
message (str (-> battle actor :name)
" attacks " (-> battle target :name)
" for " damage " damage")]
(-> battle
(update-in [target :hp] #(max 0 (- % damage)))
(update-in [:events] #(conj % message)))))
(defn do-heal-action
[battle actor target]
(let [roll (dice/basic-roll)
heal-amt roll
message (str (-> battle actor :name)
" heals " (-> battle target :name)
" for " heal-amt " health")]
(-> battle
(update-in [target :hp] #(min (-> battle target :max-hp) (+ % heal-amt)))
(update-in [:events] #(conj % message)))))
(defn do-heal-self
[battle actor]
(do-heal-action battle actor actor))
(def abilities
{:basic-attack {:fn do-basic-attack
:name "Basic Attack"
:is-available-fn #(= :in-progress (combat-state %))}
:no-action {:fn do-no-action
:name "Do Nothing"
:is-available-fn (constantly true)}
:heal-self {:fn do-heal-self
:name "Heal Self"
:is-available-fn #(constantly true)}})
(defn enemy-turn
[battle]
(if (-> battle :enemy alive?)
(do-basic-attack battle :enemy :player)
battle))
(defn available-abilities
"abilities currently available to the player"
; in the future this will take an additional argument for the character, but
; we don't know how multiple chararacters will be modeled/identified yet
[battle]
(->> battle
:player
:abilities
(filter #((-> % abilities :is-available-fn) battle))))
(defn available-abilities-character
[battle character]
(available-abilities battle))
|
[
{
"context": ";; Copyright (c) 2015 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi",
"end": 35,
"score": 0.9998834729194641,
"start": 22,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright (c) 2015 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and",
"end": 49,
"score": 0.999934196472168,
"start": 37,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
}
] | src/wydra/message.clj | funcool/wydra | 4 | ;; Copyright (c) 2015 Andrey Antukh <niwi@niwi.nz>
;; 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 HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns wydra.message
"A message abstraction.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Protocols
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol IMessageFactory
(-message [_ headers] "Create a new message instance."))
(defprotocol IMessage
(-body [_] "Get the message body.")
(-headers [_] "Get the message optional headers."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Type
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord Message [body headers]
IMessage
(-body [_] body)
(-headers [_] headers))
(alter-meta! #'->Message assoc :private true)
(alter-meta! #'map->Message assoc :private true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Protocol & Implementation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol IMessageFactory
java.lang.String
(-message [s o]
(Message. s o))
clojure.lang.IPersistentMap
(-message [m o]
(Message. m o))
Message
(-message [m _]
m))
| 67196 | ;; Copyright (c) 2015 <NAME> <<EMAIL>>
;; 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 HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns wydra.message
"A message abstraction.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Protocols
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol IMessageFactory
(-message [_ headers] "Create a new message instance."))
(defprotocol IMessage
(-body [_] "Get the message body.")
(-headers [_] "Get the message optional headers."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Type
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord Message [body headers]
IMessage
(-body [_] body)
(-headers [_] headers))
(alter-meta! #'->Message assoc :private true)
(alter-meta! #'map->Message assoc :private true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Protocol & Implementation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol IMessageFactory
java.lang.String
(-message [s o]
(Message. s o))
clojure.lang.IPersistentMap
(-message [m o]
(Message. m o))
Message
(-message [m _]
m))
| true | ;; Copyright (c) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>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 HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns wydra.message
"A message abstraction.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Protocols
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol IMessageFactory
(-message [_ headers] "Create a new message instance."))
(defprotocol IMessage
(-body [_] "Get the message body.")
(-headers [_] "Get the message optional headers."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Type
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord Message [body headers]
IMessage
(-body [_] body)
(-headers [_] headers))
(alter-meta! #'->Message assoc :private true)
(alter-meta! #'map->Message assoc :private true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Protocol & Implementation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol IMessageFactory
java.lang.String
(-message [s o]
(Message. s o))
clojure.lang.IPersistentMap
(-message [m o]
(Message. m o))
Message
(-message [m _]
m))
|
[
{
"context": "t {:id \"abcd\"\n :firstName \"James\"\n :lastName \"BOND\"\n ",
"end": 5140,
"score": 0.9995579123497009,
"start": 5135,
"tag": "NAME",
"value": "James"
},
{
"context": " :firstName \"James\"\n :lastName \"BOND\"\n :birthDate \"20-05-1940\"}\n :ent",
"end": 5173,
"score": 0.9993047714233398,
"start": 5169,
"tag": "NAME",
"value": "BOND"
},
{
"context": "rstName \"James\"\n \"lastName@upperCase\" ",
"end": 5386,
"score": 0.999338686466217,
"start": 5381,
"tag": "NAME",
"value": "James"
},
{
"context": "stName@upperCase\" \"BOND\"\n \"birthDate@dateFormat({\\\"format\\",
"end": 5461,
"score": 0.9980403184890747,
"start": 5457,
"tag": "NAME",
"value": "BOND"
},
{
"context": " {:slug \"abcd\"\n :name \"fudge master\"\n :address {:artemis.mapgraph/ref ",
"end": 33099,
"score": 0.9588515758514404,
"start": 33087,
"tag": "NAME",
"value": "fudge master"
},
{
"context": " {:slug \"abcde\"\n :name \"fudge colonel\"\n :address {:artemis.mapgraph/ref ",
"end": 33389,
"score": 0.9937062859535217,
"start": 33376,
"tag": "NAME",
"value": "fudge colonel"
},
{
"context": "\n :friends [{:slug \"abcd\" :name \"fudge master\" :address {:zip 11222}}\n ",
"end": 33561,
"score": 0.84100741147995,
"start": 33549,
"tag": "NAME",
"value": "fudge master"
},
{
"context": " {:slug \"abcde\" :name \"fudge colonel\" :address {:zip 03062}}]}}\n\n :multiple-fields\n ",
"end": 33649,
"score": 0.8808250427246094,
"start": 33636,
"tag": "NAME",
"value": "fudge colonel"
},
{
"context": " (is (= (:data (a/read store query {:slug \"bob\"}))\n {:author {:featuredBook {:titl",
"end": 40752,
"score": 0.9628278017044067,
"start": 40749,
"tag": "USERNAME",
"value": "bob"
},
{
"context": " (is (= (:data (a/read store query {:slug \"bob\"}))\n {:author {:slug \"bob\"\n",
"end": 41296,
"score": 0.9472643136978149,
"start": 41293,
"tag": "USERNAME",
"value": "bob"
},
{
"context": " \"bob\"}))\n {:author {:slug \"bob\"\n :featuredBook {:title \"",
"end": 41344,
"score": 0.9691252708435059,
"start": 41341,
"tag": "USERNAME",
"value": "bob"
}
] | test/artemis/stores/mapgraph_store_test.cljs | stevebuik/artemis | 0 | (ns artemis.stores.mapgraph-store-test
(:require [cljs.test :refer-macros [deftest is testing async]]
[artemis.core :as a]
[artemis.document :as d]
[artemis.stores.mapgraph.core :refer [create-store]]))
(def test-queries
{:basic
{:query (d/parse-document
"{
id
stringField
numberField
nullField
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
::cache "root"}}}
:args
{:query (d/parse-document
"{
id
stringField(arg: 1)
numberField
nullField
}")
:result {:id "abcd"
:stringField "The arg was 1"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
"stringField({\"arg\":1})" "The arg was 1"
:numberField 3
:nullField nil
::cache "root"}}}
:aliased
{:query (d/parse-document
"{
id
aliasedField: stringField
numberField
nullField
}")
:result {:id "abcd"
:aliasedField "this is a string"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
::cache "root"}}}
:aliased-with-args
{:query (d/parse-document
"{
id
aliasedField1: stringField(arg:1)
aliasedField2: stringField(arg:2)
numberField
nullField
}")
:result {:id "abcd"
:aliasedField1 "The arg was 1"
:aliasedField2 "The arg was 2"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
"stringField({\"arg\":1})" "The arg was 1"
"stringField({\"arg\":2})" "The arg was 2"
:numberField 3
:nullField nil
::cache "root"}}}
:with-vars
{:query (d/parse-document
"{
id
stringField(arg: $stringArg)
numberField(intArg: $intArg, floatArg: $floatArg)
nullField
}")
:input-vars {:intArg 5
:floatArg 3.14
:stringArg "This is a string"}
:result {:id "abcd"
:stringField "This worked"
:numberField 5
:nullField nil}
:entities {"root"
{:id "abcd"
:nullField nil
"numberField({\"intArg\":5,\"floatArg\":3.14})" 5
"stringField({\"arg\":\"This is a string\"})" "This worked"
::cache "root"}}}
:default-vars
{:query (d/parse-document
"query someBigQuery(
$stringArg: String = \"This is a default string\"
$intArg: Int
$floatArg: Float
) {
id
stringField(arg: $stringArg)
numberField(intArg: $intArg, floatArg: $floatArg)
nullField
}")
:input-vars {:intArg 5
:floatArg 3.14}
:result {:id "abcd"
:stringField "This worked"
:numberField 5
:nullField nil}
:entities {"root"
{:id "abcd"
:nullField nil
"numberField({\"intArg\":5,\"floatArg\":3.14})" 5
"stringField({\"arg\":\"This is a default string\"})" "This worked"
::cache "root"}}}
:directives
{:query (d/parse-document
"{
id
firstName @include(if: true)
lastName @upperCase
birthDate @dateFormat(format: \"DD-MM-YYYY\")
}")
:result {:id "abcd"
:firstName "James"
:lastName "BOND"
:birthDate "20-05-1940"}
:entities {"root"
{:id "abcd"
:firstName "James"
"lastName@upperCase" "BOND"
"birthDate@dateFormat({\"format\":\"DD-MM-YYYY\"})" "20-05-1940"
::cache "root"}}}
:nested
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:id "abcde"
:stringField "this is a string too"
:numberField 3
:nullField nil}}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:artemis.mapgraph/ref "abcde"}
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string too"
:numberField 3
:nullField nil}}}
:nested-no-id
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:stringField "this is a string too"
:numberField 3
:nullField nil}}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:artemis.mapgraph/ref "root.nestedObj"}
::cache "root"}
"root.nestedObj"
{:stringField "this is a string too"
:numberField 3
:nullField nil
::cache "root.nestedObj"}}}
:nested-with-args
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj(arg:\"val\") {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:stringField "this is a string too"
:numberField 3
:nullField nil}}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
"nestedObj({\"arg\":\"val\"})" {:artemis.mapgraph/ref "root.nestedObj({\"arg\":\"val\"})"}
::cache "root"}
"root.nestedObj({\"arg\":\"val\"})"
{:stringField "this is a string too"
:numberField 3
:nullField nil
::cache "root.nestedObj({\"arg\":\"val\"})"}}}
:nested-array
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}
{:id "abcdef"
:stringField "this is a string also"
:numberField 3
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "abcde"}
{:artemis.mapgraph/ref "abcdef"}]
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}
"abcdef"
{:id "abcdef"
:stringField "this is a string also"
:numberField 3
:nullField nil}}}
:nested-array-with-null
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}
nil]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "abcde"} nil]
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}}}
:deeply-nested-array
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
stringField
numberField
nullField
deeplyNestedArray {
numberField
stringField
}
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:stringField "this is a string too"
:numberField 2
:nullField nil
:deeplyNestedArray [{:numberField 10
:stringField "Foo"}
{:numberField 20
:stringField "Bar"}]}
{:stringField "this is a string also"
:numberField 3
:deeplyNestedArray [{:numberField 30
:stringField "Baz"}
{:numberField 40
:stringField "Boo"}]
:nullField nil}
{:stringField "this is a string, man"
:numberField 6
:deeplyNestedArray []
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "root.nestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.1"}
{:artemis.mapgraph/ref "root.nestedArray.2"}]
::cache "root"}
"root.nestedArray.0"
{:stringField "this is a string too"
:numberField 2
:nullField nil
:deeplyNestedArray [{:artemis.mapgraph/ref "root.nestedArray.0.deeplyNestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.0.deeplyNestedArray.1"}]
::cache "root.nestedArray.0"}
"root.nestedArray.1"
{:stringField "this is a string also"
:numberField 3
:nullField nil
:deeplyNestedArray [{:artemis.mapgraph/ref "root.nestedArray.1.deeplyNestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.1.deeplyNestedArray.1"}]
::cache "root.nestedArray.1"}
"root.nestedArray.2"
{:stringField "this is a string, man"
:numberField 6
:nullField nil
:deeplyNestedArray []
::cache "root.nestedArray.2"}
"root.nestedArray.0.deeplyNestedArray.0"
{:numberField 10
:stringField "Foo"
::cache "root.nestedArray.0.deeplyNestedArray.0"}
"root.nestedArray.0.deeplyNestedArray.1"
{:numberField 20
:stringField "Bar"
::cache "root.nestedArray.0.deeplyNestedArray.1"}
"root.nestedArray.1.deeplyNestedArray.0"
{:numberField 30
:stringField "Baz"
::cache "root.nestedArray.1.deeplyNestedArray.0"}
"root.nestedArray.1.deeplyNestedArray.1"
{:numberField 40
:stringField "Boo"
::cache "root.nestedArray.1.deeplyNestedArray.1"}}}
:nested-array-without-ids
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:stringField "this is a string too"
:numberField 2
:nullField nil}
{:stringField "this is a string also"
:numberField 3
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "root.nestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.1"}]
::cache "root"}
"root.nestedArray.0"
{:stringField "this is a string too"
:numberField 2
:nullField nil
::cache "root.nestedArray.0"}
"root.nestedArray.1"
{:stringField "this is a string also"
:numberField 3
:nullField nil
::cache "root.nestedArray.1"}}}
:nested-array-with-nulls-and-no-ids
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [nil
{:stringField "this is a string also"
:numberField 3
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [nil
{:artemis.mapgraph/ref "root.nestedArray.1"}]
::cache "root"}
"root.nestedArray.1"
{:stringField "this is a string also"
:numberField 3
:nullField nil
::cache "root.nestedArray.1"}}}
:simple-array
{:query (d/parse-document
"{
id
stringField
numberField
nullField
simpleArray
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray ["one" "two" "three"]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray ["one" "two" "three"]
::cache "root"}}}
:simple-array-with-nulls
{:query (d/parse-document
"{
id
stringField
numberField
nullField
simpleArray
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray [nil "two" "three"]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray [nil "two" "three"]
::cache "root"}}}
:obj-in-different-paths
{:query (d/parse-document
"{
id
object1 {
id
stringField
}
object2 {
id
numberField
}
}")
:result {:id "a"
:object1 {:id "aa"
:stringField "this is a string"}
:object2 {:id "aa"
:numberField 1}}
:entities {"root"
{:id "a"
:object1 {:artemis.mapgraph/ref "aa"}
:object2 {:artemis.mapgraph/ref "aa"}
::cache "root"}
"aa"
{:id "aa"
:stringField "this is a string"
:numberField 1}}}
:obj-in-different-array-paths
{:query (d/parse-document
"{
id
array1 {
id
stringField
obj {
id
stringField
}
}
array2 {
id
stringField
obj {
id
numberField
}
}
}")
:result {:id "a"
:array1 [{:id "aa"
:stringField "this is a string"
:obj {:id "aaa"
:stringField "string"}}]
:array2 [{:id "ab"
:stringField "this is a string too"
:obj {:id "aaa"
:numberField 1}}]}
:entities {"root"
{:id "a"
:array1 [{:artemis.mapgraph/ref "aa"}]
:array2 [{:artemis.mapgraph/ref "ab"}]
::cache "root"}
"aa"
{:id "aa"
:stringField "this is a string"
:obj {:artemis.mapgraph/ref "aaa"}}
"ab"
{:id "ab"
:stringField "this is a string too"
:obj {:artemis.mapgraph/ref "aaa"}}
"aaa"
{:id "aaa"
:stringField "string"
:numberField 1}}}
:nested-object-returning-null
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj nil}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj nil
::cache "root"}}}
:union-array
{:query (d/parse-document
"{
search(text: \"a\") {
... on object {
id
stringField
__typename
}
... on otherobject {
id
numberField
__typename
}
}
}")
:result {:search
[{:id "abcd"
:stringField "this is a string"
:__typename "object"}
{:id "efgh"
:numberField 3
:__typename "otherobject"}]}
:entities {"root"
{"search({\"text\":\"a\"})" [{:artemis.mapgraph/ref "abcd"}
{:artemis.mapgraph/ref "efgh"}]
::cache "root"}
"abcd"
{:id "abcd"
:stringField "this is a string"
:__typename "object"}
"efgh"
{:id "efgh"
:numberField 3
:__typename "otherobject"}}}
:union-array-no-id
{:query (d/parse-document
"{
search(text: \"a\") {
... on someobject {
stringField
__typename
}
}
}")
:result {:search
[{:stringField "this is a string"
:__typename "someobject"}
{:stringField "this is another string"
:__typename "someobject"}]}
:entities {"root"
{"search({\"text\":\"a\"})" [{:artemis.mapgraph/ref "root.search({\"text\":\"a\"}).0"}
{:artemis.mapgraph/ref "root.search({\"text\":\"a\"}).1"}]
::cache "root"}
"root.search({\"text\":\"a\"}).0"
{:stringField "this is a string"
:__typename "someobject"
::cache "root.search({\"text\":\"a\"}).0"}
"root.search({\"text\":\"a\"}).1"
{:stringField "this is another string"
:__typename "someobject"
::cache "root.search({\"text\":\"a\"}).1"}}}
:nested-union
{:query (d/parse-document
"{
id
stringField
unionObj {
... on object {
id
numberField
stringField
__typename
}
... on otherobject {
id
stringField
__typename
}
}
}")
:result {:id "a"
:stringField "this is a string"
:unionObj {:id "abcd"
:stringField "this is a string"
:numberField 3
:__typename "object"}}
:entities {"root"
{:id "a"
:stringField "this is a string"
:unionObj {:artemis.mapgraph/ref "abcd"}
::cache "root"}
"abcd"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:__typename "object"}}}
:nested-union-no-id
{:query (d/parse-document
"{
id
stringField
unionObj {
... on someobject {
numberField
stringField
__typename
}
... on someotherobject {
stringField
__typename
}
}
}")
:result {:id "a"
:stringField "this is a string"
:unionObj {:stringField "this is a string"
:numberField 3
:__typename "someobject"}}
:entities {"root"
{:id "a"
:stringField "this is a string"
:unionObj {:artemis.mapgraph/ref "root.unionObj"}
::cache "root"}
"root.unionObj"
{:stringField "this is a string"
:numberField 3
:__typename "someobject"
::cache "root.unionObj"}}}
:fragments
{:query (d/parse-document
"query SomeQuery {
id
...OtherFields
}
fragment OtherFields on object {
stringField
numberField
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
::cache "root"}}}
:nested-fragments
{:query (d/parse-document
"query SomeQuery {
id
nestedObj {
id
...OtherFields
}
}
fragment OtherFields on object {
stringField
numberField
}")
:result {:id "abcd"
:nestedObj {:id "abcde"
:stringField "this is a string"
:numberField 3}}
:entities {"root"
{:id "abcd"
:nestedObj {:artemis.mapgraph/ref "abcde"}
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string"
:numberField 3}}}
:chained-fragments
{:query (d/parse-document
"query SomeQuery {
id
...OtherFields
}
fragment OtherFields on object {
stringField
...EvenOtherFields
}
fragment EvenOtherFields on object {
numberField
}
")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
::cache "root"}}}})
(defn write-test [k]
(testing (str "testing normalized cache persistence for query type: " k)
(let [{:keys [query input-vars result entities]} (get test-queries k)
initial-store (create-store :cache-key ::cache)
new-store (a/write initial-store {:data result} query input-vars)]
(is (= entities (:entities new-store))))))
(deftest test-cache-persistence
(doseq [test-query (keys test-queries)]
(write-test test-query)))
(defn read-test [k]
(testing (str "testing normalized cache querying for query type: " k)
(let [{:keys [query input-vars result entities]} (get test-queries k)
store (create-store :entities entities
:cache-key ::cache)
response (a/read store query input-vars)]
(is (= {:data result} response)))))
(deftest test-cache-reading
(doseq [test-query (keys test-queries)]
(read-test test-query)))
(def test-fragments
{:basic
{:fragment (d/parse-document
"fragment A on object {
stringField
}")
:entities {"abcde"
{:id "abcde"
:stringField "this is a string"
:numberField 3
:nullField nil
::cache "root"}}
:entity "abcde"
:write-data {:stringField "this is a different string"}
:read-result {:stringField "this is a string"}}
:nested-fragments
{:fragment (d/compose
(d/parse-document
"fragment A on B {
slug
friends {
...C
}
}")
(d/parse-document
"fragment C on D {
slug
name
address {
...D
}
}")
(d/parse-document
"fragment D on E {
zip
}"))
:entities {[:slug "abc"]
{:slug "abc"
:friends [{:artemis.mapgraph/ref [:slug "abcd"]}
{:artemis.mapgraph/ref [:slug "abcde"]}]}
[:slug "abcd"]
{:slug "abcd"
:name "fudge master"
:address {:artemis.mapgraph/ref 1}}
1
{:id 1 :street "test 1" :zip 11222}
2
{:id 2 :street "test 2" :zip 03062}
[:slug "abcde"]
{:slug "abcde"
:name "fudge colonel"
:address {:artemis.mapgraph/ref 2}}}
:entity [:slug "abc"]
:read-result {:slug "abc"
:friends [{:slug "abcd" :name "fudge master" :address {:zip 11222}}
{:slug "abcde" :name "fudge colonel" :address {:zip 03062}}]}}
:multiple-fields
{:fragment (d/parse-document
"fragment A on object {
numberField
stringField
}")
:entities {"abcde"
{:id "abcde"
:stringField "this is a string"
:numberField 3}}
:entity "abcde"
:write-data {:stringField "this is a different string"
:numberField 4}
:read-result {:stringField "this is a string"
:numberField 3}}})
(defn write-fragment-test [k]
(testing (str "testing normalized cache persistence for fragment type: " k)
(let [{:keys [fragment entity write-data entities]} (get test-fragments k)
initial-store (create-store :entities entities
:cache-key ::cache)
old-ent (get (:entities initial-store) entity)
new-store (a/write-fragment initial-store {:data write-data} fragment entity)
new-ent (get (:entities new-store) entity)]
(is (= new-ent (merge old-ent new-ent))))))
(deftest test-cache-fragment-persistence
(doseq [test-fragment (keys test-fragments)]
(write-fragment-test test-fragment)))
(defn read-fragment-test [k]
(testing (str "testing normalized cache reading for fragment type: " k)
(let [{:keys [fragment entity entities read-result]} (get test-fragments k)
store (create-store :entities entities
:cache-key ::cache)
response (a/read-fragment store fragment entity)]
(is (= {:data read-result} response)))))
(deftest test-cache-fragment-reading
(doseq [test-fragment (keys test-fragments)]
(read-fragment-test test-fragment)))
(deftest return-partial
(let [entities {"root"
{:object1 {:artemis.mapgraph/ref "aa"}
::cache "root"}
"aa"
{:id "aa"
:stringField "this is a string"
:otherObject {:artemis.mapgraph/ref "bb"}}
"bb"
{:id "bb"}}
store (create-store :entities entities
:cache-key ::cache)]
(testing "query return-partial"
(testing "set to true and all data not present"
(let [query (d/parse-document "{
object1 {
id
stringField
numberField
}
}")]
(is (= (:data (a/read store query {} :return-partial? true))
{:object1
{:id "aa"
:stringField "this is a string"}}))))
(testing "set to false nested key doesn't exist"
(let [query (d/parse-document "{
object1 {
id
stringField
doesntExist { slug }
}
}")]
(is (nil? (:data (a/read store query {}))))))
(testing "set to false all data not present"
(let [query (d/parse-document "{
object1 {
id
stringField
numberField
}
}")]
(is (nil? (:data (a/read store query {}))))))
(testing "set to false all data not present deeply"
(let [query (d/parse-document "{
object1 {
otherObject {
title
}
id
}
}")]
(is (nil? (:data (a/read store query {})))))))
(testing "fragment return-partial"
(testing "set to true and all data not present"
(let [fragment (d/parse-document "fragment A on object {
id
stringField
numberField
}")]
(is (= (:data (a/read-fragment store fragment "aa" :return-partial? true))
{:id "aa"
:stringField "this is a string"}))))
(testing "set to true and all data not present"
(let [fragment (d/parse-document "fragment A on object {
id
stringField
numberField
}")]
(is (nil? (:data (a/read-fragment store fragment "aa")))))))))
(def cache-redirects-map
{:book (comp :id :variables)
:featuredBook (comp #(when (= % "bob") 1) :slug :variables)})
(deftest cache-redirects
(let [entities {"root"
{::cache "root"
"author({\"slug\":\"bob\"})" {:artemis.mapgraph/ref "bob"}
"books" [{:artemis.mapgraph/ref 1} {:artemis.mapgraph/ref 2}]}
"bob" {:slug "bob"}
1 {:id 1 :title "Book 1", :abstract "Lorem ipsum..."}
2 {:id 2 :title "Book 2", :abstract "Lorem ipsum..."}}
store (create-store :entities entities
:cache-redirects cache-redirects-map
:cache-key ::cache)]
(testing "simple redirect"
(let [query (d/parse-document "{
book(id: $id) {
id
title
abstract
}
}")]
(is (= (:data (a/read store query {:id 1}))
{:book {:id 1
:title "Book 1"
:abstract "Lorem ipsum..."}}))
(is (= (:data (a/read store query {:id 2}))
{:book {:id 2
:title "Book 2"
:abstract "Lorem ipsum..."}}))
(is (= (:data (a/read store query {:id 3}))
nil))))
(testing "deep redirect"
(let [query (d/parse-document "{
author(slug: $slug) {
featuredBook {
title
}
}
}")]
(is (= (:data (a/read store query {:slug "bob"}))
{:author {:featuredBook {:title "Book 1"}}}))))
(testing "mixed with non-redirect fields"
(let [query (d/parse-document "{
author(slug: $slug) {
slug
featuredBook {
title
}
}
}")]
(is (= (:data (a/read store query {:slug "bob"}))
{:author {:slug "bob"
:featuredBook {:title "Book 1"}}}))))))
| 14315 | (ns artemis.stores.mapgraph-store-test
(:require [cljs.test :refer-macros [deftest is testing async]]
[artemis.core :as a]
[artemis.document :as d]
[artemis.stores.mapgraph.core :refer [create-store]]))
(def test-queries
{:basic
{:query (d/parse-document
"{
id
stringField
numberField
nullField
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
::cache "root"}}}
:args
{:query (d/parse-document
"{
id
stringField(arg: 1)
numberField
nullField
}")
:result {:id "abcd"
:stringField "The arg was 1"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
"stringField({\"arg\":1})" "The arg was 1"
:numberField 3
:nullField nil
::cache "root"}}}
:aliased
{:query (d/parse-document
"{
id
aliasedField: stringField
numberField
nullField
}")
:result {:id "abcd"
:aliasedField "this is a string"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
::cache "root"}}}
:aliased-with-args
{:query (d/parse-document
"{
id
aliasedField1: stringField(arg:1)
aliasedField2: stringField(arg:2)
numberField
nullField
}")
:result {:id "abcd"
:aliasedField1 "The arg was 1"
:aliasedField2 "The arg was 2"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
"stringField({\"arg\":1})" "The arg was 1"
"stringField({\"arg\":2})" "The arg was 2"
:numberField 3
:nullField nil
::cache "root"}}}
:with-vars
{:query (d/parse-document
"{
id
stringField(arg: $stringArg)
numberField(intArg: $intArg, floatArg: $floatArg)
nullField
}")
:input-vars {:intArg 5
:floatArg 3.14
:stringArg "This is a string"}
:result {:id "abcd"
:stringField "This worked"
:numberField 5
:nullField nil}
:entities {"root"
{:id "abcd"
:nullField nil
"numberField({\"intArg\":5,\"floatArg\":3.14})" 5
"stringField({\"arg\":\"This is a string\"})" "This worked"
::cache "root"}}}
:default-vars
{:query (d/parse-document
"query someBigQuery(
$stringArg: String = \"This is a default string\"
$intArg: Int
$floatArg: Float
) {
id
stringField(arg: $stringArg)
numberField(intArg: $intArg, floatArg: $floatArg)
nullField
}")
:input-vars {:intArg 5
:floatArg 3.14}
:result {:id "abcd"
:stringField "This worked"
:numberField 5
:nullField nil}
:entities {"root"
{:id "abcd"
:nullField nil
"numberField({\"intArg\":5,\"floatArg\":3.14})" 5
"stringField({\"arg\":\"This is a default string\"})" "This worked"
::cache "root"}}}
:directives
{:query (d/parse-document
"{
id
firstName @include(if: true)
lastName @upperCase
birthDate @dateFormat(format: \"DD-MM-YYYY\")
}")
:result {:id "abcd"
:firstName "<NAME>"
:lastName "<NAME>"
:birthDate "20-05-1940"}
:entities {"root"
{:id "abcd"
:firstName "<NAME>"
"lastName@upperCase" "<NAME>"
"birthDate@dateFormat({\"format\":\"DD-MM-YYYY\"})" "20-05-1940"
::cache "root"}}}
:nested
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:id "abcde"
:stringField "this is a string too"
:numberField 3
:nullField nil}}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:artemis.mapgraph/ref "abcde"}
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string too"
:numberField 3
:nullField nil}}}
:nested-no-id
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:stringField "this is a string too"
:numberField 3
:nullField nil}}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:artemis.mapgraph/ref "root.nestedObj"}
::cache "root"}
"root.nestedObj"
{:stringField "this is a string too"
:numberField 3
:nullField nil
::cache "root.nestedObj"}}}
:nested-with-args
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj(arg:\"val\") {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:stringField "this is a string too"
:numberField 3
:nullField nil}}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
"nestedObj({\"arg\":\"val\"})" {:artemis.mapgraph/ref "root.nestedObj({\"arg\":\"val\"})"}
::cache "root"}
"root.nestedObj({\"arg\":\"val\"})"
{:stringField "this is a string too"
:numberField 3
:nullField nil
::cache "root.nestedObj({\"arg\":\"val\"})"}}}
:nested-array
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}
{:id "abcdef"
:stringField "this is a string also"
:numberField 3
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "abcde"}
{:artemis.mapgraph/ref "abcdef"}]
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}
"abcdef"
{:id "abcdef"
:stringField "this is a string also"
:numberField 3
:nullField nil}}}
:nested-array-with-null
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}
nil]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "abcde"} nil]
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}}}
:deeply-nested-array
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
stringField
numberField
nullField
deeplyNestedArray {
numberField
stringField
}
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:stringField "this is a string too"
:numberField 2
:nullField nil
:deeplyNestedArray [{:numberField 10
:stringField "Foo"}
{:numberField 20
:stringField "Bar"}]}
{:stringField "this is a string also"
:numberField 3
:deeplyNestedArray [{:numberField 30
:stringField "Baz"}
{:numberField 40
:stringField "Boo"}]
:nullField nil}
{:stringField "this is a string, man"
:numberField 6
:deeplyNestedArray []
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "root.nestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.1"}
{:artemis.mapgraph/ref "root.nestedArray.2"}]
::cache "root"}
"root.nestedArray.0"
{:stringField "this is a string too"
:numberField 2
:nullField nil
:deeplyNestedArray [{:artemis.mapgraph/ref "root.nestedArray.0.deeplyNestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.0.deeplyNestedArray.1"}]
::cache "root.nestedArray.0"}
"root.nestedArray.1"
{:stringField "this is a string also"
:numberField 3
:nullField nil
:deeplyNestedArray [{:artemis.mapgraph/ref "root.nestedArray.1.deeplyNestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.1.deeplyNestedArray.1"}]
::cache "root.nestedArray.1"}
"root.nestedArray.2"
{:stringField "this is a string, man"
:numberField 6
:nullField nil
:deeplyNestedArray []
::cache "root.nestedArray.2"}
"root.nestedArray.0.deeplyNestedArray.0"
{:numberField 10
:stringField "Foo"
::cache "root.nestedArray.0.deeplyNestedArray.0"}
"root.nestedArray.0.deeplyNestedArray.1"
{:numberField 20
:stringField "Bar"
::cache "root.nestedArray.0.deeplyNestedArray.1"}
"root.nestedArray.1.deeplyNestedArray.0"
{:numberField 30
:stringField "Baz"
::cache "root.nestedArray.1.deeplyNestedArray.0"}
"root.nestedArray.1.deeplyNestedArray.1"
{:numberField 40
:stringField "Boo"
::cache "root.nestedArray.1.deeplyNestedArray.1"}}}
:nested-array-without-ids
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:stringField "this is a string too"
:numberField 2
:nullField nil}
{:stringField "this is a string also"
:numberField 3
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "root.nestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.1"}]
::cache "root"}
"root.nestedArray.0"
{:stringField "this is a string too"
:numberField 2
:nullField nil
::cache "root.nestedArray.0"}
"root.nestedArray.1"
{:stringField "this is a string also"
:numberField 3
:nullField nil
::cache "root.nestedArray.1"}}}
:nested-array-with-nulls-and-no-ids
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [nil
{:stringField "this is a string also"
:numberField 3
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [nil
{:artemis.mapgraph/ref "root.nestedArray.1"}]
::cache "root"}
"root.nestedArray.1"
{:stringField "this is a string also"
:numberField 3
:nullField nil
::cache "root.nestedArray.1"}}}
:simple-array
{:query (d/parse-document
"{
id
stringField
numberField
nullField
simpleArray
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray ["one" "two" "three"]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray ["one" "two" "three"]
::cache "root"}}}
:simple-array-with-nulls
{:query (d/parse-document
"{
id
stringField
numberField
nullField
simpleArray
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray [nil "two" "three"]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray [nil "two" "three"]
::cache "root"}}}
:obj-in-different-paths
{:query (d/parse-document
"{
id
object1 {
id
stringField
}
object2 {
id
numberField
}
}")
:result {:id "a"
:object1 {:id "aa"
:stringField "this is a string"}
:object2 {:id "aa"
:numberField 1}}
:entities {"root"
{:id "a"
:object1 {:artemis.mapgraph/ref "aa"}
:object2 {:artemis.mapgraph/ref "aa"}
::cache "root"}
"aa"
{:id "aa"
:stringField "this is a string"
:numberField 1}}}
:obj-in-different-array-paths
{:query (d/parse-document
"{
id
array1 {
id
stringField
obj {
id
stringField
}
}
array2 {
id
stringField
obj {
id
numberField
}
}
}")
:result {:id "a"
:array1 [{:id "aa"
:stringField "this is a string"
:obj {:id "aaa"
:stringField "string"}}]
:array2 [{:id "ab"
:stringField "this is a string too"
:obj {:id "aaa"
:numberField 1}}]}
:entities {"root"
{:id "a"
:array1 [{:artemis.mapgraph/ref "aa"}]
:array2 [{:artemis.mapgraph/ref "ab"}]
::cache "root"}
"aa"
{:id "aa"
:stringField "this is a string"
:obj {:artemis.mapgraph/ref "aaa"}}
"ab"
{:id "ab"
:stringField "this is a string too"
:obj {:artemis.mapgraph/ref "aaa"}}
"aaa"
{:id "aaa"
:stringField "string"
:numberField 1}}}
:nested-object-returning-null
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj nil}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj nil
::cache "root"}}}
:union-array
{:query (d/parse-document
"{
search(text: \"a\") {
... on object {
id
stringField
__typename
}
... on otherobject {
id
numberField
__typename
}
}
}")
:result {:search
[{:id "abcd"
:stringField "this is a string"
:__typename "object"}
{:id "efgh"
:numberField 3
:__typename "otherobject"}]}
:entities {"root"
{"search({\"text\":\"a\"})" [{:artemis.mapgraph/ref "abcd"}
{:artemis.mapgraph/ref "efgh"}]
::cache "root"}
"abcd"
{:id "abcd"
:stringField "this is a string"
:__typename "object"}
"efgh"
{:id "efgh"
:numberField 3
:__typename "otherobject"}}}
:union-array-no-id
{:query (d/parse-document
"{
search(text: \"a\") {
... on someobject {
stringField
__typename
}
}
}")
:result {:search
[{:stringField "this is a string"
:__typename "someobject"}
{:stringField "this is another string"
:__typename "someobject"}]}
:entities {"root"
{"search({\"text\":\"a\"})" [{:artemis.mapgraph/ref "root.search({\"text\":\"a\"}).0"}
{:artemis.mapgraph/ref "root.search({\"text\":\"a\"}).1"}]
::cache "root"}
"root.search({\"text\":\"a\"}).0"
{:stringField "this is a string"
:__typename "someobject"
::cache "root.search({\"text\":\"a\"}).0"}
"root.search({\"text\":\"a\"}).1"
{:stringField "this is another string"
:__typename "someobject"
::cache "root.search({\"text\":\"a\"}).1"}}}
:nested-union
{:query (d/parse-document
"{
id
stringField
unionObj {
... on object {
id
numberField
stringField
__typename
}
... on otherobject {
id
stringField
__typename
}
}
}")
:result {:id "a"
:stringField "this is a string"
:unionObj {:id "abcd"
:stringField "this is a string"
:numberField 3
:__typename "object"}}
:entities {"root"
{:id "a"
:stringField "this is a string"
:unionObj {:artemis.mapgraph/ref "abcd"}
::cache "root"}
"abcd"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:__typename "object"}}}
:nested-union-no-id
{:query (d/parse-document
"{
id
stringField
unionObj {
... on someobject {
numberField
stringField
__typename
}
... on someotherobject {
stringField
__typename
}
}
}")
:result {:id "a"
:stringField "this is a string"
:unionObj {:stringField "this is a string"
:numberField 3
:__typename "someobject"}}
:entities {"root"
{:id "a"
:stringField "this is a string"
:unionObj {:artemis.mapgraph/ref "root.unionObj"}
::cache "root"}
"root.unionObj"
{:stringField "this is a string"
:numberField 3
:__typename "someobject"
::cache "root.unionObj"}}}
:fragments
{:query (d/parse-document
"query SomeQuery {
id
...OtherFields
}
fragment OtherFields on object {
stringField
numberField
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
::cache "root"}}}
:nested-fragments
{:query (d/parse-document
"query SomeQuery {
id
nestedObj {
id
...OtherFields
}
}
fragment OtherFields on object {
stringField
numberField
}")
:result {:id "abcd"
:nestedObj {:id "abcde"
:stringField "this is a string"
:numberField 3}}
:entities {"root"
{:id "abcd"
:nestedObj {:artemis.mapgraph/ref "abcde"}
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string"
:numberField 3}}}
:chained-fragments
{:query (d/parse-document
"query SomeQuery {
id
...OtherFields
}
fragment OtherFields on object {
stringField
...EvenOtherFields
}
fragment EvenOtherFields on object {
numberField
}
")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
::cache "root"}}}})
(defn write-test [k]
(testing (str "testing normalized cache persistence for query type: " k)
(let [{:keys [query input-vars result entities]} (get test-queries k)
initial-store (create-store :cache-key ::cache)
new-store (a/write initial-store {:data result} query input-vars)]
(is (= entities (:entities new-store))))))
(deftest test-cache-persistence
(doseq [test-query (keys test-queries)]
(write-test test-query)))
(defn read-test [k]
(testing (str "testing normalized cache querying for query type: " k)
(let [{:keys [query input-vars result entities]} (get test-queries k)
store (create-store :entities entities
:cache-key ::cache)
response (a/read store query input-vars)]
(is (= {:data result} response)))))
(deftest test-cache-reading
(doseq [test-query (keys test-queries)]
(read-test test-query)))
(def test-fragments
{:basic
{:fragment (d/parse-document
"fragment A on object {
stringField
}")
:entities {"abcde"
{:id "abcde"
:stringField "this is a string"
:numberField 3
:nullField nil
::cache "root"}}
:entity "abcde"
:write-data {:stringField "this is a different string"}
:read-result {:stringField "this is a string"}}
:nested-fragments
{:fragment (d/compose
(d/parse-document
"fragment A on B {
slug
friends {
...C
}
}")
(d/parse-document
"fragment C on D {
slug
name
address {
...D
}
}")
(d/parse-document
"fragment D on E {
zip
}"))
:entities {[:slug "abc"]
{:slug "abc"
:friends [{:artemis.mapgraph/ref [:slug "abcd"]}
{:artemis.mapgraph/ref [:slug "abcde"]}]}
[:slug "abcd"]
{:slug "abcd"
:name "<NAME>"
:address {:artemis.mapgraph/ref 1}}
1
{:id 1 :street "test 1" :zip 11222}
2
{:id 2 :street "test 2" :zip 03062}
[:slug "abcde"]
{:slug "abcde"
:name "<NAME>"
:address {:artemis.mapgraph/ref 2}}}
:entity [:slug "abc"]
:read-result {:slug "abc"
:friends [{:slug "abcd" :name "<NAME>" :address {:zip 11222}}
{:slug "abcde" :name "<NAME>" :address {:zip 03062}}]}}
:multiple-fields
{:fragment (d/parse-document
"fragment A on object {
numberField
stringField
}")
:entities {"abcde"
{:id "abcde"
:stringField "this is a string"
:numberField 3}}
:entity "abcde"
:write-data {:stringField "this is a different string"
:numberField 4}
:read-result {:stringField "this is a string"
:numberField 3}}})
(defn write-fragment-test [k]
(testing (str "testing normalized cache persistence for fragment type: " k)
(let [{:keys [fragment entity write-data entities]} (get test-fragments k)
initial-store (create-store :entities entities
:cache-key ::cache)
old-ent (get (:entities initial-store) entity)
new-store (a/write-fragment initial-store {:data write-data} fragment entity)
new-ent (get (:entities new-store) entity)]
(is (= new-ent (merge old-ent new-ent))))))
(deftest test-cache-fragment-persistence
(doseq [test-fragment (keys test-fragments)]
(write-fragment-test test-fragment)))
(defn read-fragment-test [k]
(testing (str "testing normalized cache reading for fragment type: " k)
(let [{:keys [fragment entity entities read-result]} (get test-fragments k)
store (create-store :entities entities
:cache-key ::cache)
response (a/read-fragment store fragment entity)]
(is (= {:data read-result} response)))))
(deftest test-cache-fragment-reading
(doseq [test-fragment (keys test-fragments)]
(read-fragment-test test-fragment)))
(deftest return-partial
(let [entities {"root"
{:object1 {:artemis.mapgraph/ref "aa"}
::cache "root"}
"aa"
{:id "aa"
:stringField "this is a string"
:otherObject {:artemis.mapgraph/ref "bb"}}
"bb"
{:id "bb"}}
store (create-store :entities entities
:cache-key ::cache)]
(testing "query return-partial"
(testing "set to true and all data not present"
(let [query (d/parse-document "{
object1 {
id
stringField
numberField
}
}")]
(is (= (:data (a/read store query {} :return-partial? true))
{:object1
{:id "aa"
:stringField "this is a string"}}))))
(testing "set to false nested key doesn't exist"
(let [query (d/parse-document "{
object1 {
id
stringField
doesntExist { slug }
}
}")]
(is (nil? (:data (a/read store query {}))))))
(testing "set to false all data not present"
(let [query (d/parse-document "{
object1 {
id
stringField
numberField
}
}")]
(is (nil? (:data (a/read store query {}))))))
(testing "set to false all data not present deeply"
(let [query (d/parse-document "{
object1 {
otherObject {
title
}
id
}
}")]
(is (nil? (:data (a/read store query {})))))))
(testing "fragment return-partial"
(testing "set to true and all data not present"
(let [fragment (d/parse-document "fragment A on object {
id
stringField
numberField
}")]
(is (= (:data (a/read-fragment store fragment "aa" :return-partial? true))
{:id "aa"
:stringField "this is a string"}))))
(testing "set to true and all data not present"
(let [fragment (d/parse-document "fragment A on object {
id
stringField
numberField
}")]
(is (nil? (:data (a/read-fragment store fragment "aa")))))))))
(def cache-redirects-map
{:book (comp :id :variables)
:featuredBook (comp #(when (= % "bob") 1) :slug :variables)})
(deftest cache-redirects
(let [entities {"root"
{::cache "root"
"author({\"slug\":\"bob\"})" {:artemis.mapgraph/ref "bob"}
"books" [{:artemis.mapgraph/ref 1} {:artemis.mapgraph/ref 2}]}
"bob" {:slug "bob"}
1 {:id 1 :title "Book 1", :abstract "Lorem ipsum..."}
2 {:id 2 :title "Book 2", :abstract "Lorem ipsum..."}}
store (create-store :entities entities
:cache-redirects cache-redirects-map
:cache-key ::cache)]
(testing "simple redirect"
(let [query (d/parse-document "{
book(id: $id) {
id
title
abstract
}
}")]
(is (= (:data (a/read store query {:id 1}))
{:book {:id 1
:title "Book 1"
:abstract "Lorem ipsum..."}}))
(is (= (:data (a/read store query {:id 2}))
{:book {:id 2
:title "Book 2"
:abstract "Lorem ipsum..."}}))
(is (= (:data (a/read store query {:id 3}))
nil))))
(testing "deep redirect"
(let [query (d/parse-document "{
author(slug: $slug) {
featuredBook {
title
}
}
}")]
(is (= (:data (a/read store query {:slug "bob"}))
{:author {:featuredBook {:title "Book 1"}}}))))
(testing "mixed with non-redirect fields"
(let [query (d/parse-document "{
author(slug: $slug) {
slug
featuredBook {
title
}
}
}")]
(is (= (:data (a/read store query {:slug "bob"}))
{:author {:slug "bob"
:featuredBook {:title "Book 1"}}}))))))
| true | (ns artemis.stores.mapgraph-store-test
(:require [cljs.test :refer-macros [deftest is testing async]]
[artemis.core :as a]
[artemis.document :as d]
[artemis.stores.mapgraph.core :refer [create-store]]))
(def test-queries
{:basic
{:query (d/parse-document
"{
id
stringField
numberField
nullField
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
::cache "root"}}}
:args
{:query (d/parse-document
"{
id
stringField(arg: 1)
numberField
nullField
}")
:result {:id "abcd"
:stringField "The arg was 1"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
"stringField({\"arg\":1})" "The arg was 1"
:numberField 3
:nullField nil
::cache "root"}}}
:aliased
{:query (d/parse-document
"{
id
aliasedField: stringField
numberField
nullField
}")
:result {:id "abcd"
:aliasedField "this is a string"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
::cache "root"}}}
:aliased-with-args
{:query (d/parse-document
"{
id
aliasedField1: stringField(arg:1)
aliasedField2: stringField(arg:2)
numberField
nullField
}")
:result {:id "abcd"
:aliasedField1 "The arg was 1"
:aliasedField2 "The arg was 2"
:numberField 3
:nullField nil}
:entities {"root"
{:id "abcd"
"stringField({\"arg\":1})" "The arg was 1"
"stringField({\"arg\":2})" "The arg was 2"
:numberField 3
:nullField nil
::cache "root"}}}
:with-vars
{:query (d/parse-document
"{
id
stringField(arg: $stringArg)
numberField(intArg: $intArg, floatArg: $floatArg)
nullField
}")
:input-vars {:intArg 5
:floatArg 3.14
:stringArg "This is a string"}
:result {:id "abcd"
:stringField "This worked"
:numberField 5
:nullField nil}
:entities {"root"
{:id "abcd"
:nullField nil
"numberField({\"intArg\":5,\"floatArg\":3.14})" 5
"stringField({\"arg\":\"This is a string\"})" "This worked"
::cache "root"}}}
:default-vars
{:query (d/parse-document
"query someBigQuery(
$stringArg: String = \"This is a default string\"
$intArg: Int
$floatArg: Float
) {
id
stringField(arg: $stringArg)
numberField(intArg: $intArg, floatArg: $floatArg)
nullField
}")
:input-vars {:intArg 5
:floatArg 3.14}
:result {:id "abcd"
:stringField "This worked"
:numberField 5
:nullField nil}
:entities {"root"
{:id "abcd"
:nullField nil
"numberField({\"intArg\":5,\"floatArg\":3.14})" 5
"stringField({\"arg\":\"This is a default string\"})" "This worked"
::cache "root"}}}
:directives
{:query (d/parse-document
"{
id
firstName @include(if: true)
lastName @upperCase
birthDate @dateFormat(format: \"DD-MM-YYYY\")
}")
:result {:id "abcd"
:firstName "PI:NAME:<NAME>END_PI"
:lastName "PI:NAME:<NAME>END_PI"
:birthDate "20-05-1940"}
:entities {"root"
{:id "abcd"
:firstName "PI:NAME:<NAME>END_PI"
"lastName@upperCase" "PI:NAME:<NAME>END_PI"
"birthDate@dateFormat({\"format\":\"DD-MM-YYYY\"})" "20-05-1940"
::cache "root"}}}
:nested
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:id "abcde"
:stringField "this is a string too"
:numberField 3
:nullField nil}}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:artemis.mapgraph/ref "abcde"}
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string too"
:numberField 3
:nullField nil}}}
:nested-no-id
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:stringField "this is a string too"
:numberField 3
:nullField nil}}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:artemis.mapgraph/ref "root.nestedObj"}
::cache "root"}
"root.nestedObj"
{:stringField "this is a string too"
:numberField 3
:nullField nil
::cache "root.nestedObj"}}}
:nested-with-args
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj(arg:\"val\") {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj {:stringField "this is a string too"
:numberField 3
:nullField nil}}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
"nestedObj({\"arg\":\"val\"})" {:artemis.mapgraph/ref "root.nestedObj({\"arg\":\"val\"})"}
::cache "root"}
"root.nestedObj({\"arg\":\"val\"})"
{:stringField "this is a string too"
:numberField 3
:nullField nil
::cache "root.nestedObj({\"arg\":\"val\"})"}}}
:nested-array
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}
{:id "abcdef"
:stringField "this is a string also"
:numberField 3
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "abcde"}
{:artemis.mapgraph/ref "abcdef"}]
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}
"abcdef"
{:id "abcdef"
:stringField "this is a string also"
:numberField 3
:nullField nil}}}
:nested-array-with-null
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}
nil]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "abcde"} nil]
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string too"
:numberField 2
:nullField nil}}}
:deeply-nested-array
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
stringField
numberField
nullField
deeplyNestedArray {
numberField
stringField
}
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:stringField "this is a string too"
:numberField 2
:nullField nil
:deeplyNestedArray [{:numberField 10
:stringField "Foo"}
{:numberField 20
:stringField "Bar"}]}
{:stringField "this is a string also"
:numberField 3
:deeplyNestedArray [{:numberField 30
:stringField "Baz"}
{:numberField 40
:stringField "Boo"}]
:nullField nil}
{:stringField "this is a string, man"
:numberField 6
:deeplyNestedArray []
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "root.nestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.1"}
{:artemis.mapgraph/ref "root.nestedArray.2"}]
::cache "root"}
"root.nestedArray.0"
{:stringField "this is a string too"
:numberField 2
:nullField nil
:deeplyNestedArray [{:artemis.mapgraph/ref "root.nestedArray.0.deeplyNestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.0.deeplyNestedArray.1"}]
::cache "root.nestedArray.0"}
"root.nestedArray.1"
{:stringField "this is a string also"
:numberField 3
:nullField nil
:deeplyNestedArray [{:artemis.mapgraph/ref "root.nestedArray.1.deeplyNestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.1.deeplyNestedArray.1"}]
::cache "root.nestedArray.1"}
"root.nestedArray.2"
{:stringField "this is a string, man"
:numberField 6
:nullField nil
:deeplyNestedArray []
::cache "root.nestedArray.2"}
"root.nestedArray.0.deeplyNestedArray.0"
{:numberField 10
:stringField "Foo"
::cache "root.nestedArray.0.deeplyNestedArray.0"}
"root.nestedArray.0.deeplyNestedArray.1"
{:numberField 20
:stringField "Bar"
::cache "root.nestedArray.0.deeplyNestedArray.1"}
"root.nestedArray.1.deeplyNestedArray.0"
{:numberField 30
:stringField "Baz"
::cache "root.nestedArray.1.deeplyNestedArray.0"}
"root.nestedArray.1.deeplyNestedArray.1"
{:numberField 40
:stringField "Boo"
::cache "root.nestedArray.1.deeplyNestedArray.1"}}}
:nested-array-without-ids
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:stringField "this is a string too"
:numberField 2
:nullField nil}
{:stringField "this is a string also"
:numberField 3
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [{:artemis.mapgraph/ref "root.nestedArray.0"}
{:artemis.mapgraph/ref "root.nestedArray.1"}]
::cache "root"}
"root.nestedArray.0"
{:stringField "this is a string too"
:numberField 2
:nullField nil
::cache "root.nestedArray.0"}
"root.nestedArray.1"
{:stringField "this is a string also"
:numberField 3
:nullField nil
::cache "root.nestedArray.1"}}}
:nested-array-with-nulls-and-no-ids
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedArray {
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [nil
{:stringField "this is a string also"
:numberField 3
:nullField nil}]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 1
:nullField nil
:nestedArray [nil
{:artemis.mapgraph/ref "root.nestedArray.1"}]
::cache "root"}
"root.nestedArray.1"
{:stringField "this is a string also"
:numberField 3
:nullField nil
::cache "root.nestedArray.1"}}}
:simple-array
{:query (d/parse-document
"{
id
stringField
numberField
nullField
simpleArray
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray ["one" "two" "three"]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray ["one" "two" "three"]
::cache "root"}}}
:simple-array-with-nulls
{:query (d/parse-document
"{
id
stringField
numberField
nullField
simpleArray
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray [nil "two" "three"]}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:simpleArray [nil "two" "three"]
::cache "root"}}}
:obj-in-different-paths
{:query (d/parse-document
"{
id
object1 {
id
stringField
}
object2 {
id
numberField
}
}")
:result {:id "a"
:object1 {:id "aa"
:stringField "this is a string"}
:object2 {:id "aa"
:numberField 1}}
:entities {"root"
{:id "a"
:object1 {:artemis.mapgraph/ref "aa"}
:object2 {:artemis.mapgraph/ref "aa"}
::cache "root"}
"aa"
{:id "aa"
:stringField "this is a string"
:numberField 1}}}
:obj-in-different-array-paths
{:query (d/parse-document
"{
id
array1 {
id
stringField
obj {
id
stringField
}
}
array2 {
id
stringField
obj {
id
numberField
}
}
}")
:result {:id "a"
:array1 [{:id "aa"
:stringField "this is a string"
:obj {:id "aaa"
:stringField "string"}}]
:array2 [{:id "ab"
:stringField "this is a string too"
:obj {:id "aaa"
:numberField 1}}]}
:entities {"root"
{:id "a"
:array1 [{:artemis.mapgraph/ref "aa"}]
:array2 [{:artemis.mapgraph/ref "ab"}]
::cache "root"}
"aa"
{:id "aa"
:stringField "this is a string"
:obj {:artemis.mapgraph/ref "aaa"}}
"ab"
{:id "ab"
:stringField "this is a string too"
:obj {:artemis.mapgraph/ref "aaa"}}
"aaa"
{:id "aaa"
:stringField "string"
:numberField 1}}}
:nested-object-returning-null
{:query (d/parse-document
"{
id
stringField
numberField
nullField
nestedObj {
id
stringField
numberField
nullField
}
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj nil}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:nullField nil
:nestedObj nil
::cache "root"}}}
:union-array
{:query (d/parse-document
"{
search(text: \"a\") {
... on object {
id
stringField
__typename
}
... on otherobject {
id
numberField
__typename
}
}
}")
:result {:search
[{:id "abcd"
:stringField "this is a string"
:__typename "object"}
{:id "efgh"
:numberField 3
:__typename "otherobject"}]}
:entities {"root"
{"search({\"text\":\"a\"})" [{:artemis.mapgraph/ref "abcd"}
{:artemis.mapgraph/ref "efgh"}]
::cache "root"}
"abcd"
{:id "abcd"
:stringField "this is a string"
:__typename "object"}
"efgh"
{:id "efgh"
:numberField 3
:__typename "otherobject"}}}
:union-array-no-id
{:query (d/parse-document
"{
search(text: \"a\") {
... on someobject {
stringField
__typename
}
}
}")
:result {:search
[{:stringField "this is a string"
:__typename "someobject"}
{:stringField "this is another string"
:__typename "someobject"}]}
:entities {"root"
{"search({\"text\":\"a\"})" [{:artemis.mapgraph/ref "root.search({\"text\":\"a\"}).0"}
{:artemis.mapgraph/ref "root.search({\"text\":\"a\"}).1"}]
::cache "root"}
"root.search({\"text\":\"a\"}).0"
{:stringField "this is a string"
:__typename "someobject"
::cache "root.search({\"text\":\"a\"}).0"}
"root.search({\"text\":\"a\"}).1"
{:stringField "this is another string"
:__typename "someobject"
::cache "root.search({\"text\":\"a\"}).1"}}}
:nested-union
{:query (d/parse-document
"{
id
stringField
unionObj {
... on object {
id
numberField
stringField
__typename
}
... on otherobject {
id
stringField
__typename
}
}
}")
:result {:id "a"
:stringField "this is a string"
:unionObj {:id "abcd"
:stringField "this is a string"
:numberField 3
:__typename "object"}}
:entities {"root"
{:id "a"
:stringField "this is a string"
:unionObj {:artemis.mapgraph/ref "abcd"}
::cache "root"}
"abcd"
{:id "abcd"
:stringField "this is a string"
:numberField 3
:__typename "object"}}}
:nested-union-no-id
{:query (d/parse-document
"{
id
stringField
unionObj {
... on someobject {
numberField
stringField
__typename
}
... on someotherobject {
stringField
__typename
}
}
}")
:result {:id "a"
:stringField "this is a string"
:unionObj {:stringField "this is a string"
:numberField 3
:__typename "someobject"}}
:entities {"root"
{:id "a"
:stringField "this is a string"
:unionObj {:artemis.mapgraph/ref "root.unionObj"}
::cache "root"}
"root.unionObj"
{:stringField "this is a string"
:numberField 3
:__typename "someobject"
::cache "root.unionObj"}}}
:fragments
{:query (d/parse-document
"query SomeQuery {
id
...OtherFields
}
fragment OtherFields on object {
stringField
numberField
}")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
::cache "root"}}}
:nested-fragments
{:query (d/parse-document
"query SomeQuery {
id
nestedObj {
id
...OtherFields
}
}
fragment OtherFields on object {
stringField
numberField
}")
:result {:id "abcd"
:nestedObj {:id "abcde"
:stringField "this is a string"
:numberField 3}}
:entities {"root"
{:id "abcd"
:nestedObj {:artemis.mapgraph/ref "abcde"}
::cache "root"}
"abcde"
{:id "abcde"
:stringField "this is a string"
:numberField 3}}}
:chained-fragments
{:query (d/parse-document
"query SomeQuery {
id
...OtherFields
}
fragment OtherFields on object {
stringField
...EvenOtherFields
}
fragment EvenOtherFields on object {
numberField
}
")
:result {:id "abcd"
:stringField "this is a string"
:numberField 3}
:entities {"root"
{:id "abcd"
:stringField "this is a string"
:numberField 3
::cache "root"}}}})
(defn write-test [k]
(testing (str "testing normalized cache persistence for query type: " k)
(let [{:keys [query input-vars result entities]} (get test-queries k)
initial-store (create-store :cache-key ::cache)
new-store (a/write initial-store {:data result} query input-vars)]
(is (= entities (:entities new-store))))))
(deftest test-cache-persistence
(doseq [test-query (keys test-queries)]
(write-test test-query)))
(defn read-test [k]
(testing (str "testing normalized cache querying for query type: " k)
(let [{:keys [query input-vars result entities]} (get test-queries k)
store (create-store :entities entities
:cache-key ::cache)
response (a/read store query input-vars)]
(is (= {:data result} response)))))
(deftest test-cache-reading
(doseq [test-query (keys test-queries)]
(read-test test-query)))
(def test-fragments
{:basic
{:fragment (d/parse-document
"fragment A on object {
stringField
}")
:entities {"abcde"
{:id "abcde"
:stringField "this is a string"
:numberField 3
:nullField nil
::cache "root"}}
:entity "abcde"
:write-data {:stringField "this is a different string"}
:read-result {:stringField "this is a string"}}
:nested-fragments
{:fragment (d/compose
(d/parse-document
"fragment A on B {
slug
friends {
...C
}
}")
(d/parse-document
"fragment C on D {
slug
name
address {
...D
}
}")
(d/parse-document
"fragment D on E {
zip
}"))
:entities {[:slug "abc"]
{:slug "abc"
:friends [{:artemis.mapgraph/ref [:slug "abcd"]}
{:artemis.mapgraph/ref [:slug "abcde"]}]}
[:slug "abcd"]
{:slug "abcd"
:name "PI:NAME:<NAME>END_PI"
:address {:artemis.mapgraph/ref 1}}
1
{:id 1 :street "test 1" :zip 11222}
2
{:id 2 :street "test 2" :zip 03062}
[:slug "abcde"]
{:slug "abcde"
:name "PI:NAME:<NAME>END_PI"
:address {:artemis.mapgraph/ref 2}}}
:entity [:slug "abc"]
:read-result {:slug "abc"
:friends [{:slug "abcd" :name "PI:NAME:<NAME>END_PI" :address {:zip 11222}}
{:slug "abcde" :name "PI:NAME:<NAME>END_PI" :address {:zip 03062}}]}}
:multiple-fields
{:fragment (d/parse-document
"fragment A on object {
numberField
stringField
}")
:entities {"abcde"
{:id "abcde"
:stringField "this is a string"
:numberField 3}}
:entity "abcde"
:write-data {:stringField "this is a different string"
:numberField 4}
:read-result {:stringField "this is a string"
:numberField 3}}})
(defn write-fragment-test [k]
(testing (str "testing normalized cache persistence for fragment type: " k)
(let [{:keys [fragment entity write-data entities]} (get test-fragments k)
initial-store (create-store :entities entities
:cache-key ::cache)
old-ent (get (:entities initial-store) entity)
new-store (a/write-fragment initial-store {:data write-data} fragment entity)
new-ent (get (:entities new-store) entity)]
(is (= new-ent (merge old-ent new-ent))))))
(deftest test-cache-fragment-persistence
(doseq [test-fragment (keys test-fragments)]
(write-fragment-test test-fragment)))
(defn read-fragment-test [k]
(testing (str "testing normalized cache reading for fragment type: " k)
(let [{:keys [fragment entity entities read-result]} (get test-fragments k)
store (create-store :entities entities
:cache-key ::cache)
response (a/read-fragment store fragment entity)]
(is (= {:data read-result} response)))))
(deftest test-cache-fragment-reading
(doseq [test-fragment (keys test-fragments)]
(read-fragment-test test-fragment)))
(deftest return-partial
(let [entities {"root"
{:object1 {:artemis.mapgraph/ref "aa"}
::cache "root"}
"aa"
{:id "aa"
:stringField "this is a string"
:otherObject {:artemis.mapgraph/ref "bb"}}
"bb"
{:id "bb"}}
store (create-store :entities entities
:cache-key ::cache)]
(testing "query return-partial"
(testing "set to true and all data not present"
(let [query (d/parse-document "{
object1 {
id
stringField
numberField
}
}")]
(is (= (:data (a/read store query {} :return-partial? true))
{:object1
{:id "aa"
:stringField "this is a string"}}))))
(testing "set to false nested key doesn't exist"
(let [query (d/parse-document "{
object1 {
id
stringField
doesntExist { slug }
}
}")]
(is (nil? (:data (a/read store query {}))))))
(testing "set to false all data not present"
(let [query (d/parse-document "{
object1 {
id
stringField
numberField
}
}")]
(is (nil? (:data (a/read store query {}))))))
(testing "set to false all data not present deeply"
(let [query (d/parse-document "{
object1 {
otherObject {
title
}
id
}
}")]
(is (nil? (:data (a/read store query {})))))))
(testing "fragment return-partial"
(testing "set to true and all data not present"
(let [fragment (d/parse-document "fragment A on object {
id
stringField
numberField
}")]
(is (= (:data (a/read-fragment store fragment "aa" :return-partial? true))
{:id "aa"
:stringField "this is a string"}))))
(testing "set to true and all data not present"
(let [fragment (d/parse-document "fragment A on object {
id
stringField
numberField
}")]
(is (nil? (:data (a/read-fragment store fragment "aa")))))))))
(def cache-redirects-map
{:book (comp :id :variables)
:featuredBook (comp #(when (= % "bob") 1) :slug :variables)})
(deftest cache-redirects
(let [entities {"root"
{::cache "root"
"author({\"slug\":\"bob\"})" {:artemis.mapgraph/ref "bob"}
"books" [{:artemis.mapgraph/ref 1} {:artemis.mapgraph/ref 2}]}
"bob" {:slug "bob"}
1 {:id 1 :title "Book 1", :abstract "Lorem ipsum..."}
2 {:id 2 :title "Book 2", :abstract "Lorem ipsum..."}}
store (create-store :entities entities
:cache-redirects cache-redirects-map
:cache-key ::cache)]
(testing "simple redirect"
(let [query (d/parse-document "{
book(id: $id) {
id
title
abstract
}
}")]
(is (= (:data (a/read store query {:id 1}))
{:book {:id 1
:title "Book 1"
:abstract "Lorem ipsum..."}}))
(is (= (:data (a/read store query {:id 2}))
{:book {:id 2
:title "Book 2"
:abstract "Lorem ipsum..."}}))
(is (= (:data (a/read store query {:id 3}))
nil))))
(testing "deep redirect"
(let [query (d/parse-document "{
author(slug: $slug) {
featuredBook {
title
}
}
}")]
(is (= (:data (a/read store query {:slug "bob"}))
{:author {:featuredBook {:title "Book 1"}}}))))
(testing "mixed with non-redirect fields"
(let [query (d/parse-document "{
author(slug: $slug) {
slug
featuredBook {
title
}
}
}")]
(is (= (:data (a/read store query {:slug "bob"}))
{:author {:slug "bob"
:featuredBook {:title "Book 1"}}}))))))
|
[
{
"context": "v* \n;; tag::test-basic-query-d[]\n[{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db",
"end": 374,
"score": 0.7475860714912415,
"start": 372,
"tag": "NAME",
"value": "an"
},
{
"context": "test-basic-query-d[]\n[{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :n",
"end": 388,
"score": 0.9997047185897827,
"start": 384,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "\n[{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-nam",
"end": 410,
"score": 0.9996775984764099,
"start": 404,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "e \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db",
"end": 433,
"score": 0.5481352806091309,
"start": 431,
"tag": "NAME",
"value": "tr"
},
{
"context": "last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :",
"end": 447,
"score": 0.9997187852859497,
"start": 443,
"tag": "NAME",
"value": "Petr"
},
{
"context": "\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-n",
"end": 469,
"score": 0.9995290040969849,
"start": 463,
"tag": "NAME",
"value": "Petrov"
},
{
"context": "ame \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}]\n;; end::te",
"end": 493,
"score": 0.5929147005081177,
"start": 488,
"tag": "NAME",
"value": "smith"
},
{
"context": "ast-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}]\n;; end::test-basic-query-",
"end": 508,
"score": 0.9997352361679077,
"start": 503,
"tag": "NAME",
"value": "Smith"
},
{
"context": "{:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}]\n;; end::test-basic-query-d[]\n)\n\n (t/testing \"",
"end": 529,
"score": 0.9997760057449341,
"start": 524,
"tag": "NAME",
"value": "Smith"
},
{
"context": " [p1 :last-name name]\n [p1 :name \"Smith\"]]}\n;; end::test-basic-query-q[]\n))))))\n\n(t/defte",
"end": 889,
"score": 0.9997522234916687,
"start": 884,
"tag": "NAME",
"value": "Smith"
},
{
"context": ";; tag::query-with-arguments-d[]\n[{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db",
"end": 1066,
"score": 0.8335156440734863,
"start": 1064,
"tag": "NAME",
"value": "an"
},
{
"context": "y-with-arguments-d[]\n[{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :n",
"end": 1080,
"score": 0.9997208118438721,
"start": 1076,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "\n[{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-nam",
"end": 1102,
"score": 0.9997074007987976,
"start": 1096,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "e \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db",
"end": 1125,
"score": 0.4624060094356537,
"start": 1123,
"tag": "NAME",
"value": "tr"
},
{
"context": "last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :",
"end": 1139,
"score": 0.9997144341468811,
"start": 1135,
"tag": "NAME",
"value": "Petr"
},
{
"context": "\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-n",
"end": 1161,
"score": 0.9996148347854614,
"start": 1155,
"tag": "NAME",
"value": "Petrov"
},
{
"context": "ame \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}]\n;; end::qu",
"end": 1185,
"score": 0.7535748481750488,
"start": 1180,
"tag": "NAME",
"value": "smith"
},
{
"context": "ast-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}]\n;; end::query-with-argume",
"end": 1200,
"score": 0.9996508955955505,
"start": 1195,
"tag": "NAME",
"value": "Smith"
},
{
"context": "{:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}]\n;; end::query-with-arguments-d[]\n ",
"end": 1221,
"score": 0.9997644424438477,
"start": 1216,
"tag": "NAME",
"value": "Smith"
},
{
"context": " (t/is (=\n;; tag::query-with-arguments1-r[]\n#{[\"Ivan\"]}\n;; end::query-with-arguments1-r[]\n ",
"end": 1420,
"score": 0.9983351230621338,
"start": 1416,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "e :name name]]\n :args [{:e :ivan \n :name \"Ivan\"}]}\n;; end::query-with-arguments1-q[]\n)))))\n\n ",
"end": 1630,
"score": 0.9996269941329956,
"start": 1626,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "nd [e]\n :where [[e :name name]]\n :args [{:name \"Ivan\"}\n {:name \"Petr\"}]}\n;; end::query-with-ar",
"end": 2003,
"score": 0.9997249841690063,
"start": 1999,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "e name]]\n :args [{:name \"Ivan\"}\n {:name \"Petr\"}]}\n;; end::query-with-arguments2-q[]\n)))))\n\n ",
"end": 2027,
"score": 0.9997628331184387,
"start": 2023,
"tag": "NAME",
"value": "Petr"
},
{
"context": " [e :last-name last-name]]\n :args [{:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Petr\" :last",
"end": 2432,
"score": 0.9997736215591431,
"start": 2428,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ame last-name]]\n :args [{:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Petr\" :last-name \"Petrov\"}]}\n;;",
"end": 2452,
"score": 0.9997262954711914,
"start": 2446,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": ":name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Petr\" :last-name \"Petrov\"}]}\n;; end::query-with-argume",
"end": 2475,
"score": 0.9998096227645874,
"start": 2471,
"tag": "NAME",
"value": "Petr"
},
{
"context": "-name \"Ivanov\"}\n {:name \"Petr\" :last-name \"Petrov\"}]}\n;; end::query-with-arguments3-q[]\n ",
"end": 2495,
"score": 0.9997308254241943,
"start": 2489,
"tag": "NAME",
"value": "Petrov"
},
{
"context": " (t/is (= \n;; tag::query-with-arguments4-r[]\n#{[\"Ivan\"]}\n;; end::query-with-arguments4-r[]\n ",
"end": 2679,
"score": 0.9953539371490479,
"start": 2675,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "re [[(re-find #\"I\" name)]\n [(= last-name \"Ivanov\")]]\n :args [{:name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 2903,
"score": 0.999814510345459,
"start": 2897,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " [(= last-name \"Ivanov\")]]\n :args [{:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Petr\" :last",
"end": 2928,
"score": 0.9998061060905457,
"start": 2924,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ame \"Ivanov\")]]\n :args [{:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Petr\" :last-name \"Petrov\"}]}\n;;",
"end": 2948,
"score": 0.999742329120636,
"start": 2942,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": ":name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Petr\" :last-name \"Petrov\"}]}\n;; end::query-with-argume",
"end": 2971,
"score": 0.9998214244842529,
"start": 2967,
"tag": "NAME",
"value": "Petr"
},
{
"context": "-name \"Ivanov\"}\n {:name \"Petr\" :last-name \"Petrov\"}]}\n;; end::query-with-arguments4-q[]\n ",
"end": 2991,
"score": 0.9996052980422974,
"start": 2985,
"tag": "NAME",
"value": "Petrov"
},
{
"context": "ag::query-at-t-d1[]\n[{:crux.db/id :malcolm :name \"Malcolm\" :last-name \"Sparks\"}]\n#inst \"1986-10-22\"\n;; end:",
"end": 3580,
"score": 0.9998401999473572,
"start": 3573,
"tag": "NAME",
"value": "Malcolm"
},
{
"context": "{:crux.db/id :malcolm :name \"Malcolm\" :last-name \"Sparks\"}]\n#inst \"1986-10-22\"\n;; end::query-at-t-d1[]\n ",
"end": 3600,
"score": 0.9995240569114685,
"start": 3594,
"tag": "NAME",
"value": "Sparks"
},
{
"context": "ag::query-at-t-d2[]\n[{:crux.db/id :malcolm :name \"Malcolma\" :last-name \"Sparks\"}]\n#inst \"1986-10-24\")\n;; end",
"end": 3796,
"score": 0.999845564365387,
"start": 3788,
"tag": "NAME",
"value": "Malcolma"
},
{
"context": ":crux.db/id :malcolm :name \"Malcolma\" :last-name \"Sparks\"}]\n#inst \"1986-10-24\")\n;; end::query-at-t-d2[]\n ",
"end": 3816,
"score": 0.999803364276886,
"start": 3810,
"tag": "NAME",
"value": "Sparks"
},
{
"context": "tag::query-at-t-q[]\n{:find [e]\n :where [[e :name \"Malcolma\"]\n [e :last-name \"Sparks\"]]}\n;; end::quer",
"end": 3954,
"score": 0.9997971653938293,
"start": 3946,
"tag": "NAME",
"value": "Malcolma"
},
{
"context": "ere [[e :name \"Malcolma\"]\n [e :last-name \"Sparks\"]]}\n;; end::query-at-t-q[]\n )]\n ",
"end": 3987,
"score": 0.9992826581001282,
"start": 3981,
"tag": "NAME",
"value": "Sparks"
},
{
"context": "{:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 100}\n #inst \"2018-05-18T0",
"end": 4630,
"score": 0.999707818031311,
"start": 4626,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "{:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 1000}\n #inst \"2015-05-18T",
"end": 4787,
"score": 0.9996808171272278,
"start": 4783,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "bc3ab1c6613\")\n\n; yields\n{:crux.db/id :ids.persons/Jeff,\n :d.person/name \"Jeff\",\n :d.person/wealth 100}\n;",
"end": 6752,
"score": 0.6943720579147339,
"start": 6748,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "\n{:crux.db/id :ids.persons/Jeff,\n :d.person/name \"Jeff\",\n :d.person/wealth 100}\n;; end::history-range[]\n",
"end": 6775,
"score": 0.9994641542434692,
"start": 6771,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "*kv* \n;; tag::join-d[]\n[{:crux.db/id :ivan :name \"Ivan\"}\n {:crux.db/id :petr :name \"Petr\"}\n {:crux.db/id",
"end": 7005,
"score": 0.9989855289459229,
"start": 7001,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "\n[{:crux.db/id :ivan :name \"Ivan\"}\n {:crux.db/id :petr :name \"Petr\"}\n {:crux.db/id :sergei :name \"Sergei",
"end": 7027,
"score": 0.5216311812400818,
"start": 7023,
"tag": "NAME",
"value": "petr"
},
{
"context": "id :ivan :name \"Ivan\"}\n {:crux.db/id :petr :name \"Petr\"}\n {:crux.db/id :sergei :name \"Sergei\"}\n {:crux.d",
"end": 7039,
"score": 0.9977748394012451,
"start": 7035,
"tag": "NAME",
"value": "Petr"
},
{
"context": " :petr :name \"Petr\"}\n {:crux.db/id :sergei :name \"Sergei\"}\n {:crux.db/id :denis-a :name \"Denis\"}\n {:crux.d",
"end": 7077,
"score": 0.9958198666572571,
"start": 7071,
"tag": "NAME",
"value": "Sergei"
},
{
"context": "gei :name \"Sergei\"}\n {:crux.db/id :denis-a :name \"Denis\"}\n {:crux.db/id :denis-b :name \"Denis\"}]\n;; end::",
"end": 7115,
"score": 0.9992336630821228,
"start": 7110,
"tag": "NAME",
"value": "Denis"
},
{
"context": "is-a :name \"Denis\"}\n {:crux.db/id :denis-b :name \"Denis\"}]\n;; end::join-d[]\n)\n\n (t/testing \"Every person",
"end": 7153,
"score": 0.9996175169944763,
"start": 7148,
"tag": "NAME",
"value": "Denis"
},
{
"context": "kv* \n;; tag::join2-d[]\n[{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :petr :name \"",
"end": 7693,
"score": 0.9997292757034302,
"start": 7689,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "-d[]\n[{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :petr :name \"Petr\" :follows #{\"Iv",
"end": 7713,
"score": 0.9998070597648621,
"start": 7707,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "\" :last-name \"Ivanov\"}\n {:crux.db/id :petr :name \"Petr\" :follows #{\"Ivanov\"}}]\n;; end::join2-d[]\n)\n\n (t",
"end": 7747,
"score": 0.99953693151474,
"start": 7743,
"tag": "NAME",
"value": "Petr"
},
{
"context": " [e2 :follows last-name]\n [e :name \"Ivan\"]]}\n;; end::join2-q[]\n ",
"end": 8010,
"score": 0.9997955560684204,
"start": 8006,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "t test-blanks\n (f/transact-people! *kv* [{:name \"Ivan\"} {:name \"Petr\"} {:name \"Sergei\"}])\n\n (t/is (= #",
"end": 8149,
"score": 0.9998356103897095,
"start": 8145,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (f/transact-people! *kv* [{:name \"Ivan\"} {:name \"Petr\"} {:name \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"Pet",
"end": 8164,
"score": 0.9998356103897095,
"start": 8160,
"tag": "NAME",
"value": "Petr"
},
{
"context": "ople! *kv* [{:name \"Ivan\"} {:name \"Petr\"} {:name \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n ",
"end": 8181,
"score": 0.9998559355735779,
"start": 8175,
"tag": "NAME",
"value": "Sergei"
},
{
"context": "{:name \"Petr\"} {:name \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n (api/q (api/db ",
"end": 8206,
"score": 0.9998377561569214,
"start": 8202,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "etr\"} {:name \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n (api/q (api/db *kv*) '{:",
"end": 8215,
"score": 0.9998276829719543,
"start": 8211,
"tag": "NAME",
"value": "Petr"
},
{
"context": "ame \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n (api/q (api/db *kv*) '{:find [name]",
"end": 8226,
"score": 0.9998453259468079,
"start": 8220,
"tag": "NAME",
"value": "Sergei"
},
{
"context": "-people! *kv* [{:crux.db/id :ivan-ivanov-1 :name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 8461,
"score": 0.9997588992118835,
"start": 8457,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "rux.db/id :ivan-ivanov-1 :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :ivan-",
"end": 8481,
"score": 0.9997175335884094,
"start": 8475,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:crux.db/id :ivan-ivanov-2 :name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 8551,
"score": 0.9997634291648865,
"start": 8547,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "rux.db/id :ivan-ivanov-2 :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :ivan-",
"end": 8571,
"score": 0.9997299313545227,
"start": 8565,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:crux.db/id :ivan-ivanovtov-1 :name \"Ivan\" :last-name \"Ivannotov\"}])\n\n (t/testing \"literal",
"end": 8644,
"score": 0.9997377991676331,
"start": 8640,
"tag": "NAME",
"value": "Ivan"
},
{
"context": ".db/id :ivan-ivanovtov-1 :name \"Ivan\" :last-name \"Ivannotov\"}])\n\n (t/testing \"literal v\"\n (t/is (= 2 (cou",
"end": 8667,
"score": 0.9997908473014832,
"start": 8658,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": " [e :name \"Ivan\"]\n ",
"end": 8880,
"score": 0.999657154083252,
"start": 8876,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (not [e :last-name \"Ivannotov\"])]}))))\n\n (t/testing \"multiple clauses in not",
"end": 8961,
"score": 0.9998180866241455,
"start": 8952,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": " [e :name \"Ivan\"]\n ",
"end": 9201,
"score": 0.9997228384017944,
"start": 9197,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (not [e :last-name \"Ivannotov\"]\n ",
"end": 9284,
"score": 0.9997813701629639,
"start": 9275,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": "test-or-query\n (f/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 9780,
"score": 0.999797523021698,
"start": 9776,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Ivan\" :last",
"end": 9800,
"score": 0.9997383952140808,
"start": 9794,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "ame \"Ivanov\"}\n {:name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 9843,
"score": 0.9998111724853516,
"start": 9839,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Ivan\" :last",
"end": 9863,
"score": 0.9997696876525879,
"start": 9857,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "ame \"Ivanov\"}\n {:name \"Ivan\" :last-name \"Ivannotov\"}\n ",
"end": 9906,
"score": 0.999808669090271,
"start": 9902,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:name \"Ivan\" :last-name \"Ivannotov\"}\n {:name \"Bob\" :last-",
"end": 9929,
"score": 0.9997344613075256,
"start": 9920,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": " \"Ivannotov\"}\n {:name \"Bob\" :last-name \"Controlguy\"}])\n\n (t/testing \"Or wor",
"end": 9971,
"score": 0.9998349547386169,
"start": 9968,
"tag": "NAME",
"value": "Bob"
},
{
"context": " {:name \"Bob\" :last-name \"Controlguy\"}])\n\n (t/testing \"Or works as expected\"\n (t/i",
"end": 9995,
"score": 0.9993403553962708,
"start": 9985,
"tag": "NAME",
"value": "Controlguy"
},
{
"context": " [e :name \"Ivan\"]\n ",
"end": 10219,
"score": 0.999671220779419,
"start": 10215,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (or [e :last-name \"Ivanov\"]\n ",
"end": 10296,
"score": 0.9997756481170654,
"start": 10290,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " [e :last-name \"Ivannotov\"])]}))))))\n;; end::or[]\n\n;; tag::or-and[]\n(t/deft",
"end": 10376,
"score": 0.9996976256370544,
"start": 10367,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": "\n (let [[ivan] (f/transact-people! *kv* [{:name \"Ivan\" :sex :male}\n ",
"end": 10509,
"score": 0.9996342658996582,
"start": 10505,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "\n {:name \"Bob\" :sex :male}\n ",
"end": 10575,
"score": 0.9998306035995483,
"start": 10572,
"tag": "NAME",
"value": "Bob"
},
{
"context": "\n {:name \"Ivana\" :sex :female}])]\n\n (t/is (= #{[\"Ivan\"]\n ",
"end": 10643,
"score": 0.9996916055679321,
"start": 10638,
"tag": "NAME",
"value": "Ivana"
},
{
"context": "{:name \"Ivana\" :sex :female}])]\n\n (t/is (= #{[\"Ivan\"]\n [\"Ivana\"]}\n (api/q (",
"end": 10684,
"score": 0.9995073676109314,
"start": 10680,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ale}])]\n\n (t/is (= #{[\"Ivan\"]\n [\"Ivana\"]}\n (api/q (api/db *kv*) '{:find [nam",
"end": 10709,
"score": 0.9996587038040161,
"start": 10704,
"tag": "NAME",
"value": "Ivana"
},
{
"context": " [e :name \"Ivan\"]))]})))))\n;; end::or-and[]\n\n;; tag::or-and2[]\n(t",
"end": 11005,
"score": 0.9997162818908691,
"start": 11001,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "r ivan ivanova] (f/transact-people! *kv* [{:name \"Petr\" :last-name \"Smith\" :sex :male}\n ",
"end": 11166,
"score": 0.9997669458389282,
"start": 11162,
"tag": "NAME",
"value": "Petr"
},
{
"context": "/transact-people! *kv* [{:name \"Petr\" :last-name \"Smith\" :sex :male}\n ",
"end": 11185,
"score": 0.9994692802429199,
"start": 11180,
"tag": "NAME",
"value": "Smith"
},
{
"context": " {:name \"Ivan\" :last-name \"Ivanov\" :sex :male}\n ",
"end": 11265,
"score": 0.9997299909591675,
"start": 11261,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:name \"Ivan\" :last-name \"Ivanov\" :sex :male}\n ",
"end": 11285,
"score": 0.9997109770774841,
"start": 11279,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:name \"Ivanova\" :last-name \"Ivanov\" :sex :female}])]\n\n (t/tes",
"end": 11368,
"score": 0.9997904300689697,
"start": 11361,
"tag": "NAME",
"value": "Ivanova"
},
{
"context": " {:name \"Ivanova\" :last-name \"Ivanov\" :sex :female}])]\n\n (t/testing \"?p2 introduced",
"end": 11388,
"score": 0.999725878238678,
"start": 11382,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " :where [(or (and [?p2 :name \"Petr\"]\n ",
"end": 11626,
"score": 0.9997789859771729,
"start": 11622,
"tag": "NAME",
"value": "Petr"
},
{
"context": " (and [?p2 :last-name \"Ivanov\"]\n ",
"end": 11822,
"score": 0.9997602105140686,
"start": 11816,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "test-not-join\n (f/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 12030,
"score": 0.9998128414154053,
"start": 12026,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Malcolm\" :l",
"end": 12050,
"score": 0.9992752075195312,
"start": 12044,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "ame \"Ivanov\"}\n {:name \"Malcolm\" :last-name \"Ofsparks\"}\n ",
"end": 12096,
"score": 0.9998461604118347,
"start": 12089,
"tag": "NAME",
"value": "Malcolm"
},
{
"context": " {:name \"Malcolm\" :last-name \"Ofsparks\"}\n {:name \"Dominic\" :l",
"end": 12118,
"score": 0.9992859959602356,
"start": 12110,
"tag": "NAME",
"value": "Ofsparks"
},
{
"context": "e \"Ofsparks\"}\n {:name \"Dominic\" :last-name \"Monroe\"}])\n\n (t/testing \"Rudimentar",
"end": 12164,
"score": 0.9998493790626526,
"start": 12157,
"tag": "NAME",
"value": "Dominic"
},
{
"context": " {:name \"Dominic\" :last-name \"Monroe\"}])\n\n (t/testing \"Rudimentary not-join\"\n (t/i",
"end": 12184,
"score": 0.9987291693687439,
"start": 12178,
"tag": "NAME",
"value": "Monroe"
},
{
"context": "t/testing \"Rudimentary not-join\"\n (t/is (= #{[\"Ivan\"] [\"Malcolm\"]}\n (api/q (api/db *kv*) ",
"end": 12247,
"score": 0.9998166561126709,
"start": 12243,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " \"Rudimentary not-join\"\n (t/is (= #{[\"Ivan\"] [\"Malcolm\"]}\n (api/q (api/db *kv*) '{:find [nam",
"end": 12259,
"score": 0.9998190999031067,
"start": 12252,
"tag": "NAME",
"value": "Malcolm"
},
{
"context": " [e :last-name \"Monroe\"])]})))))\n;; end::not-join[]\n\n(t/deftest test-mix",
"end": 12492,
"score": 0.9997811913490295,
"start": 12486,
"tag": "NAME",
"value": "Monroe"
},
{
"context": "g-expressions\n (f/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 12598,
"score": 0.999794602394104,
"start": 12594,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Derek\" :las",
"end": 12618,
"score": 0.9997223019599915,
"start": 12612,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "ame \"Ivanov\"}\n {:name \"Derek\" :last-name \"Ivanov\"}\n ",
"end": 12662,
"score": 0.9998244047164917,
"start": 12657,
"tag": "NAME",
"value": "Derek"
},
{
"context": " {:name \"Derek\" :last-name \"Ivanov\"}\n {:name \"Bob\" :last-",
"end": 12682,
"score": 0.9997099041938782,
"start": 12676,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "ame \"Ivanov\"}\n {:name \"Bob\" :last-name \"Ivannotov\"}\n ",
"end": 12724,
"score": 0.999869167804718,
"start": 12721,
"tag": "NAME",
"value": "Bob"
},
{
"context": " {:name \"Bob\" :last-name \"Ivannotov\"}\n {:name \"Fred\" :last",
"end": 12747,
"score": 0.9997970461845398,
"start": 12738,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": " \"Ivannotov\"}\n {:name \"Fred\" :last-name \"Ivannotov\"}])\n\n (t/testing \"Or can ",
"end": 12790,
"score": 0.9998408555984497,
"start": 12786,
"tag": "NAME",
"value": "Fred"
},
{
"context": " {:name \"Fred\" :last-name \"Ivannotov\"}])\n\n (t/testing \"Or can use not expression\"\n ",
"end": 12813,
"score": 0.999805748462677,
"start": 12804,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": "ting \"Or can use not expression\"\n (t/is (= #{[\"Ivan\"] [\"Derek\"] [\"Fred\"]}\n (api/q (api/db",
"end": 12881,
"score": 0.9998112916946411,
"start": 12877,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "can use not expression\"\n (t/is (= #{[\"Ivan\"] [\"Derek\"] [\"Fred\"]}\n (api/q (api/db *kv*) '{:",
"end": 12891,
"score": 0.9997827410697937,
"start": 12886,
"tag": "NAME",
"value": "Derek"
},
{
"context": "t expression\"\n (t/is (= #{[\"Ivan\"] [\"Derek\"] [\"Fred\"]}\n (api/q (api/db *kv*) '{:find [nam",
"end": 12900,
"score": 0.9998497366905212,
"start": 12896,
"tag": "NAME",
"value": "Fred"
},
{
"context": " (or [e :last-name \"Ivanov\"]\n (no",
"end": 13073,
"score": 0.9997300505638123,
"start": 13067,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " (not [e :name \"Bob\"]))]}))))\n\n (t/testing \"Not can use Or expressio",
"end": 13138,
"score": 0.9998481273651123,
"start": 13135,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ting \"Not can use Or expression\"\n (t/is (= #{[\"Fred\"]} (api/q (api/db *kv*) '{:find [name]\n ",
"end": 13212,
"score": 0.999800443649292,
"start": 13208,
"tag": "NAME",
"value": "Fred"
},
{
"context": " (not (or [e :last-name \"Ivanov\"]\n ",
"end": 13401,
"score": 0.9997723698616028,
"start": 13395,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " [e :name \"Bob\"]))]})))))\n\n(t/deftest test-predicate-expression\n",
"end": 13478,
"score": 0.9998181462287903,
"start": 13475,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ression\n (f/transact-people! *kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\" :age 30}\n ",
"end": 13572,
"score": 0.7718603014945984,
"start": 13570,
"tag": "USERNAME",
"value": "iv"
},
{
"context": "ssion\n (f/transact-people! *kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\" :age 30}\n ",
"end": 13574,
"score": 0.5195025205612183,
"start": 13572,
"tag": "NAME",
"value": "an"
},
{
"context": "/transact-people! *kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\" :age 30}\n ",
"end": 13586,
"score": 0.9997763633728027,
"start": 13582,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "*kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\" :age 30}\n {:crux.db/i",
"end": 13606,
"score": 0.9997590184211731,
"start": 13600,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:crux.db/id :bob :name \"Bob\" :last-name \"Ivanov\" :age 40}\n ",
"end": 13673,
"score": 0.9997218251228333,
"start": 13670,
"tag": "NAME",
"value": "Bob"
},
{
"context": " {:crux.db/id :bob :name \"Bob\" :last-name \"Ivanov\" :age 40}\n {:crux.db/i",
"end": 13693,
"score": 0.999751091003418,
"start": 13687,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "age 40}\n {:crux.db/id :dominic :name \"Dominic\" :last-name \"Monroe\" :age 50}])\n\n ",
"end": 13753,
"score": 0.5570371150970459,
"start": 13746,
"tag": "NAME",
"value": "dominic"
},
{
"context": " {:crux.db/id :dominic :name \"Dominic\" :last-name \"Monroe\" :age 50}])\n\n (t/testing \"ra",
"end": 13768,
"score": 0.999789297580719,
"start": 13761,
"tag": "NAME",
"value": "Dominic"
},
{
"context": "{:crux.db/id :dominic :name \"Dominic\" :last-name \"Monroe\" :age 50}])\n\n (t/testing \"range expressions\"\n ",
"end": 13788,
"score": 0.9995749592781067,
"start": 13782,
"tag": "NAME",
"value": "Monroe"
},
{
"context": " (t/testing \"range expressions\"\n (t/is (= #{[\"Ivan\"] [\"Bob\"]}\n (api/q (api/db *kv*) '{:f",
"end": 13856,
"score": 0.9997555017471313,
"start": 13852,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ing \"range expressions\"\n (t/is (= #{[\"Ivan\"] [\"Bob\"]}\n (api/q (api/db *kv*) '{:find [nam",
"end": 13864,
"score": 0.9997426867485046,
"start": 13861,
"tag": "NAME",
"value": "Bob"
},
{
"context": " [(< age 50)]]})))\n\n (t/is (= #{[\"Dominic\"]}\n (api/q (api/db *kv*) '{:find [nam",
"end": 14108,
"score": 0.999725341796875,
"start": 14101,
"tag": "NAME",
"value": "Dominic"
},
{
"context": "testing \"clojure.core predicate\"\n (t/is (= #{[\"Bob\"] [\"Dominic\"]}\n (api/q (api/db *kv*) ",
"end": 14388,
"score": 0.9998401999473572,
"start": 14385,
"tag": "NAME",
"value": "Bob"
},
{
"context": "\"clojure.core predicate\"\n (t/is (= #{[\"Bob\"] [\"Dominic\"]}\n (api/q (api/db *kv*) '{:find [nam",
"end": 14400,
"score": 0.999738872051239,
"start": 14393,
"tag": "NAME",
"value": "Dominic"
},
{
"context": "sting \"Several variables\"\n (t/is (= #{[:bob \"Ivanov\"]}\n (api/q (api/db *kv*) '{:find [e",
"end": 14642,
"score": 0.9996907114982605,
"start": 14636,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "t/testing \"Bind result to var\"\n (t/is (= #{[\"Dominic\" 25] [\"Ivan\" 15] [\"Bob\" 20]}\n (api/",
"end": 15027,
"score": 0.9997561573982239,
"start": 15020,
"tag": "NAME",
"value": "Dominic"
},
{
"context": " result to var\"\n (t/is (= #{[\"Dominic\" 25] [\"Ivan\" 15] [\"Bob\" 20]}\n (api/q (api/db *k",
"end": 15039,
"score": 0.9997760653495789,
"start": 15035,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ar\"\n (t/is (= #{[\"Dominic\" 25] [\"Ivan\" 15] [\"Bob\" 20]}\n (api/q (api/db *kv*) '{:find",
"end": 15050,
"score": 0.9997931122779846,
"start": 15047,
"tag": "NAME",
"value": "Bob"
},
{
"context": "than once intersects result\"\n (t/is (= #{[\"Ivan\" 15]}\n (api/q (api/db *kv*) '{:fi",
"end": 15386,
"score": 0.9991940855979919,
"start": 15382,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ng can use range predicates\"\n (t/is (= #{[\"Dominic\" 25]}\n (api/q (api/db *kv*) '{:fi",
"end": 15807,
"score": 0.9632601141929626,
"start": 15800,
"tag": "NAME",
"value": "Dominic"
},
{
"context": "/transact-people! *kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\" :age 30 :friends #{:bob :dom",
"end": 16248,
"score": 0.999566912651062,
"start": 16244,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "*kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\" :age 30 :friends #{:bob :dominic}}\n ",
"end": 16268,
"score": 0.9994331002235413,
"start": 16262,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:crux.db/id :bob :name \"Bob\" :last-name \"Ivanov\" :age 40 :friends #{:ivan :do",
"end": 16361,
"score": 0.9997089505195618,
"start": 16358,
"tag": "NAME",
"value": "Bob"
},
{
"context": " {:crux.db/id :bob :name \"Bob\" :last-name \"Ivanov\" :age 40 :friends #{:ivan :dominic}}\n ",
"end": 16381,
"score": 0.9993779063224792,
"start": 16375,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:crux.db/id :dominic :name \"Dominic\" :last-name \"Monroe\" :age 50 :friends #{:bob}}])\n",
"end": 16483,
"score": 0.999710738658905,
"start": 16476,
"tag": "NAME",
"value": "Dominic"
},
{
"context": "{:crux.db/id :dominic :name \"Dominic\" :last-name \"Monroe\" :age 50 :friends #{:bob}}])\n\n (t/testing \"can f",
"end": 16503,
"score": 0.9997135996818542,
"start": 16497,
"tag": "NAME",
"value": "Monroe"
},
{
"context": " :where [[i :name \"Ivan\"]\n [i :fri",
"end": 16708,
"score": 0.9994895458221436,
"start": 16704,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "/transact-people! *kv* [{:crux.db/id :ivan :name \"Ivan\" :mentor :petr}\n {:cru",
"end": 16876,
"score": 0.9992865324020386,
"start": 16872,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:crux.db/id :petr :name \"Petr\" :mentor :oleg}\n {:cru",
"end": 16951,
"score": 0.9984647631645203,
"start": 16947,
"tag": "NAME",
"value": "Petr"
},
{
"context": " {:crux.db/id :oleg :name \"Oleg\" :mentor :ivan}])\n\n (t/is (= #{[:oleg \"Oleg\" :pe",
"end": 17026,
"score": 0.9976856112480164,
"start": 17022,
"tag": "NAME",
"value": "Oleg"
},
{
"context": "ame \"Oleg\" :mentor :ivan}])\n\n (t/is (= #{[:oleg \"Oleg\" :petr \"Petr\"]\n [:ivan \"Ivan\" :oleg \"",
"end": 17071,
"score": 0.9995823502540588,
"start": 17067,
"tag": "NAME",
"value": "Oleg"
},
{
"context": "entor :ivan}])\n\n (t/is (= #{[:oleg \"Oleg\" :petr \"Petr\"]\n [:ivan \"Ivan\" :oleg \"Oleg\"]\n ",
"end": 17084,
"score": 0.9996347427368164,
"start": 17080,
"tag": "NAME",
"value": "Petr"
},
{
"context": "{[:oleg \"Oleg\" :petr \"Petr\"]\n [:ivan \"Ivan\" :oleg \"Oleg\"]\n [:petr \"Petr\" :ivan \"",
"end": 17112,
"score": 0.9997170567512512,
"start": 17108,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "\" :petr \"Petr\"]\n [:ivan \"Ivan\" :oleg \"Oleg\"]\n [:petr \"Petr\" :ivan \"Ivan\"]} (api/",
"end": 17125,
"score": 0.9994668960571289,
"start": 17121,
"tag": "NAME",
"value": "Oleg"
},
{
"context": " [:ivan \"Ivan\" :oleg \"Oleg\"]\n [:petr \"Petr\" :ivan \"Ivan\"]} (api/q (api/db *kv*) '{:find [e1 ",
"end": 17153,
"score": 0.9997190237045288,
"start": 17149,
"tag": "NAME",
"value": "Petr"
},
{
"context": "\" :oleg \"Oleg\"]\n [:petr \"Petr\" :ivan \"Ivan\"]} (api/q (api/db *kv*) '{:find [e1 n1 e2 n2]\n ",
"end": 17166,
"score": 0.9997040629386902,
"start": 17162,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "/transact-people! *kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 17563,
"score": 0.9997130632400513,
"start": 17559,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "*kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :petr ",
"end": 17583,
"score": 0.9997052550315857,
"start": 17577,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:crux.db/id :petr :name \"Petr\" :last-name \"Petrov\" :mentor :ivan}])\n\n (t/is (=",
"end": 17644,
"score": 0.9997128248214722,
"start": 17640,
"tag": "NAME",
"value": "Petr"
},
{
"context": " {:crux.db/id :petr :name \"Petr\" :last-name \"Petrov\" :mentor :ivan}])\n\n (t/is (= #{[:petr :petr]} (a",
"end": 17664,
"score": 0.9976435303688049,
"start": 17658,
"tag": "NAME",
"value": "Petrov"
},
{
"context": " :where [[p1 :name \"Petr\"]\n ",
"end": 17819,
"score": 0.9996290802955627,
"start": 17815,
"tag": "NAME",
"value": "Petr"
},
{
"context": " [(== n #{\"Petr\" \"Ivan\"})]]})))))\n\n(t/deftest test-basic-rules\n ",
"end": 18215,
"score": 0.9995423555374146,
"start": 18211,
"tag": "NAME",
"value": "Petr"
},
{
"context": " [(== n #{\"Petr\" \"Ivan\"})]]})))))\n\n(t/deftest test-basic-rules\n (f/tran",
"end": 18222,
"score": 0.9991592168807983,
"start": 18218,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "/transact-people! *kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\" :age 21}\n ",
"end": 18321,
"score": 0.9997438192367554,
"start": 18317,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "*kv* [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\" :age 21}\n {:crux.db/i",
"end": 18341,
"score": 0.9997077584266663,
"start": 18335,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:crux.db/id :petr :name \"Petr\" :last-name \"Petrov\" :age 18}])\n\n (t/testing \"wi",
"end": 18410,
"score": 0.9997434020042419,
"start": 18406,
"tag": "NAME",
"value": "Petr"
},
{
"context": " {:crux.db/id :petr :name \"Petr\" :last-name \"Petrov\" :age 18}])\n\n (t/testing \"without rule\"\n (t/i",
"end": 18430,
"score": 0.9993668794631958,
"start": 18424,
"tag": "NAME",
"value": "Petrov"
},
{
"context": " [i :name \"Ivan\"]\n ",
"end": 20150,
"score": 0.9997324347496033,
"start": 20146,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " [i :last-name \"Ivanov\"]]\n ",
"end": 20226,
"score": 0.9997242093086243,
"start": 20220,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " [i :name \"Bob\"]]]})))\n\n (t/is (= #{[\"Petr\"]} (api/q (api/db ",
"end": 20367,
"score": 0.9996521472930908,
"start": 20364,
"tag": "NAME",
"value": "Bob"
},
{
"context": " [i :name \"Bob\"]]]})))\n\n (t/is (= #{[\"Petr\"]} (api/q (api/db *kv*) '{:find [name]\n ",
"end": 20398,
"score": 0.9246909618377686,
"start": 20394,
"tag": "NAME",
"value": "Petr"
},
{
"context": " [i :name \"Ivan\"]]\n ",
"end": 20724,
"score": 0.99955153465271,
"start": 20720,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " [i :name \"Bob\"]]]}))))\n\n\n;; https://www.comp.nus.edu.sg/~ooibc/",
"end": 20867,
"score": 0.9996620416641235,
"start": 20864,
"tag": "NAME",
"value": "Bob"
},
{
"context": "s borrowed from Datascript:\n;; https://github.com/tonsky/datascript/tree/master/test/datascript/test\n\n(def",
"end": 30895,
"score": 0.9995911717414856,
"start": 30889,
"tag": "USERNAME",
"value": "tonsky"
},
{
"context": "ransact-entity-maps! *kv* [{:crux.db/id :1 :name \"Ivan\" :age 10}\n {:crux",
"end": 31038,
"score": 0.9995280504226685,
"start": 31034,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:crux.db/id :2 :name \"Ivan\" :age 20}\n {:crux",
"end": 31109,
"score": 0.9996158480644226,
"start": 31105,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:crux.db/id :3 :name \"Oleg\" :age 10}\n {:crux",
"end": 31180,
"score": 0.9996039867401123,
"start": 31176,
"tag": "NAME",
"value": "Oleg"
},
{
"context": " {:crux.db/id :4 :name \"Oleg\" :age 20}\n {:crux",
"end": 31251,
"score": 0.9996038675308228,
"start": 31247,
"tag": "NAME",
"value": "Oleg"
},
{
"context": " {:crux.db/id :5 :name \"Ivan\" :age 10}\n {:crux",
"end": 31322,
"score": 0.9995626211166382,
"start": 31318,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:crux.db/id :6 :name \"Ivan\" :age 20} ]))\n\n(t/deftest test-rules\n (f/transac",
"end": 31393,
"score": 0.9995992183685303,
"start": 31389,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "nsact-entity-maps! f/*kv* [{:crux.db/id :1 :name \"Ivan\" :age 10}\n {:cr",
"end": 37605,
"score": 0.9991666078567505,
"start": 37601,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:crux.db/id :2 :name \"Ivan\" :age 20}\n {:cr",
"end": 37678,
"score": 0.999548614025116,
"start": 37674,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:crux.db/id :3 :name \"Oleg\" :age 10}\n {:cr",
"end": 37751,
"score": 0.9996675252914429,
"start": 37747,
"tag": "NAME",
"value": "Oleg"
},
{
"context": " {:crux.db/id :4 :name \"Oleg\" :age 20}])\n (let [db (api/db *kv*)]\n ;; NOTE",
"end": 37824,
"score": 0.9996882677078247,
"start": 37820,
"tag": "NAME",
"value": "Oleg"
},
{
"context": "; Tests from Racket Datalog\n;; https://github.com/racket/datalog/tree/master/tests/examples\n\n;; Tests from",
"end": 38272,
"score": 0.9974125623703003,
"start": 38266,
"tag": "USERNAME",
"value": "racket"
}
] | docs/query_test_examples.clj | maacl/crux | 0 | (ns crux.query-test
(:require [clojure.spec.alpha :as s]
[clojure.test :as t]
[crux.db :as db]
[crux.api :as api]
[crux.fixtures :as f :refer [*kv*]])
(:import java.util.UUID))
(t/use-fixtures :each f/with-kv-store)
(t/deftest test-basic-query
(f/transact-people! *kv*
;; tag::test-basic-query-d[]
[{:crux.db/id :ivan
:name "Ivan"
:last-name "Ivanov"}
{:crux.db/id :petr
:name "Petr"
:last-name "Petrov"}
{:crux.db/id :smith
:name "Smith"
:last-name "Smith"}]
;; end::test-basic-query-d[]
)
(t/testing "Can query across fields for same value when value is passed in"
(t/is (=
;; tag::test-basic-query-r[]
#{[:smith]}
;; end::test-basic-query-r[]
(api/q (api/db *kv*) (quote
;; tag::test-basic-query-q[]
{:find [p1]
:where [[p1 :name name]
[p1 :last-name name]
[p1 :name "Smith"]]}
;; end::test-basic-query-q[]
))))))
(t/deftest test-query-with-arguments
(let [[ivan petr] (f/transact-people! *kv*
;; tag::query-with-arguments-d[]
[{:crux.db/id :ivan
:name "Ivan"
:last-name "Ivanov"}
{:crux.db/id :petr
:name "Petr"
:last-name "Petrov"}
{:crux.db/id :smith
:name "Smith"
:last-name "Smith"}]
;; end::query-with-arguments-d[]
)]
(t/testing "Can match on both entity and value position"
(t/is (=
;; tag::query-with-arguments1-r[]
#{["Ivan"]}
;; end::query-with-arguments1-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments1-q[]
{:find [name]
:where [[e :name name]]
:args [{:e :ivan
:name "Ivan"}]}
;; end::query-with-arguments1-q[]
)))))
(t/testing "Can query entity by single field with several arguments"
(t/is (=
;; tag::query-with-arguments2-r[]
#{[:ivan] [:petr]}
;; end::query-with-arguments2-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments2-q[]
{:find [e]
:where [[e :name name]]
:args [{:name "Ivan"}
{:name "Petr"}]}
;; end::query-with-arguments2-q[]
)))))
(t/testing "Can query entity with tuple arguments"
(t/is (=
;; tag::query-with-arguments3-r[]
#{[:ivan] [:petr]}
;; end::query-with-arguments3-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments3-q[]
{:find [e]
:where [[e :name name]
[e :last-name last-name]]
:args [{:name "Ivan" :last-name "Ivanov"}
{:name "Petr" :last-name "Petrov"}]}
;; end::query-with-arguments3-q[]
)))))
(t/testing "Can query predicates based on arguments alone"
(t/is (=
;; tag::query-with-arguments4-r[]
#{["Ivan"]}
;; end::query-with-arguments4-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments4-q[]
{:find [name]
:where [[(re-find #"I" name)]
[(= last-name "Ivanov")]]
:args [{:name "Ivan" :last-name "Ivanov"}
{:name "Petr" :last-name "Petrov"}]}
;; end::query-with-arguments4-q[]
))))
(t/testing "Can use range constraints on arguments"
(t/is (=
;; tag::query-with-arguments5-r[]
#{[22]}
;; end::query-with-arguments5-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments5-q[]
{:find [age]
:where [[(>= age 21)]]
:args [{:age 22}]}
;; end::query-with-arguments5-q[]
))))))))
(t/deftest test-basic-query-at-t
(let [[malcolm] (f/transact-people!
*kv*
;; tag::query-at-t-d1[]
[{:crux.db/id :malcolm :name "Malcolm" :last-name "Sparks"}]
#inst "1986-10-22"
;; end::query-at-t-d1[]
)
[malcolm2] (f/transact-people!
*kv*
;; tag::query-at-t-d2[]
[{:crux.db/id :malcolm :name "Malcolma" :last-name "Sparks"}]
#inst "1986-10-24")
;; end::query-at-t-d2[]
]
(let [q (quote
;; tag::query-at-t-q[]
{:find [e]
:where [[e :name "Malcolma"]
[e :last-name "Sparks"]]}
;; end::query-at-t-q[]
)]
(t/is (=
;; tag::query-at-t-q1-r[]
#{}
;; end::query-at-t-q1-r[]
;; tag::query-at-t-q1-q[]
; Using Clojure: `(api/q (api/db my-crux-system #inst "1986-10-23") q)`
;; end::query-at-t-q1-q[]
(api/q (api/db *kv* #inst "1986-10-23") q)
))
(t/is (=
;; tag::query-at-t-q2-r[]
#{[:malcolm]}
;; end::query-at-t-q2-r[]
;; tag::query-at-t-q2-q[]
; Using Clojure: `(api/q (api/db my-crux-system) q)`
;; end::query-at-t-q2-q[]
(api/q (api/db *kv*) q)
)))))
;; tag::history-full[]
(api/submit-tx
system
[[:crux.tx/put :ids.persons/Jeff
{:crux.db/id :ids.persons/Jeff
:person/name "Jeff"
:person/wealth 100}
#inst "2018-05-18T09:20:27.966"]
[:crux.tx/put :ids.persons/Jeff
{:crux.db/id :ids.persons/Jeff
:person/name "Jeff"
:person/wealth 1000}
#inst "2015-05-18T09:20:27.966"]])
;yields
{:crux.tx/tx-id 1555314836178,
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00"}
(api/history system :ids.persons/Jeff)
; yields
[{:crux.db/id ; sha1 hash of document id
"c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash ; sha1 hash of document contents
"6ca48d3bf05a16cd8d30e6b466f76d5cc281b561",
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817}
{:crux.db/id "c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529",
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178}]
;; end::history-full[]
;; tag::history-range[]
(crux.api/history-range system :ids.persons/Jeff
#inst "2015-05-18T09:20:27.966" ; valid-time start or nil
#inst "2015-05-18T09:20:27.966" ; transaction-time start or nil
#inst "2020-05-18T09:20:27.966" ; valid-time end or nil, inclusive
#inst "2020-05-18T09:20:27.966") ; transaction-time end or nil, inclusive.
; yields
({:crux.db/id ; sha1 hash of document id
"c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash ; sha1 hash of document contents
"a95f149636e0a10a78452298e2135791c0203529",
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178}
{:crux.db/id "c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561",
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817})
(crux.api/entity (crux.api/db system) "c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613")
; yields
{:crux.db/id :ids.persons/Jeff,
:d.person/name "Jeff",
:d.person/wealth 100}
;; end::history-range[]
(t/deftest test-query-across-entities-using-join
;; Five people, two of which share the same name:
(f/transact-people! *kv*
;; tag::join-d[]
[{:crux.db/id :ivan :name "Ivan"}
{:crux.db/id :petr :name "Petr"}
{:crux.db/id :sergei :name "Sergei"}
{:crux.db/id :denis-a :name "Denis"}
{:crux.db/id :denis-b :name "Denis"}]
;; end::join-d[]
)
(t/testing "Every person joins once, plus 2 more matches"
(t/is (=
;; tag::join-r[]
#{[:ivan :ivan]
[:petr :petr]
[:sergei :sergei]
[:denis-a :denis-a]
[:denis-b :denis-b]
[:denis-a :denis-b]
[:denis-b :denis-a]}
;; end::join-r[]
(api/q (api/db *kv*) (quote
;; tag::join-q[]
{:find [p1 p2]
:where [[p1 :name name]
[p2 :name name]]}
;; end::join-q[]
))))))
(t/deftest test-join-over-two-attributes
(f/transact-people! *kv*
;; tag::join2-d[]
[{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov"}
{:crux.db/id :petr :name "Petr" :follows #{"Ivanov"}}]
;; end::join2-d[]
)
(t/is (=
;; tag::join2-r[]
#{[:petr]}
;; end::join2-r[]
(api/q (api/db *kv*) (quote
;; tag::join2-q[]
{:find [e2]
:where [[e :last-name last-name]
[e2 :follows last-name]
[e :name "Ivan"]]}
;; end::join2-q[]
)))))
;; tag::blanks[]
(t/deftest test-blanks
(f/transact-people! *kv* [{:name "Ivan"} {:name "Petr"} {:name "Sergei"}])
(t/is (= #{["Ivan"] ["Petr"] ["Sergei"]}
(api/q (api/db *kv*) '{:find [name]
:where [[_ :name name]]}))))
;; end::blanks[]
;; tag::not[]
(t/deftest test-not-query
(f/transact-people! *kv* [{:crux.db/id :ivan-ivanov-1 :name "Ivan" :last-name "Ivanov"}
{:crux.db/id :ivan-ivanov-2 :name "Ivan" :last-name "Ivanov"}
{:crux.db/id :ivan-ivanovtov-1 :name "Ivan" :last-name "Ivannotov"}])
(t/testing "literal v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "Ivan"]
(not [e :last-name "Ivannotov"])]}))))
(t/testing "multiple clauses in not"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "Ivan"]
(not [e :last-name "Ivannotov"]
[(string? name)])]}))))))
(t/testing "variable v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[:ivan-ivanovtov-1 :last-name i-name]
(not [e :last-name i-name])]}))))))
;; end::not[]
;; tag::or[]
(t/deftest test-or-query
(f/transact-people! *kv* [{:name "Ivan" :last-name "Ivanov"}
{:name "Ivan" :last-name "Ivanov"}
{:name "Ivan" :last-name "Ivannotov"}
{:name "Bob" :last-name "Controlguy"}])
(t/testing "Or works as expected"
(t/is (= 3 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "Ivan"]
(or [e :last-name "Ivanov"]
[e :last-name "Ivannotov"])]}))))))
;; end::or[]
;; tag::or-and[]
(t/deftest test-or-query-can-use-and
(let [[ivan] (f/transact-people! *kv* [{:name "Ivan" :sex :male}
{:name "Bob" :sex :male}
{:name "Ivana" :sex :female}])]
(t/is (= #{["Ivan"]
["Ivana"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(or [e :sex :female]
(and [e :sex :male]
[e :name "Ivan"]))]})))))
;; end::or-and[]
;; tag::or-and2[]
(t/deftest test-ors-can-introduce-new-bindings
(let [[petr ivan ivanova] (f/transact-people! *kv* [{:name "Petr" :last-name "Smith" :sex :male}
{:name "Ivan" :last-name "Ivanov" :sex :male}
{:name "Ivanova" :last-name "Ivanov" :sex :female}])]
(t/testing "?p2 introduced only inside of an Or"
(t/is (= #{[(:crux.db/id ivan)]} (api/q (api/db *kv*) '{:find [?p2]
:where [(or (and [?p2 :name "Petr"]
[?p2 :sex :female])
(and [?p2 :last-name "Ivanov"]
[?p2 :sex :male]))]}))))))
;; end::or-and2[]
;; tag::not-join[]
(t/deftest test-not-join
(f/transact-people! *kv* [{:name "Ivan" :last-name "Ivanov"}
{:name "Malcolm" :last-name "Ofsparks"}
{:name "Dominic" :last-name "Monroe"}])
(t/testing "Rudimentary not-join"
(t/is (= #{["Ivan"] ["Malcolm"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(not-join [e]
[e :last-name "Monroe"])]})))))
;; end::not-join[]
(t/deftest test-mixing-expressions
(f/transact-people! *kv* [{:name "Ivan" :last-name "Ivanov"}
{:name "Derek" :last-name "Ivanov"}
{:name "Bob" :last-name "Ivannotov"}
{:name "Fred" :last-name "Ivannotov"}])
(t/testing "Or can use not expression"
(t/is (= #{["Ivan"] ["Derek"] ["Fred"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(or [e :last-name "Ivanov"]
(not [e :name "Bob"]))]}))))
(t/testing "Not can use Or expression"
(t/is (= #{["Fred"]} (api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(not (or [e :last-name "Ivanov"]
[e :name "Bob"]))]})))))
(t/deftest test-predicate-expression
(f/transact-people! *kv* [{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov" :age 30}
{:crux.db/id :bob :name "Bob" :last-name "Ivanov" :age 40}
{:crux.db/id :dominic :name "Dominic" :last-name "Monroe" :age 50}])
(t/testing "range expressions"
(t/is (= #{["Ivan"] ["Bob"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
[e :age age]
[(< age 50)]]})))
(t/is (= #{["Dominic"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
[e :age age]
[(>= age 50)]]}))))
(t/testing "clojure.core predicate"
(t/is (= #{["Bob"] ["Dominic"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
[(re-find #"o" name)]]})))
(t/testing "Several variables"
(t/is (= #{[:bob "Ivanov"]}
(api/q (api/db *kv*) '{:find [e last-name]
:where [[e :last-name last-name]
[e :age age]
[(re-find #"ov$" last-name)]
(not [(= age 30)])]}))))
(t/testing "Bind result to var"
(t/is (= #{["Dominic" 25] ["Ivan" 15] ["Bob" 20]}
(api/q (api/db *kv*) '{:find [name half-age]
:where [[e :name name]
[e :age age]
[(quot age 2) half-age]]})))
(t/testing "Binding more than once intersects result"
(t/is (= #{["Ivan" 15]}
(api/q (api/db *kv*) '{:find [name half-age]
:where [[e :name name]
[e :age real-age]
[(quot real-age 2) half-age]
[(- real-age 15) half-age]]}))))
(t/testing "Binding can use range predicates"
(t/is (= #{["Dominic" 25]}
(api/q (api/db *kv*) '{:find [name half-age]
:where [[e :name name]
[e :age real-age]
[(quot real-age 2) half-age]
[(> half-age 20)]]})))))))
(t/deftest test-attributes-with-multiple-values
(f/transact-people! *kv* [{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov" :age 30 :friends #{:bob :dominic}}
{:crux.db/id :bob :name "Bob" :last-name "Ivanov" :age 40 :friends #{:ivan :dominic}}
{:crux.db/id :dominic :name "Dominic" :last-name "Monroe" :age 50 :friends #{:bob}}])
(t/testing "can find multiple values"
(t/is (= #{[:bob] [:dominic]}
(api/q (api/db *kv*) '{:find [f]
:where [[i :name "Ivan"]
[i :friends f]]})))))
(t/deftest test-queries-with-variables-only
(f/transact-people! *kv* [{:crux.db/id :ivan :name "Ivan" :mentor :petr}
{:crux.db/id :petr :name "Petr" :mentor :oleg}
{:crux.db/id :oleg :name "Oleg" :mentor :ivan}])
(t/is (= #{[:oleg "Oleg" :petr "Petr"]
[:ivan "Ivan" :oleg "Oleg"]
[:petr "Petr" :ivan "Ivan"]} (api/q (api/db *kv*) '{:find [e1 n1 e2 n2]
:where [[e1 :name n1]
[e2 :mentor e1]
[e2 :name n2]]}))))
(t/deftest test-index-unification
(f/transact-people! *kv* [{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov"}
{:crux.db/id :petr :name "Petr" :last-name "Petrov" :mentor :ivan}])
(t/is (= #{[:petr :petr]} (api/q (api/db *kv*) '{:find [p1 p2]
:where [[p1 :name "Petr"]
[p2 :mentor i]
[(== p1 p2)]]})))
(t/testing "multiple literals in set"
(t/is (= #{[:petr] [:ivan]} (api/q (api/db *kv*) '{:find [p]
:where [[p :name n]
[(== n #{"Petr" "Ivan"})]]})))))
(t/deftest test-basic-rules
(f/transact-people! *kv* [{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov" :age 21}
{:crux.db/id :petr :name "Petr" :last-name "Petrov" :age 18}])
(t/testing "without rule"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [[i :age age]
[(>= age 21)]]}))))
(t/testing "rule using same variable name as body"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [[i :age age]
(over-twenty-one? age)]
:rules [[(over-twenty-one? age)
[(>= age 21)]]]}))))
(t/testing "rules directly on arguments"
(t/is (= #{[21]} (api/q (api/db *kv*) '{:find [age]
:where [(over-twenty-one? age)]
:args [{:age 21}]
:rules [[(over-twenty-one? age)
[(>= age 21)]]]}))))
(t/testing "rule using multiple arguments"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [[i :age age]
(over-age? age 21)]
:rules [[(over-age? [age] required-age)
[(>= age required-age)]]]}))))
(t/testing "rule using multiple branches"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [(is-ivan-or-bob? i)]
:rules [[(is-ivan-or-bob? i)
[i :name "Ivan"]
[i :last-name "Ivanov"]]
[(is-ivan-or-bob? i)
[i :name "Bob"]]]})))
(t/is (= #{["Petr"]} (api/q (api/db *kv*) '{:find [name]
:where [[i :name name]
(not (is-ivan-or-bob? i))]
:rules [[(is-ivan-or-bob? i)
[i :name "Ivan"]]
[(is-ivan-or-bob? i)
[i :name "Bob"]]]}))))
;; https://www.comp.nus.edu.sg/~ooibc/stbtree95.pdf
;; This test is based on section 7. Support for complex queries in
;; bitemporal databases
;; p1 NY [0,3] [4,now]
;; p1 LA [4,now] [4,now]
;; p2 SFO [0,now] [0,5]
;; p2 SFO [0,5] [5,now]
;; p3 LA [0,now] [0,4]
;; p3 LA [0,4] [4,7]
;; p3 LA [0,7] [7,now]
;; p3 SFO [8,0] [8,now]
;; p4 NY [2,now] [2,3]
;; p4 NY [2,3] [3,now]
;; p4 LA [8,now] [8,now]
;; p5 LA [1O,now] [1O,now]
;; p6 NY [12,now] [12,now]
;; p7 NY [11,now] [11,now]
;; Find all persons who are known to be present in the United States
;; on day 2 (valid time), as of day 3 (transaction time)
;; t2 p2 SFO, t5 p3 LA, t9 p4 NY, t10 p4 NY (?)
(comment
;; tag::bitemp0[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp0[]
;; tag::bitemp2[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time :na}
#inst "2019-01-02"
;; end::bitemp2[]
;; tag::bitemp3[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp3[]
;; tag::bitemp4[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp4[]
;; tag::bitemp4b[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp4b[]
;; tag::bitemp4c[]
{:crux.db/id :p1
:entry-pt :LA
:arrival-time #inst "2019-01-04"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-04"}
#inst "2019-01-04"
;; end::bitemp4c[]
;; tag::bitemp5[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-05"}
#inst "2019-01-05"
;; end::bitemp5[]
;; tag::bitemp7[]
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2019-01-04"
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-07"}
#inst "2019-01-07"
;; end::bitemp7[]
;; tag::bitemp8[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
{:crux.db/id :p4
:entry-pt :LA
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
;; end::bitemp8[]
;; tag::bitemp9[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time #inst "2019-01-08"}
#inst "2019-01-09"
;; end::bitemp9[]
;; tag::bitemp10[]
{:crux.db/id :p5
:entry-pt :LA
:arrival-time #inst "2019-01-10"
:departure-time :na}
#inst "2019-01-10"
;; end::bitemp10[]
;; tag::bitemp11[]
{:crux.db/id :p7
:entry-pt :NY
:arrival-time #inst "2019-01-11"
:departure-time :na}
#inst "2019-01-11"
;; end::bitemp11[]
;; tag::bitemp12[]
{:crux.db/id :p6
:entry-pt :NY
:arrival-time #inst "2019-01-12"
:departure-time :na}
#inst "2019-01-12"
;; end::bitemp12[]
)
;; tag::bitempq[]
{:find [p entry-pt arrival-time departure-time]
:where [[p :entry-pt entry-pt]
[p :arrival-time arrival-time]
[p :departure-time departure-time]]}
#inst "2019-01-02" ; `as of` valid time
#inst "2019-01-03" ; `as at` transaction time
;; end::bitempq[]
;; tag::bitempr[]
#{[:p2 :SFO #inst "2018-12-31" :na]
[:p3 :LA #inst "2018-12-31" :na]
[:p4 :NY #inst "2019-01-02" :na]}
;; end::bitempr[]
(t/deftest test-bitemp-query-from-indexing-temporal-data-using-existing-b+-trees-paper
(let [tx-log (crux.tx/->KvTxLog *kv*)]
;; Day 0, represented as #inst "2018-12-31"
@(db/submit-tx tx-log [[:crux.tx/put :p2
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"]
[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"]])
;; Day 1, nothing happens.
@(db/submit-tx tx-log [])
;; Day 2
@(db/submit-tx tx-log [[:crux.tx/put :p4
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time :na}
#inst "2019-01-02"]])
;; Day 3
(let [third-day-submitted-tx @(db/submit-tx tx-log [[:crux.tx/put :p4
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"]])]
;; Day 4, correction, adding missing trip on new arrival.
@(db/submit-tx tx-log [[:crux.tx/put :p1
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"]
[:crux.tx/put :p1
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"]
[:crux.tx/put :p1
{:crux.db/id :p1
:entry-pt :LA
:arrival-time #inst "2019-01-04"
:departure-time :na}
#inst "2019-01-04"]
[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-04"}
#inst "2019-01-04"]])
;; Day 5
@(db/submit-tx tx-log [[:crux.tx/put :p2
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-05"}
#inst "2019-01-05"]])
;; Day 6, nothing happens.
@(db/submit-tx tx-log [])
;; Day 7-12, correction of deletion/departure on day 4. Shows
;; how valid time cannot be the same as arrival time.
@(db/submit-tx tx-log [[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2019-01-04"]
[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-07"}
#inst "2019-01-07"]])
@(db/submit-tx tx-log [[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"]
[:crux.tx/put :p4
{:crux.db/id :p4
:entry-pt :LA
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"]])
@(db/submit-tx tx-log [[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time #inst "2019-01-08"}
#inst "2019-01-09"]])
@(db/submit-tx tx-log [[:crux.tx/put :p5
{:crux.db/id :p5
:entry-pt :LA
:arrival-time #inst "2019-01-10"
:departure-time :na}
#inst "2019-01-10"]])
@(db/submit-tx tx-log [[:crux.tx/put :p7
{:crux.db/id :p7
:entry-pt :NY
:arrival-time #inst "2019-01-11"
:departure-time :na}
#inst "2019-01-11"]])
@(db/submit-tx tx-log [[:crux.tx/put :p6
{:crux.db/id :p6
:entry-pt :NY
:arrival-time #inst "2019-01-12"
:departure-time :na}
#inst "2019-01-12"]])
(t/is (= #{[:p2 :SFO #inst "2018-12-31" :na]
[:p3 :LA #inst "2018-12-31" :na]
[:p4 :NY #inst "2019-01-02" :na]}
(api/q (api/db f/*kv* #inst "2019-01-02" (:crux.tx/tx-time third-day-submitted-tx))
'{:find [p entry-pt arrival-time departure-time]
:where [[p :entry-pt entry-pt]
[p :arrival-time arrival-time]
[p :departure-time departure-time]]}))))))
;; Tests borrowed from Datascript:
;; https://github.com/tonsky/datascript/tree/master/test/datascript/test
(defn populate-datascript-test-db []
(f/transact-entity-maps! *kv* [{:crux.db/id :1 :name "Ivan" :age 10}
{:crux.db/id :2 :name "Ivan" :age 20}
{:crux.db/id :3 :name "Oleg" :age 10}
{:crux.db/id :4 :name "Oleg" :age 20}
{:crux.db/id :5 :name "Ivan" :age 10}
{:crux.db/id :6 :name "Ivan" :age 20} ]))
(t/deftest test-rules
(f/transact-entity-maps! f/*kv* [{:crux.db/id :5 :follow :3}
{:crux.db/id :1 :follow :2}
{:crux.db/id :2 :follow #{:3 :4}}
{:crux.db/id :3 :follow :4}
{:crux.db/id :4 :follow :6}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(follow ?e1 ?e2)]
:rules [[(follow ?x ?y)
[?x :follow ?y]]]})
#{[:1 :2] [:2 :3] [:3 :4] [:2 :4] [:5 :3] [:4 :6]}))
;; NOTE: Crux does not support vars in attribute position, so
;; :follow is explicit.
(t/testing "Joining regular clauses with rule"
(t/is (= (api/q db
'{:find [?y ?x]
:where [[_ :follow ?x]
(rule ?x ?y)
[(crux.query-test/even-kw? ?x)]]
:rules [[(rule ?a ?b)
[?a :follow ?b]]]})
#{[:3 :2] [:6 :4] [:4 :2]})))
;; NOTE: Crux does not support vars in attribute position.
#_(t/testing "Rule context is isolated from outer context"
(t/is (= (api/q db
'{:find [?x]
:where [[?e _ _]
(rule ?x)]
:rules [[(rule ?e)
[_ ?e _]]]})
#{[:follow]})))
(t/testing "Rule with branches"
(t/is (= (api/q db
'{:find [?e2]
:where [(follow ?e1 ?e2)]
:args [{:?e1 :1}]
:rules [[(follow ?e2 ?e1)
[?e2 :follow ?e1]]
[(follow ?e2 ?e1)
[?e2 :follow ?t]
[?t :follow ?e1]]]})
#{[:2] [:3] [:4]})))
(t/testing "Recursive rules"
(t/is (= (api/q db
'{:find [?e2]
:where [(follow ?e1 ?e2)]
:args [{:?e1 :1}]
:rules [[(follow ?e1 ?e2)
[?e1 :follow ?e2]]
[(follow ?e1 ?e2)
[?e1 :follow ?t]
(follow ?t ?e2)]]})
#{[:2] [:3] [:4] [:6]}))
(f/with-kv-store
(fn []
(f/transact-entity-maps! f/*kv* [{:crux.db/id :1 :follow :2}
{:crux.db/id :2 :follow :3}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(follow ?e1 ?e2)]
:rules [[(follow ?e1 ?e2)
[?e1 :follow ?e2]]
[(follow ?e1 ?e2)
(follow ?e2 ?e1)]]})
#{[:1 :2] [:2 :3] [:2 :1] [:3 :2]})))))
(f/with-kv-store
(fn []
(f/transact-entity-maps! f/*kv* [{:crux.db/id :1 :follow :2}
{:crux.db/id :2 :follow :3}
{:crux.db/id :3 :follow :1}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(follow ?e1 ?e2)]
:rules [[(follow ?e1 ?e2)
[?e1 :follow ?e2]]
[(follow ?e1 ?e2)
(follow ?e2 ?e1)]]})
#{[:1 :2] [:2 :3] [:3 :1] [:2 :1] [:3 :2] [:1 :3]}))))))
(t/testing "Mutually recursive rules"
(f/with-kv-store
(fn []
(f/transact-entity-maps! f/*kv* [{:crux.db/id :0 :f1 :1}
{:crux.db/id :1 :f2 :2}
{:crux.db/id :2 :f1 :3}
{:crux.db/id :3 :f2 :4}
{:crux.db/id :4 :f1 :5}
{:crux.db/id :5 :f2 :6}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(f1 ?e1 ?e2)]
:rules [[(f1 ?e1 ?e2)
[?e1 :f1 ?e2]]
[(f1 ?e1 ?e2)
[?t :f1 ?e2]
(f2 ?e1 ?t)]
[(f2 ?e1 ?e2)
[?e1 :f2 ?e2]]
[(f2 ?e1 ?e2)
[?t :f2 ?e2]
(f1 ?e1 ?t)]]})
#{[:0 :1] [:0 :3] [:0 :5]
[:1 :3] [:1 :5]
[:2 :3] [:2 :5]
[:3 :5]
[:4 :5]}))))))
(t/testing "Passing ins to rule"
(t/is (= (api/q db
{:find '[?x ?y]
:where '[(match ?even ?x ?y)]
:rules '[[(match ?pred ?e ?e2)
[?e :follow ?e2]
[(?pred ?e)]
[(?pred ?e2)]]]
:args [{:?even even-kw?}]})
#{[:4 :6] [:2 :4]})))))
(t/deftest data-script-test-query-fns
;; NOTE: Crux does not support these functions.
#_(t/testing "ground")
#_(t/testing "get-else")
#_(t/testing "get-some")
#_(t/testing "missing?")
#_(t/testing "missing? back-ref")
;; NOTE: Crux does not currently support destructuring.
#_(t/testing "Destructured conflicting function values for two bindings.")
#_(t/testing "Result bindings"))
(defn kw-less-than? [x y]
(< (Long/parseLong (name x))
(Long/parseLong (name y))))
(t/deftest datascript-test-predicates
(f/transact-entity-maps! f/*kv* [{:crux.db/id :1 :name "Ivan" :age 10}
{:crux.db/id :2 :name "Ivan" :age 20}
{:crux.db/id :3 :name "Oleg" :age 10}
{:crux.db/id :4 :name "Oleg" :age 20}])
(let [db (api/db *kv*)]
;; NOTE: Crux does not support source vars.
#_(let [pred (fn [db e a]
(= a (:age (d/entity db e))))]
(t/is (= (api/q '[:find ?e
:in $ ?pred
:where [?e :age ?a]
[(?pred $ ?e 10)]]
db pred)
#{[1] [3]})))))
;; Tests from Racket Datalog
;; https://github.com/racket/datalog/tree/master/tests/examples
;; Tests from
;; https://pdfs.semanticscholar.org/9374/f0da312f3ba77fa840071d68935a28cba364.pdf
| 62210 | (ns crux.query-test
(:require [clojure.spec.alpha :as s]
[clojure.test :as t]
[crux.db :as db]
[crux.api :as api]
[crux.fixtures :as f :refer [*kv*]])
(:import java.util.UUID))
(t/use-fixtures :each f/with-kv-store)
(t/deftest test-basic-query
(f/transact-people! *kv*
;; tag::test-basic-query-d[]
[{:crux.db/id :iv<NAME>
:name "<NAME>"
:last-name "<NAME>"}
{:crux.db/id :pe<NAME>
:name "<NAME>"
:last-name "<NAME>"}
{:crux.db/id :<NAME>
:name "<NAME>"
:last-name "<NAME>"}]
;; end::test-basic-query-d[]
)
(t/testing "Can query across fields for same value when value is passed in"
(t/is (=
;; tag::test-basic-query-r[]
#{[:smith]}
;; end::test-basic-query-r[]
(api/q (api/db *kv*) (quote
;; tag::test-basic-query-q[]
{:find [p1]
:where [[p1 :name name]
[p1 :last-name name]
[p1 :name "<NAME>"]]}
;; end::test-basic-query-q[]
))))))
(t/deftest test-query-with-arguments
(let [[ivan petr] (f/transact-people! *kv*
;; tag::query-with-arguments-d[]
[{:crux.db/id :iv<NAME>
:name "<NAME>"
:last-name "<NAME>"}
{:crux.db/id :pe<NAME>
:name "<NAME>"
:last-name "<NAME>"}
{:crux.db/id :<NAME>
:name "<NAME>"
:last-name "<NAME>"}]
;; end::query-with-arguments-d[]
)]
(t/testing "Can match on both entity and value position"
(t/is (=
;; tag::query-with-arguments1-r[]
#{["<NAME>"]}
;; end::query-with-arguments1-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments1-q[]
{:find [name]
:where [[e :name name]]
:args [{:e :ivan
:name "<NAME>"}]}
;; end::query-with-arguments1-q[]
)))))
(t/testing "Can query entity by single field with several arguments"
(t/is (=
;; tag::query-with-arguments2-r[]
#{[:ivan] [:petr]}
;; end::query-with-arguments2-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments2-q[]
{:find [e]
:where [[e :name name]]
:args [{:name "<NAME>"}
{:name "<NAME>"}]}
;; end::query-with-arguments2-q[]
)))))
(t/testing "Can query entity with tuple arguments"
(t/is (=
;; tag::query-with-arguments3-r[]
#{[:ivan] [:petr]}
;; end::query-with-arguments3-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments3-q[]
{:find [e]
:where [[e :name name]
[e :last-name last-name]]
:args [{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}]}
;; end::query-with-arguments3-q[]
)))))
(t/testing "Can query predicates based on arguments alone"
(t/is (=
;; tag::query-with-arguments4-r[]
#{["<NAME>"]}
;; end::query-with-arguments4-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments4-q[]
{:find [name]
:where [[(re-find #"I" name)]
[(= last-name "<NAME>")]]
:args [{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}]}
;; end::query-with-arguments4-q[]
))))
(t/testing "Can use range constraints on arguments"
(t/is (=
;; tag::query-with-arguments5-r[]
#{[22]}
;; end::query-with-arguments5-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments5-q[]
{:find [age]
:where [[(>= age 21)]]
:args [{:age 22}]}
;; end::query-with-arguments5-q[]
))))))))
(t/deftest test-basic-query-at-t
(let [[malcolm] (f/transact-people!
*kv*
;; tag::query-at-t-d1[]
[{:crux.db/id :malcolm :name "<NAME>" :last-name "<NAME>"}]
#inst "1986-10-22"
;; end::query-at-t-d1[]
)
[malcolm2] (f/transact-people!
*kv*
;; tag::query-at-t-d2[]
[{:crux.db/id :malcolm :name "<NAME>" :last-name "<NAME>"}]
#inst "1986-10-24")
;; end::query-at-t-d2[]
]
(let [q (quote
;; tag::query-at-t-q[]
{:find [e]
:where [[e :name "<NAME>"]
[e :last-name "<NAME>"]]}
;; end::query-at-t-q[]
)]
(t/is (=
;; tag::query-at-t-q1-r[]
#{}
;; end::query-at-t-q1-r[]
;; tag::query-at-t-q1-q[]
; Using Clojure: `(api/q (api/db my-crux-system #inst "1986-10-23") q)`
;; end::query-at-t-q1-q[]
(api/q (api/db *kv* #inst "1986-10-23") q)
))
(t/is (=
;; tag::query-at-t-q2-r[]
#{[:malcolm]}
;; end::query-at-t-q2-r[]
;; tag::query-at-t-q2-q[]
; Using Clojure: `(api/q (api/db my-crux-system) q)`
;; end::query-at-t-q2-q[]
(api/q (api/db *kv*) q)
)))))
;; tag::history-full[]
(api/submit-tx
system
[[:crux.tx/put :ids.persons/Jeff
{:crux.db/id :ids.persons/Jeff
:person/name "<NAME>"
:person/wealth 100}
#inst "2018-05-18T09:20:27.966"]
[:crux.tx/put :ids.persons/Jeff
{:crux.db/id :ids.persons/Jeff
:person/name "<NAME>"
:person/wealth 1000}
#inst "2015-05-18T09:20:27.966"]])
;yields
{:crux.tx/tx-id 1555314836178,
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00"}
(api/history system :ids.persons/Jeff)
; yields
[{:crux.db/id ; sha1 hash of document id
"c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash ; sha1 hash of document contents
"6ca48d3bf05a16cd8d30e6b466f76d5cc281b561",
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817}
{:crux.db/id "c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529",
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178}]
;; end::history-full[]
;; tag::history-range[]
(crux.api/history-range system :ids.persons/Jeff
#inst "2015-05-18T09:20:27.966" ; valid-time start or nil
#inst "2015-05-18T09:20:27.966" ; transaction-time start or nil
#inst "2020-05-18T09:20:27.966" ; valid-time end or nil, inclusive
#inst "2020-05-18T09:20:27.966") ; transaction-time end or nil, inclusive.
; yields
({:crux.db/id ; sha1 hash of document id
"c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash ; sha1 hash of document contents
"a95f149636e0a10a78452298e2135791c0203529",
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178}
{:crux.db/id "c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561",
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817})
(crux.api/entity (crux.api/db system) "c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613")
; yields
{:crux.db/id :ids.persons/<NAME>,
:d.person/name "<NAME>",
:d.person/wealth 100}
;; end::history-range[]
(t/deftest test-query-across-entities-using-join
;; Five people, two of which share the same name:
(f/transact-people! *kv*
;; tag::join-d[]
[{:crux.db/id :ivan :name "<NAME>"}
{:crux.db/id :<NAME> :name "<NAME>"}
{:crux.db/id :sergei :name "<NAME>"}
{:crux.db/id :denis-a :name "<NAME>"}
{:crux.db/id :denis-b :name "<NAME>"}]
;; end::join-d[]
)
(t/testing "Every person joins once, plus 2 more matches"
(t/is (=
;; tag::join-r[]
#{[:ivan :ivan]
[:petr :petr]
[:sergei :sergei]
[:denis-a :denis-a]
[:denis-b :denis-b]
[:denis-a :denis-b]
[:denis-b :denis-a]}
;; end::join-r[]
(api/q (api/db *kv*) (quote
;; tag::join-q[]
{:find [p1 p2]
:where [[p1 :name name]
[p2 :name name]]}
;; end::join-q[]
))))))
(t/deftest test-join-over-two-attributes
(f/transact-people! *kv*
;; tag::join2-d[]
[{:crux.db/id :ivan :name "<NAME>" :last-name "<NAME>"}
{:crux.db/id :petr :name "<NAME>" :follows #{"Ivanov"}}]
;; end::join2-d[]
)
(t/is (=
;; tag::join2-r[]
#{[:petr]}
;; end::join2-r[]
(api/q (api/db *kv*) (quote
;; tag::join2-q[]
{:find [e2]
:where [[e :last-name last-name]
[e2 :follows last-name]
[e :name "<NAME>"]]}
;; end::join2-q[]
)))))
;; tag::blanks[]
(t/deftest test-blanks
(f/transact-people! *kv* [{:name "<NAME>"} {:name "<NAME>"} {:name "<NAME>"}])
(t/is (= #{["<NAME>"] ["<NAME>"] ["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[_ :name name]]}))))
;; end::blanks[]
;; tag::not[]
(t/deftest test-not-query
(f/transact-people! *kv* [{:crux.db/id :ivan-ivanov-1 :name "<NAME>" :last-name "<NAME>"}
{:crux.db/id :ivan-ivanov-2 :name "<NAME>" :last-name "<NAME>"}
{:crux.db/id :ivan-ivanovtov-1 :name "<NAME>" :last-name "<NAME>"}])
(t/testing "literal v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "<NAME>"]
(not [e :last-name "<NAME>"])]}))))
(t/testing "multiple clauses in not"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "<NAME>"]
(not [e :last-name "<NAME>"]
[(string? name)])]}))))))
(t/testing "variable v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[:ivan-ivanovtov-1 :last-name i-name]
(not [e :last-name i-name])]}))))))
;; end::not[]
;; tag::or[]
(t/deftest test-or-query
(f/transact-people! *kv* [{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}])
(t/testing "Or works as expected"
(t/is (= 3 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "<NAME>"]
(or [e :last-name "<NAME>"]
[e :last-name "<NAME>"])]}))))))
;; end::or[]
;; tag::or-and[]
(t/deftest test-or-query-can-use-and
(let [[ivan] (f/transact-people! *kv* [{:name "<NAME>" :sex :male}
{:name "<NAME>" :sex :male}
{:name "<NAME>" :sex :female}])]
(t/is (= #{["<NAME>"]
["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(or [e :sex :female]
(and [e :sex :male]
[e :name "<NAME>"]))]})))))
;; end::or-and[]
;; tag::or-and2[]
(t/deftest test-ors-can-introduce-new-bindings
(let [[petr ivan ivanova] (f/transact-people! *kv* [{:name "<NAME>" :last-name "<NAME>" :sex :male}
{:name "<NAME>" :last-name "<NAME>" :sex :male}
{:name "<NAME>" :last-name "<NAME>" :sex :female}])]
(t/testing "?p2 introduced only inside of an Or"
(t/is (= #{[(:crux.db/id ivan)]} (api/q (api/db *kv*) '{:find [?p2]
:where [(or (and [?p2 :name "<NAME>"]
[?p2 :sex :female])
(and [?p2 :last-name "<NAME>"]
[?p2 :sex :male]))]}))))))
;; end::or-and2[]
;; tag::not-join[]
(t/deftest test-not-join
(f/transact-people! *kv* [{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}])
(t/testing "Rudimentary not-join"
(t/is (= #{["<NAME>"] ["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(not-join [e]
[e :last-name "<NAME>"])]})))))
;; end::not-join[]
(t/deftest test-mixing-expressions
(f/transact-people! *kv* [{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}])
(t/testing "Or can use not expression"
(t/is (= #{["<NAME>"] ["<NAME>"] ["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(or [e :last-name "<NAME>"]
(not [e :name "<NAME>"]))]}))))
(t/testing "Not can use Or expression"
(t/is (= #{["<NAME>"]} (api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(not (or [e :last-name "<NAME>"]
[e :name "<NAME>"]))]})))))
(t/deftest test-predicate-expression
(f/transact-people! *kv* [{:crux.db/id :iv<NAME> :name "<NAME>" :last-name "<NAME>" :age 30}
{:crux.db/id :bob :name "<NAME>" :last-name "<NAME>" :age 40}
{:crux.db/id :<NAME> :name "<NAME>" :last-name "<NAME>" :age 50}])
(t/testing "range expressions"
(t/is (= #{["<NAME>"] ["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
[e :age age]
[(< age 50)]]})))
(t/is (= #{["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
[e :age age]
[(>= age 50)]]}))))
(t/testing "clojure.core predicate"
(t/is (= #{["<NAME>"] ["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
[(re-find #"o" name)]]})))
(t/testing "Several variables"
(t/is (= #{[:bob "<NAME>"]}
(api/q (api/db *kv*) '{:find [e last-name]
:where [[e :last-name last-name]
[e :age age]
[(re-find #"ov$" last-name)]
(not [(= age 30)])]}))))
(t/testing "Bind result to var"
(t/is (= #{["<NAME>" 25] ["<NAME>" 15] ["<NAME>" 20]}
(api/q (api/db *kv*) '{:find [name half-age]
:where [[e :name name]
[e :age age]
[(quot age 2) half-age]]})))
(t/testing "Binding more than once intersects result"
(t/is (= #{["<NAME>" 15]}
(api/q (api/db *kv*) '{:find [name half-age]
:where [[e :name name]
[e :age real-age]
[(quot real-age 2) half-age]
[(- real-age 15) half-age]]}))))
(t/testing "Binding can use range predicates"
(t/is (= #{["<NAME>" 25]}
(api/q (api/db *kv*) '{:find [name half-age]
:where [[e :name name]
[e :age real-age]
[(quot real-age 2) half-age]
[(> half-age 20)]]})))))))
(t/deftest test-attributes-with-multiple-values
(f/transact-people! *kv* [{:crux.db/id :ivan :name "<NAME>" :last-name "<NAME>" :age 30 :friends #{:bob :dominic}}
{:crux.db/id :bob :name "<NAME>" :last-name "<NAME>" :age 40 :friends #{:ivan :dominic}}
{:crux.db/id :dominic :name "<NAME>" :last-name "<NAME>" :age 50 :friends #{:bob}}])
(t/testing "can find multiple values"
(t/is (= #{[:bob] [:dominic]}
(api/q (api/db *kv*) '{:find [f]
:where [[i :name "<NAME>"]
[i :friends f]]})))))
(t/deftest test-queries-with-variables-only
(f/transact-people! *kv* [{:crux.db/id :ivan :name "<NAME>" :mentor :petr}
{:crux.db/id :petr :name "<NAME>" :mentor :oleg}
{:crux.db/id :oleg :name "<NAME>" :mentor :ivan}])
(t/is (= #{[:oleg "<NAME>" :petr "<NAME>"]
[:ivan "<NAME>" :oleg "<NAME>"]
[:petr "<NAME>" :ivan "<NAME>"]} (api/q (api/db *kv*) '{:find [e1 n1 e2 n2]
:where [[e1 :name n1]
[e2 :mentor e1]
[e2 :name n2]]}))))
(t/deftest test-index-unification
(f/transact-people! *kv* [{:crux.db/id :ivan :name "<NAME>" :last-name "<NAME>"}
{:crux.db/id :petr :name "<NAME>" :last-name "<NAME>" :mentor :ivan}])
(t/is (= #{[:petr :petr]} (api/q (api/db *kv*) '{:find [p1 p2]
:where [[p1 :name "<NAME>"]
[p2 :mentor i]
[(== p1 p2)]]})))
(t/testing "multiple literals in set"
(t/is (= #{[:petr] [:ivan]} (api/q (api/db *kv*) '{:find [p]
:where [[p :name n]
[(== n #{"<NAME>" "<NAME>"})]]})))))
(t/deftest test-basic-rules
(f/transact-people! *kv* [{:crux.db/id :ivan :name "<NAME>" :last-name "<NAME>" :age 21}
{:crux.db/id :petr :name "<NAME>" :last-name "<NAME>" :age 18}])
(t/testing "without rule"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [[i :age age]
[(>= age 21)]]}))))
(t/testing "rule using same variable name as body"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [[i :age age]
(over-twenty-one? age)]
:rules [[(over-twenty-one? age)
[(>= age 21)]]]}))))
(t/testing "rules directly on arguments"
(t/is (= #{[21]} (api/q (api/db *kv*) '{:find [age]
:where [(over-twenty-one? age)]
:args [{:age 21}]
:rules [[(over-twenty-one? age)
[(>= age 21)]]]}))))
(t/testing "rule using multiple arguments"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [[i :age age]
(over-age? age 21)]
:rules [[(over-age? [age] required-age)
[(>= age required-age)]]]}))))
(t/testing "rule using multiple branches"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [(is-ivan-or-bob? i)]
:rules [[(is-ivan-or-bob? i)
[i :name "<NAME>"]
[i :last-name "<NAME>"]]
[(is-ivan-or-bob? i)
[i :name "<NAME>"]]]})))
(t/is (= #{["<NAME>"]} (api/q (api/db *kv*) '{:find [name]
:where [[i :name name]
(not (is-ivan-or-bob? i))]
:rules [[(is-ivan-or-bob? i)
[i :name "<NAME>"]]
[(is-ivan-or-bob? i)
[i :name "<NAME>"]]]}))))
;; https://www.comp.nus.edu.sg/~ooibc/stbtree95.pdf
;; This test is based on section 7. Support for complex queries in
;; bitemporal databases
;; p1 NY [0,3] [4,now]
;; p1 LA [4,now] [4,now]
;; p2 SFO [0,now] [0,5]
;; p2 SFO [0,5] [5,now]
;; p3 LA [0,now] [0,4]
;; p3 LA [0,4] [4,7]
;; p3 LA [0,7] [7,now]
;; p3 SFO [8,0] [8,now]
;; p4 NY [2,now] [2,3]
;; p4 NY [2,3] [3,now]
;; p4 LA [8,now] [8,now]
;; p5 LA [1O,now] [1O,now]
;; p6 NY [12,now] [12,now]
;; p7 NY [11,now] [11,now]
;; Find all persons who are known to be present in the United States
;; on day 2 (valid time), as of day 3 (transaction time)
;; t2 p2 SFO, t5 p3 LA, t9 p4 NY, t10 p4 NY (?)
(comment
;; tag::bitemp0[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp0[]
;; tag::bitemp2[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time :na}
#inst "2019-01-02"
;; end::bitemp2[]
;; tag::bitemp3[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp3[]
;; tag::bitemp4[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp4[]
;; tag::bitemp4b[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp4b[]
;; tag::bitemp4c[]
{:crux.db/id :p1
:entry-pt :LA
:arrival-time #inst "2019-01-04"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-04"}
#inst "2019-01-04"
;; end::bitemp4c[]
;; tag::bitemp5[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-05"}
#inst "2019-01-05"
;; end::bitemp5[]
;; tag::bitemp7[]
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2019-01-04"
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-07"}
#inst "2019-01-07"
;; end::bitemp7[]
;; tag::bitemp8[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
{:crux.db/id :p4
:entry-pt :LA
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
;; end::bitemp8[]
;; tag::bitemp9[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time #inst "2019-01-08"}
#inst "2019-01-09"
;; end::bitemp9[]
;; tag::bitemp10[]
{:crux.db/id :p5
:entry-pt :LA
:arrival-time #inst "2019-01-10"
:departure-time :na}
#inst "2019-01-10"
;; end::bitemp10[]
;; tag::bitemp11[]
{:crux.db/id :p7
:entry-pt :NY
:arrival-time #inst "2019-01-11"
:departure-time :na}
#inst "2019-01-11"
;; end::bitemp11[]
;; tag::bitemp12[]
{:crux.db/id :p6
:entry-pt :NY
:arrival-time #inst "2019-01-12"
:departure-time :na}
#inst "2019-01-12"
;; end::bitemp12[]
)
;; tag::bitempq[]
{:find [p entry-pt arrival-time departure-time]
:where [[p :entry-pt entry-pt]
[p :arrival-time arrival-time]
[p :departure-time departure-time]]}
#inst "2019-01-02" ; `as of` valid time
#inst "2019-01-03" ; `as at` transaction time
;; end::bitempq[]
;; tag::bitempr[]
#{[:p2 :SFO #inst "2018-12-31" :na]
[:p3 :LA #inst "2018-12-31" :na]
[:p4 :NY #inst "2019-01-02" :na]}
;; end::bitempr[]
(t/deftest test-bitemp-query-from-indexing-temporal-data-using-existing-b+-trees-paper
(let [tx-log (crux.tx/->KvTxLog *kv*)]
;; Day 0, represented as #inst "2018-12-31"
@(db/submit-tx tx-log [[:crux.tx/put :p2
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"]
[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"]])
;; Day 1, nothing happens.
@(db/submit-tx tx-log [])
;; Day 2
@(db/submit-tx tx-log [[:crux.tx/put :p4
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time :na}
#inst "2019-01-02"]])
;; Day 3
(let [third-day-submitted-tx @(db/submit-tx tx-log [[:crux.tx/put :p4
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"]])]
;; Day 4, correction, adding missing trip on new arrival.
@(db/submit-tx tx-log [[:crux.tx/put :p1
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"]
[:crux.tx/put :p1
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"]
[:crux.tx/put :p1
{:crux.db/id :p1
:entry-pt :LA
:arrival-time #inst "2019-01-04"
:departure-time :na}
#inst "2019-01-04"]
[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-04"}
#inst "2019-01-04"]])
;; Day 5
@(db/submit-tx tx-log [[:crux.tx/put :p2
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-05"}
#inst "2019-01-05"]])
;; Day 6, nothing happens.
@(db/submit-tx tx-log [])
;; Day 7-12, correction of deletion/departure on day 4. Shows
;; how valid time cannot be the same as arrival time.
@(db/submit-tx tx-log [[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2019-01-04"]
[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-07"}
#inst "2019-01-07"]])
@(db/submit-tx tx-log [[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"]
[:crux.tx/put :p4
{:crux.db/id :p4
:entry-pt :LA
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"]])
@(db/submit-tx tx-log [[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time #inst "2019-01-08"}
#inst "2019-01-09"]])
@(db/submit-tx tx-log [[:crux.tx/put :p5
{:crux.db/id :p5
:entry-pt :LA
:arrival-time #inst "2019-01-10"
:departure-time :na}
#inst "2019-01-10"]])
@(db/submit-tx tx-log [[:crux.tx/put :p7
{:crux.db/id :p7
:entry-pt :NY
:arrival-time #inst "2019-01-11"
:departure-time :na}
#inst "2019-01-11"]])
@(db/submit-tx tx-log [[:crux.tx/put :p6
{:crux.db/id :p6
:entry-pt :NY
:arrival-time #inst "2019-01-12"
:departure-time :na}
#inst "2019-01-12"]])
(t/is (= #{[:p2 :SFO #inst "2018-12-31" :na]
[:p3 :LA #inst "2018-12-31" :na]
[:p4 :NY #inst "2019-01-02" :na]}
(api/q (api/db f/*kv* #inst "2019-01-02" (:crux.tx/tx-time third-day-submitted-tx))
'{:find [p entry-pt arrival-time departure-time]
:where [[p :entry-pt entry-pt]
[p :arrival-time arrival-time]
[p :departure-time departure-time]]}))))))
;; Tests borrowed from Datascript:
;; https://github.com/tonsky/datascript/tree/master/test/datascript/test
(defn populate-datascript-test-db []
(f/transact-entity-maps! *kv* [{:crux.db/id :1 :name "<NAME>" :age 10}
{:crux.db/id :2 :name "<NAME>" :age 20}
{:crux.db/id :3 :name "<NAME>" :age 10}
{:crux.db/id :4 :name "<NAME>" :age 20}
{:crux.db/id :5 :name "<NAME>" :age 10}
{:crux.db/id :6 :name "<NAME>" :age 20} ]))
(t/deftest test-rules
(f/transact-entity-maps! f/*kv* [{:crux.db/id :5 :follow :3}
{:crux.db/id :1 :follow :2}
{:crux.db/id :2 :follow #{:3 :4}}
{:crux.db/id :3 :follow :4}
{:crux.db/id :4 :follow :6}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(follow ?e1 ?e2)]
:rules [[(follow ?x ?y)
[?x :follow ?y]]]})
#{[:1 :2] [:2 :3] [:3 :4] [:2 :4] [:5 :3] [:4 :6]}))
;; NOTE: Crux does not support vars in attribute position, so
;; :follow is explicit.
(t/testing "Joining regular clauses with rule"
(t/is (= (api/q db
'{:find [?y ?x]
:where [[_ :follow ?x]
(rule ?x ?y)
[(crux.query-test/even-kw? ?x)]]
:rules [[(rule ?a ?b)
[?a :follow ?b]]]})
#{[:3 :2] [:6 :4] [:4 :2]})))
;; NOTE: Crux does not support vars in attribute position.
#_(t/testing "Rule context is isolated from outer context"
(t/is (= (api/q db
'{:find [?x]
:where [[?e _ _]
(rule ?x)]
:rules [[(rule ?e)
[_ ?e _]]]})
#{[:follow]})))
(t/testing "Rule with branches"
(t/is (= (api/q db
'{:find [?e2]
:where [(follow ?e1 ?e2)]
:args [{:?e1 :1}]
:rules [[(follow ?e2 ?e1)
[?e2 :follow ?e1]]
[(follow ?e2 ?e1)
[?e2 :follow ?t]
[?t :follow ?e1]]]})
#{[:2] [:3] [:4]})))
(t/testing "Recursive rules"
(t/is (= (api/q db
'{:find [?e2]
:where [(follow ?e1 ?e2)]
:args [{:?e1 :1}]
:rules [[(follow ?e1 ?e2)
[?e1 :follow ?e2]]
[(follow ?e1 ?e2)
[?e1 :follow ?t]
(follow ?t ?e2)]]})
#{[:2] [:3] [:4] [:6]}))
(f/with-kv-store
(fn []
(f/transact-entity-maps! f/*kv* [{:crux.db/id :1 :follow :2}
{:crux.db/id :2 :follow :3}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(follow ?e1 ?e2)]
:rules [[(follow ?e1 ?e2)
[?e1 :follow ?e2]]
[(follow ?e1 ?e2)
(follow ?e2 ?e1)]]})
#{[:1 :2] [:2 :3] [:2 :1] [:3 :2]})))))
(f/with-kv-store
(fn []
(f/transact-entity-maps! f/*kv* [{:crux.db/id :1 :follow :2}
{:crux.db/id :2 :follow :3}
{:crux.db/id :3 :follow :1}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(follow ?e1 ?e2)]
:rules [[(follow ?e1 ?e2)
[?e1 :follow ?e2]]
[(follow ?e1 ?e2)
(follow ?e2 ?e1)]]})
#{[:1 :2] [:2 :3] [:3 :1] [:2 :1] [:3 :2] [:1 :3]}))))))
(t/testing "Mutually recursive rules"
(f/with-kv-store
(fn []
(f/transact-entity-maps! f/*kv* [{:crux.db/id :0 :f1 :1}
{:crux.db/id :1 :f2 :2}
{:crux.db/id :2 :f1 :3}
{:crux.db/id :3 :f2 :4}
{:crux.db/id :4 :f1 :5}
{:crux.db/id :5 :f2 :6}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(f1 ?e1 ?e2)]
:rules [[(f1 ?e1 ?e2)
[?e1 :f1 ?e2]]
[(f1 ?e1 ?e2)
[?t :f1 ?e2]
(f2 ?e1 ?t)]
[(f2 ?e1 ?e2)
[?e1 :f2 ?e2]]
[(f2 ?e1 ?e2)
[?t :f2 ?e2]
(f1 ?e1 ?t)]]})
#{[:0 :1] [:0 :3] [:0 :5]
[:1 :3] [:1 :5]
[:2 :3] [:2 :5]
[:3 :5]
[:4 :5]}))))))
(t/testing "Passing ins to rule"
(t/is (= (api/q db
{:find '[?x ?y]
:where '[(match ?even ?x ?y)]
:rules '[[(match ?pred ?e ?e2)
[?e :follow ?e2]
[(?pred ?e)]
[(?pred ?e2)]]]
:args [{:?even even-kw?}]})
#{[:4 :6] [:2 :4]})))))
(t/deftest data-script-test-query-fns
;; NOTE: Crux does not support these functions.
#_(t/testing "ground")
#_(t/testing "get-else")
#_(t/testing "get-some")
#_(t/testing "missing?")
#_(t/testing "missing? back-ref")
;; NOTE: Crux does not currently support destructuring.
#_(t/testing "Destructured conflicting function values for two bindings.")
#_(t/testing "Result bindings"))
(defn kw-less-than? [x y]
(< (Long/parseLong (name x))
(Long/parseLong (name y))))
(t/deftest datascript-test-predicates
(f/transact-entity-maps! f/*kv* [{:crux.db/id :1 :name "<NAME>" :age 10}
{:crux.db/id :2 :name "<NAME>" :age 20}
{:crux.db/id :3 :name "<NAME>" :age 10}
{:crux.db/id :4 :name "<NAME>" :age 20}])
(let [db (api/db *kv*)]
;; NOTE: Crux does not support source vars.
#_(let [pred (fn [db e a]
(= a (:age (d/entity db e))))]
(t/is (= (api/q '[:find ?e
:in $ ?pred
:where [?e :age ?a]
[(?pred $ ?e 10)]]
db pred)
#{[1] [3]})))))
;; Tests from Racket Datalog
;; https://github.com/racket/datalog/tree/master/tests/examples
;; Tests from
;; https://pdfs.semanticscholar.org/9374/f0da312f3ba77fa840071d68935a28cba364.pdf
| true | (ns crux.query-test
(:require [clojure.spec.alpha :as s]
[clojure.test :as t]
[crux.db :as db]
[crux.api :as api]
[crux.fixtures :as f :refer [*kv*]])
(:import java.util.UUID))
(t/use-fixtures :each f/with-kv-store)
(t/deftest test-basic-query
(f/transact-people! *kv*
;; tag::test-basic-query-d[]
[{:crux.db/id :ivPI:NAME:<NAME>END_PI
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :pePI:NAME:<NAME>END_PI
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :PI:NAME:<NAME>END_PI
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}]
;; end::test-basic-query-d[]
)
(t/testing "Can query across fields for same value when value is passed in"
(t/is (=
;; tag::test-basic-query-r[]
#{[:smith]}
;; end::test-basic-query-r[]
(api/q (api/db *kv*) (quote
;; tag::test-basic-query-q[]
{:find [p1]
:where [[p1 :name name]
[p1 :last-name name]
[p1 :name "PI:NAME:<NAME>END_PI"]]}
;; end::test-basic-query-q[]
))))))
(t/deftest test-query-with-arguments
(let [[ivan petr] (f/transact-people! *kv*
;; tag::query-with-arguments-d[]
[{:crux.db/id :ivPI:NAME:<NAME>END_PI
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :pePI:NAME:<NAME>END_PI
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :PI:NAME:<NAME>END_PI
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}]
;; end::query-with-arguments-d[]
)]
(t/testing "Can match on both entity and value position"
(t/is (=
;; tag::query-with-arguments1-r[]
#{["PI:NAME:<NAME>END_PI"]}
;; end::query-with-arguments1-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments1-q[]
{:find [name]
:where [[e :name name]]
:args [{:e :ivan
:name "PI:NAME:<NAME>END_PI"}]}
;; end::query-with-arguments1-q[]
)))))
(t/testing "Can query entity by single field with several arguments"
(t/is (=
;; tag::query-with-arguments2-r[]
#{[:ivan] [:petr]}
;; end::query-with-arguments2-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments2-q[]
{:find [e]
:where [[e :name name]]
:args [{:name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI"}]}
;; end::query-with-arguments2-q[]
)))))
(t/testing "Can query entity with tuple arguments"
(t/is (=
;; tag::query-with-arguments3-r[]
#{[:ivan] [:petr]}
;; end::query-with-arguments3-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments3-q[]
{:find [e]
:where [[e :name name]
[e :last-name last-name]]
:args [{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}]}
;; end::query-with-arguments3-q[]
)))))
(t/testing "Can query predicates based on arguments alone"
(t/is (=
;; tag::query-with-arguments4-r[]
#{["PI:NAME:<NAME>END_PI"]}
;; end::query-with-arguments4-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments4-q[]
{:find [name]
:where [[(re-find #"I" name)]
[(= last-name "PI:NAME:<NAME>END_PI")]]
:args [{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}]}
;; end::query-with-arguments4-q[]
))))
(t/testing "Can use range constraints on arguments"
(t/is (=
;; tag::query-with-arguments5-r[]
#{[22]}
;; end::query-with-arguments5-r[]
(api/q
(api/db *kv*)
(quote
;; tag::query-with-arguments5-q[]
{:find [age]
:where [[(>= age 21)]]
:args [{:age 22}]}
;; end::query-with-arguments5-q[]
))))))))
(t/deftest test-basic-query-at-t
(let [[malcolm] (f/transact-people!
*kv*
;; tag::query-at-t-d1[]
[{:crux.db/id :malcolm :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}]
#inst "1986-10-22"
;; end::query-at-t-d1[]
)
[malcolm2] (f/transact-people!
*kv*
;; tag::query-at-t-d2[]
[{:crux.db/id :malcolm :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}]
#inst "1986-10-24")
;; end::query-at-t-d2[]
]
(let [q (quote
;; tag::query-at-t-q[]
{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]
[e :last-name "PI:NAME:<NAME>END_PI"]]}
;; end::query-at-t-q[]
)]
(t/is (=
;; tag::query-at-t-q1-r[]
#{}
;; end::query-at-t-q1-r[]
;; tag::query-at-t-q1-q[]
; Using Clojure: `(api/q (api/db my-crux-system #inst "1986-10-23") q)`
;; end::query-at-t-q1-q[]
(api/q (api/db *kv* #inst "1986-10-23") q)
))
(t/is (=
;; tag::query-at-t-q2-r[]
#{[:malcolm]}
;; end::query-at-t-q2-r[]
;; tag::query-at-t-q2-q[]
; Using Clojure: `(api/q (api/db my-crux-system) q)`
;; end::query-at-t-q2-q[]
(api/q (api/db *kv*) q)
)))))
;; tag::history-full[]
(api/submit-tx
system
[[:crux.tx/put :ids.persons/Jeff
{:crux.db/id :ids.persons/Jeff
:person/name "PI:NAME:<NAME>END_PI"
:person/wealth 100}
#inst "2018-05-18T09:20:27.966"]
[:crux.tx/put :ids.persons/Jeff
{:crux.db/id :ids.persons/Jeff
:person/name "PI:NAME:<NAME>END_PI"
:person/wealth 1000}
#inst "2015-05-18T09:20:27.966"]])
;yields
{:crux.tx/tx-id 1555314836178,
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00"}
(api/history system :ids.persons/Jeff)
; yields
[{:crux.db/id ; sha1 hash of document id
"c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash ; sha1 hash of document contents
"6ca48d3bf05a16cd8d30e6b466f76d5cc281b561",
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817}
{:crux.db/id "c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529",
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178}]
;; end::history-full[]
;; tag::history-range[]
(crux.api/history-range system :ids.persons/Jeff
#inst "2015-05-18T09:20:27.966" ; valid-time start or nil
#inst "2015-05-18T09:20:27.966" ; transaction-time start or nil
#inst "2020-05-18T09:20:27.966" ; valid-time end or nil, inclusive
#inst "2020-05-18T09:20:27.966") ; transaction-time end or nil, inclusive.
; yields
({:crux.db/id ; sha1 hash of document id
"c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash ; sha1 hash of document contents
"a95f149636e0a10a78452298e2135791c0203529",
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178}
{:crux.db/id "c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613",
:crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561",
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817})
(crux.api/entity (crux.api/db system) "c7e66f757f198e08a07a8ea6dfc84bc3ab1c6613")
; yields
{:crux.db/id :ids.persons/PI:NAME:<NAME>END_PI,
:d.person/name "PI:NAME:<NAME>END_PI",
:d.person/wealth 100}
;; end::history-range[]
(t/deftest test-query-across-entities-using-join
;; Five people, two of which share the same name:
(f/transact-people! *kv*
;; tag::join-d[]
[{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :PI:NAME:<NAME>END_PI :name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :sergei :name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :denis-a :name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :denis-b :name "PI:NAME:<NAME>END_PI"}]
;; end::join-d[]
)
(t/testing "Every person joins once, plus 2 more matches"
(t/is (=
;; tag::join-r[]
#{[:ivan :ivan]
[:petr :petr]
[:sergei :sergei]
[:denis-a :denis-a]
[:denis-b :denis-b]
[:denis-a :denis-b]
[:denis-b :denis-a]}
;; end::join-r[]
(api/q (api/db *kv*) (quote
;; tag::join-q[]
{:find [p1 p2]
:where [[p1 :name name]
[p2 :name name]]}
;; end::join-q[]
))))))
(t/deftest test-join-over-two-attributes
(f/transact-people! *kv*
;; tag::join2-d[]
[{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :follows #{"Ivanov"}}]
;; end::join2-d[]
)
(t/is (=
;; tag::join2-r[]
#{[:petr]}
;; end::join2-r[]
(api/q (api/db *kv*) (quote
;; tag::join2-q[]
{:find [e2]
:where [[e :last-name last-name]
[e2 :follows last-name]
[e :name "PI:NAME:<NAME>END_PI"]]}
;; end::join2-q[]
)))))
;; tag::blanks[]
(t/deftest test-blanks
(f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}])
(t/is (= #{["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[_ :name name]]}))))
;; end::blanks[]
;; tag::not[]
(t/deftest test-not-query
(f/transact-people! *kv* [{:crux.db/id :ivan-ivanov-1 :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :ivan-ivanov-2 :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :ivan-ivanovtov-1 :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}])
(t/testing "literal v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "PI:NAME:<NAME>END_PI"]
(not [e :last-name "PI:NAME:<NAME>END_PI"])]}))))
(t/testing "multiple clauses in not"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "PI:NAME:<NAME>END_PI"]
(not [e :last-name "PI:NAME:<NAME>END_PI"]
[(string? name)])]}))))))
(t/testing "variable v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[:ivan-ivanovtov-1 :last-name i-name]
(not [e :last-name i-name])]}))))))
;; end::not[]
;; tag::or[]
(t/deftest test-or-query
(f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}])
(t/testing "Or works as expected"
(t/is (= 3 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "PI:NAME:<NAME>END_PI"]
(or [e :last-name "PI:NAME:<NAME>END_PI"]
[e :last-name "PI:NAME:<NAME>END_PI"])]}))))))
;; end::or[]
;; tag::or-and[]
(t/deftest test-or-query-can-use-and
(let [[ivan] (f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI" :sex :male}
{:name "PI:NAME:<NAME>END_PI" :sex :male}
{:name "PI:NAME:<NAME>END_PI" :sex :female}])]
(t/is (= #{["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(or [e :sex :female]
(and [e :sex :male]
[e :name "PI:NAME:<NAME>END_PI"]))]})))))
;; end::or-and[]
;; tag::or-and2[]
(t/deftest test-ors-can-introduce-new-bindings
(let [[petr ivan ivanova] (f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :male}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :male}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :female}])]
(t/testing "?p2 introduced only inside of an Or"
(t/is (= #{[(:crux.db/id ivan)]} (api/q (api/db *kv*) '{:find [?p2]
:where [(or (and [?p2 :name "PI:NAME:<NAME>END_PI"]
[?p2 :sex :female])
(and [?p2 :last-name "PI:NAME:<NAME>END_PI"]
[?p2 :sex :male]))]}))))))
;; end::or-and2[]
;; tag::not-join[]
(t/deftest test-not-join
(f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}])
(t/testing "Rudimentary not-join"
(t/is (= #{["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(not-join [e]
[e :last-name "PI:NAME:<NAME>END_PI"])]})))))
;; end::not-join[]
(t/deftest test-mixing-expressions
(f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}])
(t/testing "Or can use not expression"
(t/is (= #{["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(or [e :last-name "PI:NAME:<NAME>END_PI"]
(not [e :name "PI:NAME:<NAME>END_PI"]))]}))))
(t/testing "Not can use Or expression"
(t/is (= #{["PI:NAME:<NAME>END_PI"]} (api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(not (or [e :last-name "PI:NAME:<NAME>END_PI"]
[e :name "PI:NAME:<NAME>END_PI"]))]})))))
(t/deftest test-predicate-expression
(f/transact-people! *kv* [{:crux.db/id :ivPI:NAME:<NAME>END_PI :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 30}
{:crux.db/id :bob :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 40}
{:crux.db/id :PI:NAME:<NAME>END_PI :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 50}])
(t/testing "range expressions"
(t/is (= #{["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
[e :age age]
[(< age 50)]]})))
(t/is (= #{["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
[e :age age]
[(>= age 50)]]}))))
(t/testing "clojure.core predicate"
(t/is (= #{["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
[(re-find #"o" name)]]})))
(t/testing "Several variables"
(t/is (= #{[:bob "PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [e last-name]
:where [[e :last-name last-name]
[e :age age]
[(re-find #"ov$" last-name)]
(not [(= age 30)])]}))))
(t/testing "Bind result to var"
(t/is (= #{["PI:NAME:<NAME>END_PI" 25] ["PI:NAME:<NAME>END_PI" 15] ["PI:NAME:<NAME>END_PI" 20]}
(api/q (api/db *kv*) '{:find [name half-age]
:where [[e :name name]
[e :age age]
[(quot age 2) half-age]]})))
(t/testing "Binding more than once intersects result"
(t/is (= #{["PI:NAME:<NAME>END_PI" 15]}
(api/q (api/db *kv*) '{:find [name half-age]
:where [[e :name name]
[e :age real-age]
[(quot real-age 2) half-age]
[(- real-age 15) half-age]]}))))
(t/testing "Binding can use range predicates"
(t/is (= #{["PI:NAME:<NAME>END_PI" 25]}
(api/q (api/db *kv*) '{:find [name half-age]
:where [[e :name name]
[e :age real-age]
[(quot real-age 2) half-age]
[(> half-age 20)]]})))))))
(t/deftest test-attributes-with-multiple-values
(f/transact-people! *kv* [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 30 :friends #{:bob :dominic}}
{:crux.db/id :bob :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 40 :friends #{:ivan :dominic}}
{:crux.db/id :dominic :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 50 :friends #{:bob}}])
(t/testing "can find multiple values"
(t/is (= #{[:bob] [:dominic]}
(api/q (api/db *kv*) '{:find [f]
:where [[i :name "PI:NAME:<NAME>END_PI"]
[i :friends f]]})))))
(t/deftest test-queries-with-variables-only
(f/transact-people! *kv* [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :mentor :petr}
{:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :mentor :oleg}
{:crux.db/id :oleg :name "PI:NAME:<NAME>END_PI" :mentor :ivan}])
(t/is (= #{[:oleg "PI:NAME:<NAME>END_PI" :petr "PI:NAME:<NAME>END_PI"]
[:ivan "PI:NAME:<NAME>END_PI" :oleg "PI:NAME:<NAME>END_PI"]
[:petr "PI:NAME:<NAME>END_PI" :ivan "PI:NAME:<NAME>END_PI"]} (api/q (api/db *kv*) '{:find [e1 n1 e2 n2]
:where [[e1 :name n1]
[e2 :mentor e1]
[e2 :name n2]]}))))
(t/deftest test-index-unification
(f/transact-people! *kv* [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :mentor :ivan}])
(t/is (= #{[:petr :petr]} (api/q (api/db *kv*) '{:find [p1 p2]
:where [[p1 :name "PI:NAME:<NAME>END_PI"]
[p2 :mentor i]
[(== p1 p2)]]})))
(t/testing "multiple literals in set"
(t/is (= #{[:petr] [:ivan]} (api/q (api/db *kv*) '{:find [p]
:where [[p :name n]
[(== n #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"})]]})))))
(t/deftest test-basic-rules
(f/transact-people! *kv* [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 21}
{:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 18}])
(t/testing "without rule"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [[i :age age]
[(>= age 21)]]}))))
(t/testing "rule using same variable name as body"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [[i :age age]
(over-twenty-one? age)]
:rules [[(over-twenty-one? age)
[(>= age 21)]]]}))))
(t/testing "rules directly on arguments"
(t/is (= #{[21]} (api/q (api/db *kv*) '{:find [age]
:where [(over-twenty-one? age)]
:args [{:age 21}]
:rules [[(over-twenty-one? age)
[(>= age 21)]]]}))))
(t/testing "rule using multiple arguments"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [[i :age age]
(over-age? age 21)]
:rules [[(over-age? [age] required-age)
[(>= age required-age)]]]}))))
(t/testing "rule using multiple branches"
(t/is (= #{[:ivan]} (api/q (api/db *kv*) '{:find [i]
:where [(is-ivan-or-bob? i)]
:rules [[(is-ivan-or-bob? i)
[i :name "PI:NAME:<NAME>END_PI"]
[i :last-name "PI:NAME:<NAME>END_PI"]]
[(is-ivan-or-bob? i)
[i :name "PI:NAME:<NAME>END_PI"]]]})))
(t/is (= #{["PI:NAME:<NAME>END_PI"]} (api/q (api/db *kv*) '{:find [name]
:where [[i :name name]
(not (is-ivan-or-bob? i))]
:rules [[(is-ivan-or-bob? i)
[i :name "PI:NAME:<NAME>END_PI"]]
[(is-ivan-or-bob? i)
[i :name "PI:NAME:<NAME>END_PI"]]]}))))
;; https://www.comp.nus.edu.sg/~ooibc/stbtree95.pdf
;; This test is based on section 7. Support for complex queries in
;; bitemporal databases
;; p1 NY [0,3] [4,now]
;; p1 LA [4,now] [4,now]
;; p2 SFO [0,now] [0,5]
;; p2 SFO [0,5] [5,now]
;; p3 LA [0,now] [0,4]
;; p3 LA [0,4] [4,7]
;; p3 LA [0,7] [7,now]
;; p3 SFO [8,0] [8,now]
;; p4 NY [2,now] [2,3]
;; p4 NY [2,3] [3,now]
;; p4 LA [8,now] [8,now]
;; p5 LA [1O,now] [1O,now]
;; p6 NY [12,now] [12,now]
;; p7 NY [11,now] [11,now]
;; Find all persons who are known to be present in the United States
;; on day 2 (valid time), as of day 3 (transaction time)
;; t2 p2 SFO, t5 p3 LA, t9 p4 NY, t10 p4 NY (?)
(comment
;; tag::bitemp0[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp0[]
;; tag::bitemp2[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time :na}
#inst "2019-01-02"
;; end::bitemp2[]
;; tag::bitemp3[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp3[]
;; tag::bitemp4[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp4[]
;; tag::bitemp4b[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp4b[]
;; tag::bitemp4c[]
{:crux.db/id :p1
:entry-pt :LA
:arrival-time #inst "2019-01-04"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-04"}
#inst "2019-01-04"
;; end::bitemp4c[]
;; tag::bitemp5[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-05"}
#inst "2019-01-05"
;; end::bitemp5[]
;; tag::bitemp7[]
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2019-01-04"
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-07"}
#inst "2019-01-07"
;; end::bitemp7[]
;; tag::bitemp8[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
{:crux.db/id :p4
:entry-pt :LA
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
;; end::bitemp8[]
;; tag::bitemp9[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time #inst "2019-01-08"}
#inst "2019-01-09"
;; end::bitemp9[]
;; tag::bitemp10[]
{:crux.db/id :p5
:entry-pt :LA
:arrival-time #inst "2019-01-10"
:departure-time :na}
#inst "2019-01-10"
;; end::bitemp10[]
;; tag::bitemp11[]
{:crux.db/id :p7
:entry-pt :NY
:arrival-time #inst "2019-01-11"
:departure-time :na}
#inst "2019-01-11"
;; end::bitemp11[]
;; tag::bitemp12[]
{:crux.db/id :p6
:entry-pt :NY
:arrival-time #inst "2019-01-12"
:departure-time :na}
#inst "2019-01-12"
;; end::bitemp12[]
)
;; tag::bitempq[]
{:find [p entry-pt arrival-time departure-time]
:where [[p :entry-pt entry-pt]
[p :arrival-time arrival-time]
[p :departure-time departure-time]]}
#inst "2019-01-02" ; `as of` valid time
#inst "2019-01-03" ; `as at` transaction time
;; end::bitempq[]
;; tag::bitempr[]
#{[:p2 :SFO #inst "2018-12-31" :na]
[:p3 :LA #inst "2018-12-31" :na]
[:p4 :NY #inst "2019-01-02" :na]}
;; end::bitempr[]
(t/deftest test-bitemp-query-from-indexing-temporal-data-using-existing-b+-trees-paper
(let [tx-log (crux.tx/->KvTxLog *kv*)]
;; Day 0, represented as #inst "2018-12-31"
@(db/submit-tx tx-log [[:crux.tx/put :p2
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"]
[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"]])
;; Day 1, nothing happens.
@(db/submit-tx tx-log [])
;; Day 2
@(db/submit-tx tx-log [[:crux.tx/put :p4
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time :na}
#inst "2019-01-02"]])
;; Day 3
(let [third-day-submitted-tx @(db/submit-tx tx-log [[:crux.tx/put :p4
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"]])]
;; Day 4, correction, adding missing trip on new arrival.
@(db/submit-tx tx-log [[:crux.tx/put :p1
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"]
[:crux.tx/put :p1
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"]
[:crux.tx/put :p1
{:crux.db/id :p1
:entry-pt :LA
:arrival-time #inst "2019-01-04"
:departure-time :na}
#inst "2019-01-04"]
[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-04"}
#inst "2019-01-04"]])
;; Day 5
@(db/submit-tx tx-log [[:crux.tx/put :p2
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-05"}
#inst "2019-01-05"]])
;; Day 6, nothing happens.
@(db/submit-tx tx-log [])
;; Day 7-12, correction of deletion/departure on day 4. Shows
;; how valid time cannot be the same as arrival time.
@(db/submit-tx tx-log [[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2019-01-04"]
[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-07"}
#inst "2019-01-07"]])
@(db/submit-tx tx-log [[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"]
[:crux.tx/put :p4
{:crux.db/id :p4
:entry-pt :LA
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"]])
@(db/submit-tx tx-log [[:crux.tx/put :p3
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time #inst "2019-01-08"}
#inst "2019-01-09"]])
@(db/submit-tx tx-log [[:crux.tx/put :p5
{:crux.db/id :p5
:entry-pt :LA
:arrival-time #inst "2019-01-10"
:departure-time :na}
#inst "2019-01-10"]])
@(db/submit-tx tx-log [[:crux.tx/put :p7
{:crux.db/id :p7
:entry-pt :NY
:arrival-time #inst "2019-01-11"
:departure-time :na}
#inst "2019-01-11"]])
@(db/submit-tx tx-log [[:crux.tx/put :p6
{:crux.db/id :p6
:entry-pt :NY
:arrival-time #inst "2019-01-12"
:departure-time :na}
#inst "2019-01-12"]])
(t/is (= #{[:p2 :SFO #inst "2018-12-31" :na]
[:p3 :LA #inst "2018-12-31" :na]
[:p4 :NY #inst "2019-01-02" :na]}
(api/q (api/db f/*kv* #inst "2019-01-02" (:crux.tx/tx-time third-day-submitted-tx))
'{:find [p entry-pt arrival-time departure-time]
:where [[p :entry-pt entry-pt]
[p :arrival-time arrival-time]
[p :departure-time departure-time]]}))))))
;; Tests borrowed from Datascript:
;; https://github.com/tonsky/datascript/tree/master/test/datascript/test
(defn populate-datascript-test-db []
(f/transact-entity-maps! *kv* [{:crux.db/id :1 :name "PI:NAME:<NAME>END_PI" :age 10}
{:crux.db/id :2 :name "PI:NAME:<NAME>END_PI" :age 20}
{:crux.db/id :3 :name "PI:NAME:<NAME>END_PI" :age 10}
{:crux.db/id :4 :name "PI:NAME:<NAME>END_PI" :age 20}
{:crux.db/id :5 :name "PI:NAME:<NAME>END_PI" :age 10}
{:crux.db/id :6 :name "PI:NAME:<NAME>END_PI" :age 20} ]))
(t/deftest test-rules
(f/transact-entity-maps! f/*kv* [{:crux.db/id :5 :follow :3}
{:crux.db/id :1 :follow :2}
{:crux.db/id :2 :follow #{:3 :4}}
{:crux.db/id :3 :follow :4}
{:crux.db/id :4 :follow :6}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(follow ?e1 ?e2)]
:rules [[(follow ?x ?y)
[?x :follow ?y]]]})
#{[:1 :2] [:2 :3] [:3 :4] [:2 :4] [:5 :3] [:4 :6]}))
;; NOTE: Crux does not support vars in attribute position, so
;; :follow is explicit.
(t/testing "Joining regular clauses with rule"
(t/is (= (api/q db
'{:find [?y ?x]
:where [[_ :follow ?x]
(rule ?x ?y)
[(crux.query-test/even-kw? ?x)]]
:rules [[(rule ?a ?b)
[?a :follow ?b]]]})
#{[:3 :2] [:6 :4] [:4 :2]})))
;; NOTE: Crux does not support vars in attribute position.
#_(t/testing "Rule context is isolated from outer context"
(t/is (= (api/q db
'{:find [?x]
:where [[?e _ _]
(rule ?x)]
:rules [[(rule ?e)
[_ ?e _]]]})
#{[:follow]})))
(t/testing "Rule with branches"
(t/is (= (api/q db
'{:find [?e2]
:where [(follow ?e1 ?e2)]
:args [{:?e1 :1}]
:rules [[(follow ?e2 ?e1)
[?e2 :follow ?e1]]
[(follow ?e2 ?e1)
[?e2 :follow ?t]
[?t :follow ?e1]]]})
#{[:2] [:3] [:4]})))
(t/testing "Recursive rules"
(t/is (= (api/q db
'{:find [?e2]
:where [(follow ?e1 ?e2)]
:args [{:?e1 :1}]
:rules [[(follow ?e1 ?e2)
[?e1 :follow ?e2]]
[(follow ?e1 ?e2)
[?e1 :follow ?t]
(follow ?t ?e2)]]})
#{[:2] [:3] [:4] [:6]}))
(f/with-kv-store
(fn []
(f/transact-entity-maps! f/*kv* [{:crux.db/id :1 :follow :2}
{:crux.db/id :2 :follow :3}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(follow ?e1 ?e2)]
:rules [[(follow ?e1 ?e2)
[?e1 :follow ?e2]]
[(follow ?e1 ?e2)
(follow ?e2 ?e1)]]})
#{[:1 :2] [:2 :3] [:2 :1] [:3 :2]})))))
(f/with-kv-store
(fn []
(f/transact-entity-maps! f/*kv* [{:crux.db/id :1 :follow :2}
{:crux.db/id :2 :follow :3}
{:crux.db/id :3 :follow :1}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(follow ?e1 ?e2)]
:rules [[(follow ?e1 ?e2)
[?e1 :follow ?e2]]
[(follow ?e1 ?e2)
(follow ?e2 ?e1)]]})
#{[:1 :2] [:2 :3] [:3 :1] [:2 :1] [:3 :2] [:1 :3]}))))))
(t/testing "Mutually recursive rules"
(f/with-kv-store
(fn []
(f/transact-entity-maps! f/*kv* [{:crux.db/id :0 :f1 :1}
{:crux.db/id :1 :f2 :2}
{:crux.db/id :2 :f1 :3}
{:crux.db/id :3 :f2 :4}
{:crux.db/id :4 :f1 :5}
{:crux.db/id :5 :f2 :6}])
(let [db (api/db *kv*)]
(t/is (= (api/q db
'{:find [?e1 ?e2]
:where [(f1 ?e1 ?e2)]
:rules [[(f1 ?e1 ?e2)
[?e1 :f1 ?e2]]
[(f1 ?e1 ?e2)
[?t :f1 ?e2]
(f2 ?e1 ?t)]
[(f2 ?e1 ?e2)
[?e1 :f2 ?e2]]
[(f2 ?e1 ?e2)
[?t :f2 ?e2]
(f1 ?e1 ?t)]]})
#{[:0 :1] [:0 :3] [:0 :5]
[:1 :3] [:1 :5]
[:2 :3] [:2 :5]
[:3 :5]
[:4 :5]}))))))
(t/testing "Passing ins to rule"
(t/is (= (api/q db
{:find '[?x ?y]
:where '[(match ?even ?x ?y)]
:rules '[[(match ?pred ?e ?e2)
[?e :follow ?e2]
[(?pred ?e)]
[(?pred ?e2)]]]
:args [{:?even even-kw?}]})
#{[:4 :6] [:2 :4]})))))
(t/deftest data-script-test-query-fns
;; NOTE: Crux does not support these functions.
#_(t/testing "ground")
#_(t/testing "get-else")
#_(t/testing "get-some")
#_(t/testing "missing?")
#_(t/testing "missing? back-ref")
;; NOTE: Crux does not currently support destructuring.
#_(t/testing "Destructured conflicting function values for two bindings.")
#_(t/testing "Result bindings"))
(defn kw-less-than? [x y]
(< (Long/parseLong (name x))
(Long/parseLong (name y))))
(t/deftest datascript-test-predicates
(f/transact-entity-maps! f/*kv* [{:crux.db/id :1 :name "PI:NAME:<NAME>END_PI" :age 10}
{:crux.db/id :2 :name "PI:NAME:<NAME>END_PI" :age 20}
{:crux.db/id :3 :name "PI:NAME:<NAME>END_PI" :age 10}
{:crux.db/id :4 :name "PI:NAME:<NAME>END_PI" :age 20}])
(let [db (api/db *kv*)]
;; NOTE: Crux does not support source vars.
#_(let [pred (fn [db e a]
(= a (:age (d/entity db e))))]
(t/is (= (api/q '[:find ?e
:in $ ?pred
:where [?e :age ?a]
[(?pred $ ?e 10)]]
db pred)
#{[1] [3]})))))
;; Tests from Racket Datalog
;; https://github.com/racket/datalog/tree/master/tests/examples
;; Tests from
;; https://pdfs.semanticscholar.org/9374/f0da312f3ba77fa840071d68935a28cba364.pdf
|
[
{
"context": " (assoc-in [:session :store] (cookie-store {:key \"I'm a 16-bit key\"}))\n (assoc-in [:security :ssl-redirect] {:s",
"end": 1590,
"score": 0.9968998432159424,
"start": 1574,
"tag": "KEY",
"value": "I'm a 16-bit key"
}
] | src/quackers/handler.clj | innoq/quackers | 13 | (ns quackers.handler
(:require [compojure.core :refer :all]
[compojure.route :as route]
[ring.middleware.defaults :refer [wrap-defaults secure-site-defaults]]
[ring.middleware.session.cookie :refer [cookie-store]]
[quackers.helpers :as h]
[quackers.users :refer [user-routes]]
[quackers.authentication :refer [auth-routes auth-middleware]]
[quackers.quacker :refer [quacker-routes]]
[clojure.tools.logging :as log]
[buddy.auth :refer [authenticated?]]))
(defn app-routes []
(routes
(auth-routes)
(quacker-routes)
(user-routes)
(route/not-found "Not Found!")))
(defn ignore-trailing-slash
"Modifies the request uri before calling the handler.
Removes a single trailing slash from the end of the uri if present.
Useful for handling optional trailing slashes until Compojure's route matching syntax supports regex.
Adapted from http://stackoverflow.com/questions/8380468/compojure-regex-for-matching-a-trailing-slash"
[handler]
(fn [request]
(let [uri (:uri request)]
(handler (assoc request :uri (if (and (not (= "/" uri))
(.endsWith uri "/"))
(subs uri 0 (dec (count uri)))
uri))))))
(defn logging-middleware [handler]
(fn [request]
(let [response (handler request)]
response)))
(defn middleware-settings []
(-> secure-site-defaults
(assoc-in [:session :store] (cookie-store {:key "I'm a 16-bit key"}))
(assoc-in [:security :ssl-redirect] {:ssl-port (h/ssl-port)})))
;;(assoc-in [:security :hsts] false))) ;; for non-standard ssl-port
(def app
(-> (app-routes)
ignore-trailing-slash
;;logging-middleware
auth-middleware
(wrap-defaults (middleware-settings))))
| 53565 | (ns quackers.handler
(:require [compojure.core :refer :all]
[compojure.route :as route]
[ring.middleware.defaults :refer [wrap-defaults secure-site-defaults]]
[ring.middleware.session.cookie :refer [cookie-store]]
[quackers.helpers :as h]
[quackers.users :refer [user-routes]]
[quackers.authentication :refer [auth-routes auth-middleware]]
[quackers.quacker :refer [quacker-routes]]
[clojure.tools.logging :as log]
[buddy.auth :refer [authenticated?]]))
(defn app-routes []
(routes
(auth-routes)
(quacker-routes)
(user-routes)
(route/not-found "Not Found!")))
(defn ignore-trailing-slash
"Modifies the request uri before calling the handler.
Removes a single trailing slash from the end of the uri if present.
Useful for handling optional trailing slashes until Compojure's route matching syntax supports regex.
Adapted from http://stackoverflow.com/questions/8380468/compojure-regex-for-matching-a-trailing-slash"
[handler]
(fn [request]
(let [uri (:uri request)]
(handler (assoc request :uri (if (and (not (= "/" uri))
(.endsWith uri "/"))
(subs uri 0 (dec (count uri)))
uri))))))
(defn logging-middleware [handler]
(fn [request]
(let [response (handler request)]
response)))
(defn middleware-settings []
(-> secure-site-defaults
(assoc-in [:session :store] (cookie-store {:key "<KEY>"}))
(assoc-in [:security :ssl-redirect] {:ssl-port (h/ssl-port)})))
;;(assoc-in [:security :hsts] false))) ;; for non-standard ssl-port
(def app
(-> (app-routes)
ignore-trailing-slash
;;logging-middleware
auth-middleware
(wrap-defaults (middleware-settings))))
| true | (ns quackers.handler
(:require [compojure.core :refer :all]
[compojure.route :as route]
[ring.middleware.defaults :refer [wrap-defaults secure-site-defaults]]
[ring.middleware.session.cookie :refer [cookie-store]]
[quackers.helpers :as h]
[quackers.users :refer [user-routes]]
[quackers.authentication :refer [auth-routes auth-middleware]]
[quackers.quacker :refer [quacker-routes]]
[clojure.tools.logging :as log]
[buddy.auth :refer [authenticated?]]))
(defn app-routes []
(routes
(auth-routes)
(quacker-routes)
(user-routes)
(route/not-found "Not Found!")))
(defn ignore-trailing-slash
"Modifies the request uri before calling the handler.
Removes a single trailing slash from the end of the uri if present.
Useful for handling optional trailing slashes until Compojure's route matching syntax supports regex.
Adapted from http://stackoverflow.com/questions/8380468/compojure-regex-for-matching-a-trailing-slash"
[handler]
(fn [request]
(let [uri (:uri request)]
(handler (assoc request :uri (if (and (not (= "/" uri))
(.endsWith uri "/"))
(subs uri 0 (dec (count uri)))
uri))))))
(defn logging-middleware [handler]
(fn [request]
(let [response (handler request)]
response)))
(defn middleware-settings []
(-> secure-site-defaults
(assoc-in [:session :store] (cookie-store {:key "PI:KEY:<KEY>END_PI"}))
(assoc-in [:security :ssl-redirect] {:ssl-port (h/ssl-port)})))
;;(assoc-in [:security :hsts] false))) ;; for non-standard ssl-port
(def app
(-> (app-routes)
ignore-trailing-slash
;;logging-middleware
auth-middleware
(wrap-defaults (middleware-settings))))
|
[
{
"context": "(ns #^{:author \"Roger Allen\"\n :doc \"Shadertoy meets Overtone. A demons",
"end": 27,
"score": 0.9998628497123718,
"start": 16,
"tag": "NAME",
"value": "Roger Allen"
},
{
"context": ";; once here.\n\n;; inspiration https://twitter.com/redFrik/status/329311535723839489\n;; more translated twee",
"end": 324,
"score": 0.9993509650230408,
"start": 317,
"tag": "USERNAME",
"value": "redFrik"
},
{
"context": "; more translated tweets in\n;; https://github.com/rogerallen/explore_overtone/blob/master/src/explore_overtone",
"end": 412,
"score": 0.9996097683906555,
"start": 402,
"tag": "USERNAME",
"value": "rogerallen"
},
{
"context": "o inspired by\")\n (println \"https://twitter.com/redFrik/status/329311535723839489\\nEnjoy...\")\n (Thread",
"end": 1372,
"score": 0.9995042681694031,
"start": 1365,
"tag": "USERNAME",
"value": "redFrik"
}
] | src/shadertone/core.clj | baskeboler/shadertone | 304 | (ns #^{:author "Roger Allen"
:doc "Shadertoy meets Overtone. A demonstration for 'lein run'"}
shadertone.core
(:use [overtone.live])
(:require [shadertone.tone :as t])
(:gen-class))
;; See examples/00demo_intro_tour.clj for the example code that was
;; once here.
;; inspiration https://twitter.com/redFrik/status/329311535723839489
;; more translated tweets in
;; https://github.com/rogerallen/explore_overtone/blob/master/src/explore_overtone/redFrik.clj
(defsynth red-frik-329311535723839489
[gate 1]
(out
0
(* (env-gen (adsr 3.0 0.1 0.8 3.0) :gate gate :action FREE)
(rlpf:ar
(distort
(leak-dc:ar
(lf-tri:ar
(let [t (leak-dc:ar
(sum
(for [x (range 1 9)]
(pan2:ar
(> (lf-tri:ar
(/ 1 x) (/ x 3)) 0.3333)
(lf-tri:ar (/ 666 x))))))
;; add a filtered tap to use in the shader
_ (tap "t0" 60 (a2k (lag t 0.5)))]
(* t 999))))) 3e3))))
(defn -main [& args]
(let [rf (red-frik-329311535723839489)]
(t/start "examples/redFrik.glsl"
:width 1280 :height 720
:user-data {"t0" (atom {:synth rf :tap "t0"})})
(println "Playing a 60 second demo inspired by")
(println "https://twitter.com/redFrik/status/329311535723839489\nEnjoy...")
(Thread/sleep (* 60 1000))
(println "Done.")
(ctl rf :gate 0) ;; fade out
(Thread/sleep (* 3 1000))
(t/stop)
(stop)
(System/exit 0)))
| 76887 | (ns #^{:author "<NAME>"
:doc "Shadertoy meets Overtone. A demonstration for 'lein run'"}
shadertone.core
(:use [overtone.live])
(:require [shadertone.tone :as t])
(:gen-class))
;; See examples/00demo_intro_tour.clj for the example code that was
;; once here.
;; inspiration https://twitter.com/redFrik/status/329311535723839489
;; more translated tweets in
;; https://github.com/rogerallen/explore_overtone/blob/master/src/explore_overtone/redFrik.clj
(defsynth red-frik-329311535723839489
[gate 1]
(out
0
(* (env-gen (adsr 3.0 0.1 0.8 3.0) :gate gate :action FREE)
(rlpf:ar
(distort
(leak-dc:ar
(lf-tri:ar
(let [t (leak-dc:ar
(sum
(for [x (range 1 9)]
(pan2:ar
(> (lf-tri:ar
(/ 1 x) (/ x 3)) 0.3333)
(lf-tri:ar (/ 666 x))))))
;; add a filtered tap to use in the shader
_ (tap "t0" 60 (a2k (lag t 0.5)))]
(* t 999))))) 3e3))))
(defn -main [& args]
(let [rf (red-frik-329311535723839489)]
(t/start "examples/redFrik.glsl"
:width 1280 :height 720
:user-data {"t0" (atom {:synth rf :tap "t0"})})
(println "Playing a 60 second demo inspired by")
(println "https://twitter.com/redFrik/status/329311535723839489\nEnjoy...")
(Thread/sleep (* 60 1000))
(println "Done.")
(ctl rf :gate 0) ;; fade out
(Thread/sleep (* 3 1000))
(t/stop)
(stop)
(System/exit 0)))
| true | (ns #^{:author "PI:NAME:<NAME>END_PI"
:doc "Shadertoy meets Overtone. A demonstration for 'lein run'"}
shadertone.core
(:use [overtone.live])
(:require [shadertone.tone :as t])
(:gen-class))
;; See examples/00demo_intro_tour.clj for the example code that was
;; once here.
;; inspiration https://twitter.com/redFrik/status/329311535723839489
;; more translated tweets in
;; https://github.com/rogerallen/explore_overtone/blob/master/src/explore_overtone/redFrik.clj
(defsynth red-frik-329311535723839489
[gate 1]
(out
0
(* (env-gen (adsr 3.0 0.1 0.8 3.0) :gate gate :action FREE)
(rlpf:ar
(distort
(leak-dc:ar
(lf-tri:ar
(let [t (leak-dc:ar
(sum
(for [x (range 1 9)]
(pan2:ar
(> (lf-tri:ar
(/ 1 x) (/ x 3)) 0.3333)
(lf-tri:ar (/ 666 x))))))
;; add a filtered tap to use in the shader
_ (tap "t0" 60 (a2k (lag t 0.5)))]
(* t 999))))) 3e3))))
(defn -main [& args]
(let [rf (red-frik-329311535723839489)]
(t/start "examples/redFrik.glsl"
:width 1280 :height 720
:user-data {"t0" (atom {:synth rf :tap "t0"})})
(println "Playing a 60 second demo inspired by")
(println "https://twitter.com/redFrik/status/329311535723839489\nEnjoy...")
(Thread/sleep (* 60 1000))
(println "Done.")
(ctl rf :gate 0) ;; fade out
(Thread/sleep (* 3 1000))
(t/stop)
(stop)
(System/exit 0)))
|
[
{
"context": ";; Copyright (c) 2015 <Diego Souza>\n\n;; Permission is hereby granted, free of charge",
"end": 34,
"score": 0.9998728036880493,
"start": 23,
"tag": "NAME",
"value": "Diego Souza"
}
] | src/storaged/src/leela/storaged/network/controller.clj | locaweb/leela | 22 | ;; Copyright (c) 2015 <Diego Souza>
;; 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 leela.storaged.network.controller
(:import
[java.nio ByteOrder ByteBuffer])
(:require
[leela.storaged.time :refer :all]
[slingshot.slingshot :refer [try+]]
[clojure.tools.logging :refer [info warn error]]
[leela.storaged.control :refer [try-fn]]
[leela.storaged.network.protocol :refer :all]
[leela.storaged.network.actions.metrics :refer :all]
[leela.storaged.network.actions.bitmap :refer :all]
[leela.storaged.network.actions.sequence :refer :all]))
(defn- fmt-request [r]
(pr-str r))
(defn- fmt-error [e]
(pr-str e))
(defn- fmt-reply [r]
(pr-str r))
(defn- fmt-duration [t]
(pr-str t))
(defn- between? [n [a b]]
(and (<= a n) (> b n)))
(defn m->logger [fun]
(fn [payload]
(let [[duration reply] (time-it (fun payload))
code (status reply)]
(if (between? code [200, 500])
(info (format "%s - %s [%s]"
(fmt-request payload)
(fmt-reply reply)
(fmt-duration duration)))
(info (format "%s - %s [%s]"
(fmt-request payload)
(fmt-error reply)
(human-string duration))))
reply)))
(defn- e-trace [^Throwable e]
(when e
(map str (.getStackTrace e))))
(defn w->error [fun]
(fn [payload]
(try+
(fun payload)
(catch [:type :leela.storaged/user-error] info
(frame
(encode-reply 500 {:trace (e-trace (:cause info))} (:message info))))
(catch Exception e
(error e "unexpected error serving request")
(frame
(encode-reply 500 {:trace (e-trace e)} (.getMessage e)))))))
(defn m->proto [fun]
(fn [payload]
(frame
(if-let [query (unframe-when payload query?)]
(fun query)
(encode-reply 400 {} "bad frame")))))
(defn- handle-bitmap [query]
(case (first (resource query))
"chunk" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-chunk-handler params)))
(encode-reply 404 {} "unknown table")))
(defn- handle-get-sequence [query]
(case (first (resource query))
"block" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-block-handler params)))
"sequence" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-sequence-handler params)))
"seqid" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-seqid-handler params)))
(encode-reply 404 {} "unknown table")))
(defn- handle-put-sequence [query]
(case (first (resource query))
"block" (let [params (second (resource query))]
(encode-reply 200 {} (put-store-block-handler params)))
"sequence" (let [params (second (resource query))]
(encode-reply 200 {} (put-fetch-sequence-handler params)))
(encode-reply 404 {} "unknown table")))
(defn- handle-get [query]
(case (first (resource query))
"metrics" (let [params (second (resource query))]
(encode-reply 200 {} (get-metrics-handler (first params))))
"bitmap" (handle-bitmap (resource-fmap rest query))
"sequence" (handle-get-sequence (ressource-fmap rest query))
(encode-reply 404 {} "unknown table")))
(defn- handle-put [query]
(case (first (resource query))
"metrics" (let [params (second (resource query))]
(encode-reply 201 {} (put-metrics-handler (first params))))
"sequence" (handle-put-sequence (ressource-fmap rest query))
(encode-reply 404 {} "unknown table")))
(defn- handle-post [query]
(case (first (resource query))
"sequence"(let [params (second (resource query))]
(encode-reply 201 {} (post-fetch-next-block-handler (first params))))
(encode-reply 404 {} "unknown table")))
(defn controller [query]
(case (first (resource query))
"get" (handle-get (resource-fmap rest query))
"put" (handle-put (resource-fmap rest query))
"post" (handle-post (ressource-fmap rest query))
(encode-reply 405 {:allow [:get :put]} "unknown verb")))
(defn make-controller [ctrl & middlewares]
(w->error (reduce (fn [f g] (g f)) ctrl middlewares)))
(defn make-controller-default []
(make-controller controller m->logger m->proto))
| 14259 | ;; 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 leela.storaged.network.controller
(:import
[java.nio ByteOrder ByteBuffer])
(:require
[leela.storaged.time :refer :all]
[slingshot.slingshot :refer [try+]]
[clojure.tools.logging :refer [info warn error]]
[leela.storaged.control :refer [try-fn]]
[leela.storaged.network.protocol :refer :all]
[leela.storaged.network.actions.metrics :refer :all]
[leela.storaged.network.actions.bitmap :refer :all]
[leela.storaged.network.actions.sequence :refer :all]))
(defn- fmt-request [r]
(pr-str r))
(defn- fmt-error [e]
(pr-str e))
(defn- fmt-reply [r]
(pr-str r))
(defn- fmt-duration [t]
(pr-str t))
(defn- between? [n [a b]]
(and (<= a n) (> b n)))
(defn m->logger [fun]
(fn [payload]
(let [[duration reply] (time-it (fun payload))
code (status reply)]
(if (between? code [200, 500])
(info (format "%s - %s [%s]"
(fmt-request payload)
(fmt-reply reply)
(fmt-duration duration)))
(info (format "%s - %s [%s]"
(fmt-request payload)
(fmt-error reply)
(human-string duration))))
reply)))
(defn- e-trace [^Throwable e]
(when e
(map str (.getStackTrace e))))
(defn w->error [fun]
(fn [payload]
(try+
(fun payload)
(catch [:type :leela.storaged/user-error] info
(frame
(encode-reply 500 {:trace (e-trace (:cause info))} (:message info))))
(catch Exception e
(error e "unexpected error serving request")
(frame
(encode-reply 500 {:trace (e-trace e)} (.getMessage e)))))))
(defn m->proto [fun]
(fn [payload]
(frame
(if-let [query (unframe-when payload query?)]
(fun query)
(encode-reply 400 {} "bad frame")))))
(defn- handle-bitmap [query]
(case (first (resource query))
"chunk" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-chunk-handler params)))
(encode-reply 404 {} "unknown table")))
(defn- handle-get-sequence [query]
(case (first (resource query))
"block" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-block-handler params)))
"sequence" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-sequence-handler params)))
"seqid" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-seqid-handler params)))
(encode-reply 404 {} "unknown table")))
(defn- handle-put-sequence [query]
(case (first (resource query))
"block" (let [params (second (resource query))]
(encode-reply 200 {} (put-store-block-handler params)))
"sequence" (let [params (second (resource query))]
(encode-reply 200 {} (put-fetch-sequence-handler params)))
(encode-reply 404 {} "unknown table")))
(defn- handle-get [query]
(case (first (resource query))
"metrics" (let [params (second (resource query))]
(encode-reply 200 {} (get-metrics-handler (first params))))
"bitmap" (handle-bitmap (resource-fmap rest query))
"sequence" (handle-get-sequence (ressource-fmap rest query))
(encode-reply 404 {} "unknown table")))
(defn- handle-put [query]
(case (first (resource query))
"metrics" (let [params (second (resource query))]
(encode-reply 201 {} (put-metrics-handler (first params))))
"sequence" (handle-put-sequence (ressource-fmap rest query))
(encode-reply 404 {} "unknown table")))
(defn- handle-post [query]
(case (first (resource query))
"sequence"(let [params (second (resource query))]
(encode-reply 201 {} (post-fetch-next-block-handler (first params))))
(encode-reply 404 {} "unknown table")))
(defn controller [query]
(case (first (resource query))
"get" (handle-get (resource-fmap rest query))
"put" (handle-put (resource-fmap rest query))
"post" (handle-post (ressource-fmap rest query))
(encode-reply 405 {:allow [:get :put]} "unknown verb")))
(defn make-controller [ctrl & middlewares]
(w->error (reduce (fn [f g] (g f)) ctrl middlewares)))
(defn make-controller-default []
(make-controller controller m->logger m->proto))
| true | ;; 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 leela.storaged.network.controller
(:import
[java.nio ByteOrder ByteBuffer])
(:require
[leela.storaged.time :refer :all]
[slingshot.slingshot :refer [try+]]
[clojure.tools.logging :refer [info warn error]]
[leela.storaged.control :refer [try-fn]]
[leela.storaged.network.protocol :refer :all]
[leela.storaged.network.actions.metrics :refer :all]
[leela.storaged.network.actions.bitmap :refer :all]
[leela.storaged.network.actions.sequence :refer :all]))
(defn- fmt-request [r]
(pr-str r))
(defn- fmt-error [e]
(pr-str e))
(defn- fmt-reply [r]
(pr-str r))
(defn- fmt-duration [t]
(pr-str t))
(defn- between? [n [a b]]
(and (<= a n) (> b n)))
(defn m->logger [fun]
(fn [payload]
(let [[duration reply] (time-it (fun payload))
code (status reply)]
(if (between? code [200, 500])
(info (format "%s - %s [%s]"
(fmt-request payload)
(fmt-reply reply)
(fmt-duration duration)))
(info (format "%s - %s [%s]"
(fmt-request payload)
(fmt-error reply)
(human-string duration))))
reply)))
(defn- e-trace [^Throwable e]
(when e
(map str (.getStackTrace e))))
(defn w->error [fun]
(fn [payload]
(try+
(fun payload)
(catch [:type :leela.storaged/user-error] info
(frame
(encode-reply 500 {:trace (e-trace (:cause info))} (:message info))))
(catch Exception e
(error e "unexpected error serving request")
(frame
(encode-reply 500 {:trace (e-trace e)} (.getMessage e)))))))
(defn m->proto [fun]
(fn [payload]
(frame
(if-let [query (unframe-when payload query?)]
(fun query)
(encode-reply 400 {} "bad frame")))))
(defn- handle-bitmap [query]
(case (first (resource query))
"chunk" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-chunk-handler params)))
(encode-reply 404 {} "unknown table")))
(defn- handle-get-sequence [query]
(case (first (resource query))
"block" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-block-handler params)))
"sequence" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-sequence-handler params)))
"seqid" (let [params (second (resource query))]
(encode-reply 200 {} (get-fetch-seqid-handler params)))
(encode-reply 404 {} "unknown table")))
(defn- handle-put-sequence [query]
(case (first (resource query))
"block" (let [params (second (resource query))]
(encode-reply 200 {} (put-store-block-handler params)))
"sequence" (let [params (second (resource query))]
(encode-reply 200 {} (put-fetch-sequence-handler params)))
(encode-reply 404 {} "unknown table")))
(defn- handle-get [query]
(case (first (resource query))
"metrics" (let [params (second (resource query))]
(encode-reply 200 {} (get-metrics-handler (first params))))
"bitmap" (handle-bitmap (resource-fmap rest query))
"sequence" (handle-get-sequence (ressource-fmap rest query))
(encode-reply 404 {} "unknown table")))
(defn- handle-put [query]
(case (first (resource query))
"metrics" (let [params (second (resource query))]
(encode-reply 201 {} (put-metrics-handler (first params))))
"sequence" (handle-put-sequence (ressource-fmap rest query))
(encode-reply 404 {} "unknown table")))
(defn- handle-post [query]
(case (first (resource query))
"sequence"(let [params (second (resource query))]
(encode-reply 201 {} (post-fetch-next-block-handler (first params))))
(encode-reply 404 {} "unknown table")))
(defn controller [query]
(case (first (resource query))
"get" (handle-get (resource-fmap rest query))
"put" (handle-put (resource-fmap rest query))
"post" (handle-post (ressource-fmap rest query))
(encode-reply 405 {:allow [:get :put]} "unknown verb")))
(defn make-controller [ctrl & middlewares]
(w->error (reduce (fn [f g] (g f)) ctrl middlewares)))
(defn make-controller-default []
(make-controller controller m->logger m->proto))
|
[
{
"context": " :person.firstName\n [[1 \"Richard\"]\n [2\"Cindy\"]\n [3",
"end": 159,
"score": 0.9998109340667725,
"start": 152,
"tag": "NAME",
"value": "Richard"
},
{
"context": " [[1 \"Richard\"]\n [2\"Cindy\"]\n [3 \"Craig\"]]\n\n ",
"end": 187,
"score": 0.9998204112052917,
"start": 182,
"tag": "NAME",
"value": "Cindy"
},
{
"context": "\n [2\"Cindy\"]\n [3 \"Craig\"]]\n\n :person.lastName\n ",
"end": 216,
"score": 0.9998410940170288,
"start": 211,
"tag": "NAME",
"value": "Craig"
},
{
"context": " :person.lastName\n [[1 \"Mutt\"]\n [2 \"Marshall\"]\n ",
"end": 279,
"score": 0.9998184442520142,
"start": 275,
"tag": "NAME",
"value": "Mutt"
},
{
"context": "\n [[1 \"Mutt\"]\n [2 \"Marshall\"]\n [3 \"Ellis\"]]\n\n ",
"end": 311,
"score": 0.9998761415481567,
"start": 303,
"tag": "NAME",
"value": "Marshall"
},
{
"context": " [2 \"Marshall\"]\n [3 \"Ellis\"]]\n\n :person.country\n ",
"end": 340,
"score": 0.9998154640197754,
"start": 335,
"tag": "NAME",
"value": "Ellis"
},
{
"context": " :person.nickName\n [[1 \"Dick\"]]\n\n })\n\n\n;;----------------and---",
"end": 602,
"score": 0.9997941851615906,
"start": 598,
"tag": "NAME",
"value": "Dick"
}
] | test/documentation/binary_ops.clj | tkaryadis/louna-local | 0 | (ns documentation.binary-ops
(:use louna.louna
louna.louna-util))
#_(def personDB {
:person.firstName
[[1 "Richard"]
[2"Cindy"]
[3 "Craig"]]
:person.lastName
[[1 "Mutt"]
[2 "Marshall"]
[3 "Ellis"]]
:person.country
[[1 "GREECE"]
[2 "USA"]
[3 "SAUDI-ARABIA"]]
:person.workTel
[[3 "(245) 315-5486"]]
:person.nickName
[[1 "Dick"]]
})
;;----------------and---------------------
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:person.country ?country))
#_(q {:q-in [personDB] :q-out ["print"]}
((:person.firstName ?person ?first)
(:person.lastName ?last))
(:and (:person.country ?person ?country)))
#_(q {:q-in [personDB] :q-out ["print"]}
((:person.firstName ?person ?first)
(:person.lastName ?last))
((:person.country ?person ?country)))
;;-----------------if---------------------
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:person.workTel ?workTel))
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:if (:person.workTel ?person ?workTel)))
#_(q {:q-in [personDB] :q-out ["print"]}
[?first ?last]
(:person.lastName ?person ?last)
(:if (:person.nickName ?person ?first)))
#_(q {:q-in [personDB] :q-out ["print"]}
[?first ?last]
(:person.lastName ?person ?last)
(:if (:person.nickName ?person ?first))
(:if (:person.firstName ?person ?first)))
;;-----------:not-------------------------------
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:not (:person.workTel ?person ?workNum)))
;;-----------:add------------------------------
#_(def booksDB {
:y2000.title
[[2 "SPARQL Protocol Tutorial"]
[3 "SPARQL (updated)"]]
:y2010.title
[[1 "SPARQL Query Language Tutorial"]
[3 "SPARQL"]]
})
#_(q {:q-in [booksDB] :q-out ["print"]}
(:y2000.title ?book ?title00)
(:add (:y2010.title ?book ?title10))) | 58456 | (ns documentation.binary-ops
(:use louna.louna
louna.louna-util))
#_(def personDB {
:person.firstName
[[1 "<NAME>"]
[2"<NAME>"]
[3 "<NAME>"]]
:person.lastName
[[1 "<NAME>"]
[2 "<NAME>"]
[3 "<NAME>"]]
:person.country
[[1 "GREECE"]
[2 "USA"]
[3 "SAUDI-ARABIA"]]
:person.workTel
[[3 "(245) 315-5486"]]
:person.nickName
[[1 "<NAME>"]]
})
;;----------------and---------------------
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:person.country ?country))
#_(q {:q-in [personDB] :q-out ["print"]}
((:person.firstName ?person ?first)
(:person.lastName ?last))
(:and (:person.country ?person ?country)))
#_(q {:q-in [personDB] :q-out ["print"]}
((:person.firstName ?person ?first)
(:person.lastName ?last))
((:person.country ?person ?country)))
;;-----------------if---------------------
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:person.workTel ?workTel))
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:if (:person.workTel ?person ?workTel)))
#_(q {:q-in [personDB] :q-out ["print"]}
[?first ?last]
(:person.lastName ?person ?last)
(:if (:person.nickName ?person ?first)))
#_(q {:q-in [personDB] :q-out ["print"]}
[?first ?last]
(:person.lastName ?person ?last)
(:if (:person.nickName ?person ?first))
(:if (:person.firstName ?person ?first)))
;;-----------:not-------------------------------
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:not (:person.workTel ?person ?workNum)))
;;-----------:add------------------------------
#_(def booksDB {
:y2000.title
[[2 "SPARQL Protocol Tutorial"]
[3 "SPARQL (updated)"]]
:y2010.title
[[1 "SPARQL Query Language Tutorial"]
[3 "SPARQL"]]
})
#_(q {:q-in [booksDB] :q-out ["print"]}
(:y2000.title ?book ?title00)
(:add (:y2010.title ?book ?title10))) | true | (ns documentation.binary-ops
(:use louna.louna
louna.louna-util))
#_(def personDB {
:person.firstName
[[1 "PI:NAME:<NAME>END_PI"]
[2"PI:NAME:<NAME>END_PI"]
[3 "PI:NAME:<NAME>END_PI"]]
:person.lastName
[[1 "PI:NAME:<NAME>END_PI"]
[2 "PI:NAME:<NAME>END_PI"]
[3 "PI:NAME:<NAME>END_PI"]]
:person.country
[[1 "GREECE"]
[2 "USA"]
[3 "SAUDI-ARABIA"]]
:person.workTel
[[3 "(245) 315-5486"]]
:person.nickName
[[1 "PI:NAME:<NAME>END_PI"]]
})
;;----------------and---------------------
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:person.country ?country))
#_(q {:q-in [personDB] :q-out ["print"]}
((:person.firstName ?person ?first)
(:person.lastName ?last))
(:and (:person.country ?person ?country)))
#_(q {:q-in [personDB] :q-out ["print"]}
((:person.firstName ?person ?first)
(:person.lastName ?last))
((:person.country ?person ?country)))
;;-----------------if---------------------
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:person.workTel ?workTel))
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:if (:person.workTel ?person ?workTel)))
#_(q {:q-in [personDB] :q-out ["print"]}
[?first ?last]
(:person.lastName ?person ?last)
(:if (:person.nickName ?person ?first)))
#_(q {:q-in [personDB] :q-out ["print"]}
[?first ?last]
(:person.lastName ?person ?last)
(:if (:person.nickName ?person ?first))
(:if (:person.firstName ?person ?first)))
;;-----------:not-------------------------------
#_(q {:q-in [personDB] :q-out ["print"]}
(:person.firstName ?person ?first)
(:person.lastName ?last)
(:not (:person.workTel ?person ?workNum)))
;;-----------:add------------------------------
#_(def booksDB {
:y2000.title
[[2 "SPARQL Protocol Tutorial"]
[3 "SPARQL (updated)"]]
:y2010.title
[[1 "SPARQL Query Language Tutorial"]
[3 "SPARQL"]]
})
#_(q {:q-in [booksDB] :q-out ["print"]}
(:y2000.title ?book ?title00)
(:add (:y2010.title ?book ?title10))) |
[
{
"context": "{:user\n {:signing {:gpg-key \"chad@deercreeklabs.com\"}\n :injections [(require 'pjstadig.humane-test-o",
"end": 51,
"score": 0.9997812509536743,
"start": 29,
"tag": "EMAIL",
"value": "chad@deercreeklabs.com"
},
{
"context": "ne-test-output/activate!)]\n\n :plugins\n [[com.jakemccrary/lein-test-refresh \"0.23.0\"]\n [lein-bikeshed ",
"end": 192,
"score": 0.5905898809432983,
"start": 187,
"tag": "USERNAME",
"value": "emccr"
},
{
"context": ".3.0\" :exclusions [fipp org.clojure/clojure]]\n [jonase/eastwood \"0.3.3\" :exclusions [org.clojure/clojure",
"end": 473,
"score": 0.9706919193267822,
"start": 467,
"tag": "USERNAME",
"value": "jonase"
}
] | profiles.clj | chadharrington/my-profiles-clj | 1 | {:user
{:signing {:gpg-key "chad@deercreeklabs.com"}
:injections [(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)]
:plugins
[[com.jakemccrary/lein-test-refresh "0.23.0"]
[lein-bikeshed "0.5.1"
:exclusions [org.clojure/clojure org.clojure/tools.cli]]
[lein-cljfmt "0.6.1"
:exclusions [org.clojure/clojure org.clojure/tools.reader]]
[lein-cprint "1.3.0" :exclusions [fipp org.clojure/clojure]]
[jonase/eastwood "0.3.3" :exclusions [org.clojure/clojure]]
[lein-kibit "0.1.6" :exclusions [org.clojure/clojure]]
[lein-try "0.4.3"]
[fipp "0.6.14"]]
:dependencies
[[org.clojure/tools.nrepl "0.2.13"]
[pjstadig/humane-test-output "0.9.0"]]
:test-refresh {:notify-command ["terminal-notifier"
"-title" "Tests" "-message"]}}
:repl
{:plugins [[cider/cider-nrepl "0.18.0"]]}}
| 81096 | {:user
{:signing {:gpg-key "<EMAIL>"}
:injections [(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)]
:plugins
[[com.jakemccrary/lein-test-refresh "0.23.0"]
[lein-bikeshed "0.5.1"
:exclusions [org.clojure/clojure org.clojure/tools.cli]]
[lein-cljfmt "0.6.1"
:exclusions [org.clojure/clojure org.clojure/tools.reader]]
[lein-cprint "1.3.0" :exclusions [fipp org.clojure/clojure]]
[jonase/eastwood "0.3.3" :exclusions [org.clojure/clojure]]
[lein-kibit "0.1.6" :exclusions [org.clojure/clojure]]
[lein-try "0.4.3"]
[fipp "0.6.14"]]
:dependencies
[[org.clojure/tools.nrepl "0.2.13"]
[pjstadig/humane-test-output "0.9.0"]]
:test-refresh {:notify-command ["terminal-notifier"
"-title" "Tests" "-message"]}}
:repl
{:plugins [[cider/cider-nrepl "0.18.0"]]}}
| true | {:user
{:signing {:gpg-key "PI:EMAIL:<EMAIL>END_PI"}
:injections [(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)]
:plugins
[[com.jakemccrary/lein-test-refresh "0.23.0"]
[lein-bikeshed "0.5.1"
:exclusions [org.clojure/clojure org.clojure/tools.cli]]
[lein-cljfmt "0.6.1"
:exclusions [org.clojure/clojure org.clojure/tools.reader]]
[lein-cprint "1.3.0" :exclusions [fipp org.clojure/clojure]]
[jonase/eastwood "0.3.3" :exclusions [org.clojure/clojure]]
[lein-kibit "0.1.6" :exclusions [org.clojure/clojure]]
[lein-try "0.4.3"]
[fipp "0.6.14"]]
:dependencies
[[org.clojure/tools.nrepl "0.2.13"]
[pjstadig/humane-test-output "0.9.0"]]
:test-refresh {:notify-command ["terminal-notifier"
"-title" "Tests" "-message"]}}
:repl
{:plugins [[cider/cider-nrepl "0.18.0"]]}}
|
[
{
"context": ";; Copyright (c) 2011,2012,2013 Walter Tetzner\n\n;; Permission is hereby granted, free of charge,",
"end": 46,
"score": 0.9998266696929932,
"start": 32,
"tag": "NAME",
"value": "Walter Tetzner"
}
] | src/org/bovinegenius/exploding_fish.clj | wtetzner/exploding-fish | 93 | ;; Copyright (c) 2011,2012,2013 Walter Tetzner
;; 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 org.bovinegenius.exploding-fish
(:require (org.bovinegenius.exploding-fish
[path :as path]
[query-string :as qs]
[parser :as parse]
[constructor :as build]))
(:import (java.net URI URL URLDecoder URLEncoder)))
(def ^:dynamic *default-encoding*
"Default encoding for query params."
(ref "UTF-8"))
(defn default-encoding
"Get the default encoding for query params."
[]
(if (string? *default-encoding*)
*default-encoding*
(deref *default-encoding*)))
(defmacro with-encoding
"Run body with the given encoding as the default-encoding."
[encoding & body]
`(binding [*default-encoding* ~encoding]
~@body))
(defprotocol UniformResourceIdentifier
"Protocol for dealing with URIs."
(scheme
[self] [self new-scheme]
"Get or set the scheme component of the URI.")
(scheme-relative
[self] [self new-scheme-relative]
"Get or set the scheme specific part of the URI.")
(authority
[self] [self new-authority]
"Get or set the authority of the URI.")
(user-info
[self] [self new-user-info]
"Get or set the user-info of the URI.")
(host
[self] [self new-host]
"Get or set the host of the URI.")
(port
[self] [self new-port]
"Get or set the port of the URI.")
(path
[self] [self new-path]
"Get or set the path of the URI.")
(query
[self] [self new-query]
"Get or set the query string of the URI.")
(fragment
[self] [self new-fragment]
"Get or set the fragment of the URI."))
(def ^{:dynamic true, :private true}
*uri-keys* #{:scheme :scheme-relative :authority
:user-info :host :port :path :query
:fragment})
(deftype Uri [data metadata]
UniformResourceIdentifier
(scheme [self] (:scheme data))
(scheme [self new-scheme] (-> (assoc data :scheme new-scheme)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata)))
(scheme-relative [self] (:scheme-relative data))
(scheme-relative [self ssp]
(let [new-data (assoc data :scheme-relative ssp)
ssp-data (parse/scheme-specific ssp)
auth-data (parse/authority (:authority ssp-data))]
(-> (merge new-data ssp-data auth-data)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(authority [self] (:authority data))
(authority [self authority]
(let [new-data (assoc data :authority authority)
auth-data (parse/authority authority)]
(-> (merge new-data auth-data)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(user-info [self] (:user-info data))
(user-info [self user-info]
(let [new-data (assoc data :user-info user-info)
authority (build/authority new-data)
new-data (assoc new-data :authority authority)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(host [self] (:host self))
(host [self host]
(let [new-data (assoc data :host host)
authority (build/authority new-data)
new-data (assoc new-data :authority authority)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(port [self] (:port self))
(port [self port]
(let [new-data (if (and port (>= port 0))
(assoc data :port port)
(dissoc data :port))
authority (build/authority new-data)
new-data (assoc new-data :authority authority)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(path [self] (:path self))
(path [self path]
(let [new-data (assoc data :path path)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(query [self] (:query self))
(query [self query]
(let [new-data (assoc data :query query)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(fragment [self] (:fragment self))
(fragment [self fragment]
(-> (assoc data :fragment fragment)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata)))
clojure.lang.Associative
(containsKey [self key] (contains? data key))
(assoc [self key value]
(condp = key
:scheme (scheme self value)
:scheme-relative (scheme-relative self value)
:authority (authority self value)
:user-info (user-info self value)
:host (host self value)
:port (port self value)
:path (path self value)
:query (query self value)
:fragment (fragment self value)
(Uri. (parse/clean-map (build/prepare-map (assoc data key value)) *uri-keys*) metadata)))
(entryAt [_ key] (find data key))
clojure.lang.ILookup
(valAt [self key] (get data key))
(valAt [self key value] (get data key value))
clojure.lang.Seqable
(seq [self] (seq data))
clojure.lang.IPersistentMap
(without [self key]
(condp = key
:scheme (scheme self nil)
:scheme-relative (scheme-relative self nil)
:authority (authority self nil)
:user-info (user-info self nil)
:host (host self nil)
:port (port self nil)
:path (path self nil)
:query (query self nil)
:fragment (fragment self nil)
(Uri. (parse/clean-map (build/prepare-map (dissoc data key)) *uri-keys*) metadata)))
Iterable
(iterator [_] (.iterator ^Iterable data))
clojure.lang.IFn
(invoke [self key]
(get self key))
(invoke [self key value]
(get self key value))
Object
(toString [self] (build/uri-string data))
(equals [self other]
(if (and (instance? (class self) other)
(= (into {} other) data))
true
false))
(hashCode [self]
(int (/ (+ (Integer. (.hashCode data))
(Integer. (.hashCode (str self)))) 2)))
java.io.Serializable
java.util.Map
(size [self] (count self))
(isEmpty [self] (= 0 (count self)))
(containsValue [self value] (boolean (some #{value} (vals self))))
(get [self key] (.valAt self key))
(put [_ _ _] (throw (UnsupportedOperationException.)))
(remove [_ _] (throw (UnsupportedOperationException.)))
(putAll [_ _] (throw (UnsupportedOperationException.)))
(clear [_] (throw (UnsupportedOperationException.)))
(keySet [self] (set (keys self)))
(values [self] (vals self))
(entrySet [self] (set self))
clojure.lang.IPersistentCollection
(count [_] (count data))
(empty [_] (Uri. {} metadata))
(cons [self o]
(cond (instance? java.util.Map$Entry o) (assoc self (key o) (val o))
(vector? o) (assoc self (nth o 0) (nth o 1))
:else (reduce conj self o)))
(equiv [self other] (.equals self other))
clojure.lang.IObj
(withMeta [self mdata] (Uri. data mdata))
clojure.lang.IMeta
(meta [self] metadata))
(defmethod print-method Uri [obj writer]
(.write ^java.io.Writer writer (format "#<Uri %s>"
(str obj))))
(defn uri
"Builds a Uri object. Takes a map of URI keys, a URI string, or
another Uri object."
[uri]
(condp instance? uri
Uri uri
clojure.lang.IPersistentMap (Uri. (parse/clean-map (build/prepare-map uri) *uri-keys*) (meta uri))
java.lang.String (Uri. (parse/clean-map (build/prepare-map (parse/uri uri)) *uri-keys*) nil)
(Uri. (-> uri str str parse/uri build/prepare-map (parse/clean-map *uri-keys*)) nil)))
(extend java.net.URI
UniformResourceIdentifier
{:scheme (fn ([^URI self] (-> self uri scheme))
([^URI self ^String new-scheme]
(-> self uri (scheme new-scheme) str URI.)))
:scheme-relative (fn ([^URI self]
(-> self uri scheme-relative))
([^URI self ^String ssp]
(-> self uri
(scheme-relative ssp) str URI.)))
:authority (fn ([^URI self] (-> self uri authority))
([^URI self ^String new-authority]
(-> self uri (authority new-authority) str URI.)))
:user-info (fn ([^URI self] (-> self uri user-info))
([^URI self ^String new-user-info]
(-> self uri (user-info new-user-info) str URI.)))
:host (fn ([^URI self] (-> self uri host))
([^URI self ^String new-host]
(-> self uri (host new-host) str URI.)))
:port (fn ([^URI self] (let [port (-> self uri port)]
(if (= port -1) nil port)))
([^URI self ^Integer new-port]
(-> self uri (port new-port) str URI.)))
:path (fn ([^URI self] (-> self uri path))
([^URI self ^String new-path]
(-> self uri (path new-path) str URI.)))
:query (fn ([^URI self] (-> self uri query))
([^URI self ^String new-query]
(-> self uri (query new-query) str URI.)))
:fragment (fn ([^URI self] (-> self uri fragment))
([^URI self ^String new-fragment]
(-> self uri (fragment new-fragment) str URI.)))})
(extend String
UniformResourceIdentifier
{:scheme (fn ([^String self] (-> self uri scheme))
([^String self ^String new-scheme]
(-> self uri (scheme new-scheme) str str)))
:scheme-relative (fn ([^String self]
(-> self uri scheme-relative))
([^String self ^String ssp]
(-> self uri
(scheme-relative ssp) str str)))
:authority (fn ([^String self] (-> self uri authority))
([^String self ^String new-authority]
(-> self uri (authority new-authority) str str)))
:user-info (fn ([^String self] (-> self uri user-info))
([^String self ^String new-user-info]
(-> self uri (user-info new-user-info) str str)))
:host (fn ([^String self] (-> self uri host))
([^String self ^String new-host]
(-> self uri (host new-host) str str)))
:port (fn ([^String self] (-> self uri port))
([^String self ^Integer new-port]
(-> self uri (port new-port) str str)))
:path (fn ([^String self] (-> self uri path))
([^String self ^String new-path]
(-> self uri (path new-path) str str)))
:query (fn ([^String self] (-> self uri query))
([^String self ^String new-query]
(-> self uri (query new-query) str str)))
:fragment (fn ([^String self] (-> self uri fragment))
([^String self ^String new-fragment]
(-> self uri (fragment new-fragment) str str)))})
(extend java.net.URL
UniformResourceIdentifier
{:scheme (fn ([^URL self] (-> self uri scheme))
([^URL self ^String new-scheme]
(-> self uri (scheme new-scheme) str URL.)))
:scheme-relative (fn ([^URL self]
(-> self uri scheme-relative))
([^URL self ^String ssp]
(-> self uri
(scheme-relative ssp) str URL.)))
:authority (fn ([^URL self] (-> self uri authority))
([^URL self ^String new-authority]
(-> self uri (authority new-authority) str URL.)))
:user-info (fn ([^URL self] (-> self uri user-info))
([^URL self ^String new-user-info]
(-> self uri (user-info new-user-info) str URL.)))
:host (fn ([^URL self] (-> self uri host))
([^URL self ^String new-host]
(-> self uri (host new-host) str URL.)))
:port (fn ([^URL self] (-> self uri port))
([^URL self ^Integer new-port]
(-> self uri (port new-port) str URL.)))
:path (fn ([^URL self] (-> self uri path))
([^URL self ^String new-path]
(-> self uri (path new-path) str URL.)))
:query (fn ([^URL self] (-> self uri query))
([^URL self ^String new-query]
(-> self uri (query new-query) str URL.)))
:fragment (fn ([^URL self] (-> self uri fragment))
([^URL self ^String new-fragment]
(-> self uri (fragment new-fragment) str URL.)))})
(defn uri->map
"Convert a java.net.URI into a hash-map."
[^URI uri]
(->> {:scheme (scheme uri)
:scheme-relative (scheme-relative uri)
:authority (authority uri)
:user-info (user-info uri)
:host (host uri)
:port (port uri)
:path (path uri)
:query (query uri)
:fragment (fragment uri)}
(filter val)
(into {})))
(defn ^URI map->uri
"Convert a hash-map into a java.net.URI."
[uri]
(cond (-> (:scheme-relative uri) empty? not)
(URI. (:scheme uri) (:scheme-relative uri)
(:fragment uri))
(:user-info uri)
(URI. (:scheme uri) (:user-info uri)
(:host uri) (or (:port uri) -1)
(:path uri) (:query uri)
(:fragment uri))
(:host uri)
(URI. (:scheme uri) (:host uri) (:path uri)
(:fragment uri))
:else (URI. (:scheme uri) (:authority uri)
(:path uri) (:query uri)
(:fragment uri))))
(defn string->map
"Convert a URI in string form to a map."
[^String string]
(-> string URI. uri->map))
(defn ^String map->string
"Convert a URI in map form to a string."
[uri]
(-> uri map->uri str str))
(defn query-list
"Returns a list from the query string of the given URI."
[uri]
(-> uri query qs/query-string->list))
(defn raw-pairs
"Returns an alist of the query params matching the given key. If no
key is given, an alist of all the query params is returned."
([uri key]
(->> uri qs/query-string->alist
(filter (fn [[param-key value]]
(= param-key key)))
vec))
([uri]
(-> uri query qs/query-string->alist)))
(defn- encode-param
"Encode a query key or param. If the value is nil, just return nil."
[text]
(if (string? text)
(URLEncoder/encode text (default-encoding))
text))
(defn- decode-param
"Decode a query key or param. If the value is nil, just return nil."
[text]
(if (string? text)
(URLDecoder/decode text (default-encoding))
text))
(defn query-pairs
"Returns an alist of the query params matching the given key. If no
key is given, an alist of all the query params is returned. The keys
and values of the pairs are URL decoded."
([uri key]
(->> uri raw-pairs
(map (fn [[key val]]
[(decode-param key) (decode-param val)]))
(filter (fn [[param-key value]]
(= param-key key)))
vec))
([uri]
(->> uri raw-pairs
(map (fn [[key val]]
[(decode-param key) (decode-param val)]))
vec)))
(defn params-raw
"Returns an alist of the query values whose key matches the given
key. If no key is given, all values are returned."
([uri key]
(->> uri raw-pairs
(filter (fn [[param-key value]]
(= param-key key)))
(map second)
vec))
([uri]
(->> uri raw-pairs (map second) vec)))
(defn params
"Returns an alist of the query values whose key matches the given
key. If no key is given, all values are returned."
([uri key]
(->> uri query-pairs
(filter (fn [[param-key value]]
(= param-key key)))
(map second)
vec))
([uri]
(->> uri query-pairs (map second) vec)))
(defn param-raw
"Get the last param value that matches the given key. If 3 args are
given, set the first param value that matches the given key, and
remove the remaining params that match the given key. If 4 args are
given, set the nth param value that matches the given key."
([uri key]
(-> uri (params-raw key) last))
([uri key value]
(query uri (-> uri raw-pairs
(qs/alist-replace key value)
qs/alist->query-string)))
([uri key value index]
(query uri (-> uri raw-pairs
(qs/alist-replace key value index)
qs/alist->query-string))))
(defn param
"Get the last param value that matches the given key. If 3 args are
given, set the first param value that matches the given key, and
remove the remaining params that match the given key. If 4 args are
given, set the nth param value that matches the given key."
([uri key]
(-> uri (params key) last))
([uri key value]
(query uri (->> (qs/alist-replace (query-pairs uri) key value)
(map (fn [[key val]]
[(encode-param key) (encode-param val)]))
qs/alist->query-string)))
([uri key value index]
(query uri (->> (qs/alist-replace (query-pairs uri) key value index)
(map (fn [[key val]]
[(encode-param key) (encode-param val)]))
qs/alist->query-string))))
(defn query-map
"Returns a map of the query string parameters for the given URI."
([uri]
(->> uri query-pairs (into {})))
([uri param-map]
(let [keywords-to-strings (fn [[k v]] [(name k) v])
query-params (->> (map keywords-to-strings param-map) (into {}))
add-param (fn [url [key val]] (param url key val))]
(reduce add-param uri query-params))))
(defn raw-keys
"Returns a list of the query string keys of the given URI."
[uri]
(->> uri raw-pairs (map first) vec))
(defn query-keys
"Returns a list of the query string keys of the given URI."
[uri]
(->> uri query-pairs (map first) vec))
(defn normalize-path
"Normalize the path of the given uri."
[uri]
(->> (path uri) path/normalize (path uri)))
(defn- as-path
"Ensure path"
[p]
(path (uri p)))
(defn resolve-path
"Resolve the given path against the given uri."
[the-uri the-path]
(let [current-path (or (path the-uri) "/")]
(path the-uri
(-> current-path (path/resolve-path (as-path the-path))))))
(defn absolute-path?
"Returns true if the given uri path is absolute."
[uri]
(-> uri path path/absolute?))
(defn absolute?
"Returns true if the given URI is absolute."
[uri]
(boolean (authority uri)))
(defn resolve-uri
"Resolves a target uri from a source uri.
Essentially this is an implementation of:
-> RFC 2396
-> RFC 1808
This implementation and the associated tests based on
this document: http://www.ics.uci.edu/~fielding/url/test2.html"
[src-uri target-uri]
(let [target-uri-query (query target-uri)
target-uri-fragment (fragment target-uri)]
;; need to handle this case separately:
;; resolve-uri "http://a/b/c" "//c"
;; since path is nil, the resolve fails
(cond
(re-find #"^//" (str target-uri))
(scheme target-uri
(scheme src-uri))
(absolute? target-uri) ; this is the second condition we match
target-uri ; against since (absolute? //a/b) => #t
; and we want (resolve-uri "http:/a/b"
; "http://c/d") to resolve to the target
; URI itself
:else
(-> src-uri
(resolve-path target-uri)
(query target-uri-query)
(fragment target-uri-fragment)))))
| 31833 | ;; Copyright (c) 2011,2012,2013 <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 org.bovinegenius.exploding-fish
(:require (org.bovinegenius.exploding-fish
[path :as path]
[query-string :as qs]
[parser :as parse]
[constructor :as build]))
(:import (java.net URI URL URLDecoder URLEncoder)))
(def ^:dynamic *default-encoding*
"Default encoding for query params."
(ref "UTF-8"))
(defn default-encoding
"Get the default encoding for query params."
[]
(if (string? *default-encoding*)
*default-encoding*
(deref *default-encoding*)))
(defmacro with-encoding
"Run body with the given encoding as the default-encoding."
[encoding & body]
`(binding [*default-encoding* ~encoding]
~@body))
(defprotocol UniformResourceIdentifier
"Protocol for dealing with URIs."
(scheme
[self] [self new-scheme]
"Get or set the scheme component of the URI.")
(scheme-relative
[self] [self new-scheme-relative]
"Get or set the scheme specific part of the URI.")
(authority
[self] [self new-authority]
"Get or set the authority of the URI.")
(user-info
[self] [self new-user-info]
"Get or set the user-info of the URI.")
(host
[self] [self new-host]
"Get or set the host of the URI.")
(port
[self] [self new-port]
"Get or set the port of the URI.")
(path
[self] [self new-path]
"Get or set the path of the URI.")
(query
[self] [self new-query]
"Get or set the query string of the URI.")
(fragment
[self] [self new-fragment]
"Get or set the fragment of the URI."))
(def ^{:dynamic true, :private true}
*uri-keys* #{:scheme :scheme-relative :authority
:user-info :host :port :path :query
:fragment})
(deftype Uri [data metadata]
UniformResourceIdentifier
(scheme [self] (:scheme data))
(scheme [self new-scheme] (-> (assoc data :scheme new-scheme)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata)))
(scheme-relative [self] (:scheme-relative data))
(scheme-relative [self ssp]
(let [new-data (assoc data :scheme-relative ssp)
ssp-data (parse/scheme-specific ssp)
auth-data (parse/authority (:authority ssp-data))]
(-> (merge new-data ssp-data auth-data)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(authority [self] (:authority data))
(authority [self authority]
(let [new-data (assoc data :authority authority)
auth-data (parse/authority authority)]
(-> (merge new-data auth-data)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(user-info [self] (:user-info data))
(user-info [self user-info]
(let [new-data (assoc data :user-info user-info)
authority (build/authority new-data)
new-data (assoc new-data :authority authority)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(host [self] (:host self))
(host [self host]
(let [new-data (assoc data :host host)
authority (build/authority new-data)
new-data (assoc new-data :authority authority)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(port [self] (:port self))
(port [self port]
(let [new-data (if (and port (>= port 0))
(assoc data :port port)
(dissoc data :port))
authority (build/authority new-data)
new-data (assoc new-data :authority authority)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(path [self] (:path self))
(path [self path]
(let [new-data (assoc data :path path)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(query [self] (:query self))
(query [self query]
(let [new-data (assoc data :query query)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(fragment [self] (:fragment self))
(fragment [self fragment]
(-> (assoc data :fragment fragment)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata)))
clojure.lang.Associative
(containsKey [self key] (contains? data key))
(assoc [self key value]
(condp = key
:scheme (scheme self value)
:scheme-relative (scheme-relative self value)
:authority (authority self value)
:user-info (user-info self value)
:host (host self value)
:port (port self value)
:path (path self value)
:query (query self value)
:fragment (fragment self value)
(Uri. (parse/clean-map (build/prepare-map (assoc data key value)) *uri-keys*) metadata)))
(entryAt [_ key] (find data key))
clojure.lang.ILookup
(valAt [self key] (get data key))
(valAt [self key value] (get data key value))
clojure.lang.Seqable
(seq [self] (seq data))
clojure.lang.IPersistentMap
(without [self key]
(condp = key
:scheme (scheme self nil)
:scheme-relative (scheme-relative self nil)
:authority (authority self nil)
:user-info (user-info self nil)
:host (host self nil)
:port (port self nil)
:path (path self nil)
:query (query self nil)
:fragment (fragment self nil)
(Uri. (parse/clean-map (build/prepare-map (dissoc data key)) *uri-keys*) metadata)))
Iterable
(iterator [_] (.iterator ^Iterable data))
clojure.lang.IFn
(invoke [self key]
(get self key))
(invoke [self key value]
(get self key value))
Object
(toString [self] (build/uri-string data))
(equals [self other]
(if (and (instance? (class self) other)
(= (into {} other) data))
true
false))
(hashCode [self]
(int (/ (+ (Integer. (.hashCode data))
(Integer. (.hashCode (str self)))) 2)))
java.io.Serializable
java.util.Map
(size [self] (count self))
(isEmpty [self] (= 0 (count self)))
(containsValue [self value] (boolean (some #{value} (vals self))))
(get [self key] (.valAt self key))
(put [_ _ _] (throw (UnsupportedOperationException.)))
(remove [_ _] (throw (UnsupportedOperationException.)))
(putAll [_ _] (throw (UnsupportedOperationException.)))
(clear [_] (throw (UnsupportedOperationException.)))
(keySet [self] (set (keys self)))
(values [self] (vals self))
(entrySet [self] (set self))
clojure.lang.IPersistentCollection
(count [_] (count data))
(empty [_] (Uri. {} metadata))
(cons [self o]
(cond (instance? java.util.Map$Entry o) (assoc self (key o) (val o))
(vector? o) (assoc self (nth o 0) (nth o 1))
:else (reduce conj self o)))
(equiv [self other] (.equals self other))
clojure.lang.IObj
(withMeta [self mdata] (Uri. data mdata))
clojure.lang.IMeta
(meta [self] metadata))
(defmethod print-method Uri [obj writer]
(.write ^java.io.Writer writer (format "#<Uri %s>"
(str obj))))
(defn uri
"Builds a Uri object. Takes a map of URI keys, a URI string, or
another Uri object."
[uri]
(condp instance? uri
Uri uri
clojure.lang.IPersistentMap (Uri. (parse/clean-map (build/prepare-map uri) *uri-keys*) (meta uri))
java.lang.String (Uri. (parse/clean-map (build/prepare-map (parse/uri uri)) *uri-keys*) nil)
(Uri. (-> uri str str parse/uri build/prepare-map (parse/clean-map *uri-keys*)) nil)))
(extend java.net.URI
UniformResourceIdentifier
{:scheme (fn ([^URI self] (-> self uri scheme))
([^URI self ^String new-scheme]
(-> self uri (scheme new-scheme) str URI.)))
:scheme-relative (fn ([^URI self]
(-> self uri scheme-relative))
([^URI self ^String ssp]
(-> self uri
(scheme-relative ssp) str URI.)))
:authority (fn ([^URI self] (-> self uri authority))
([^URI self ^String new-authority]
(-> self uri (authority new-authority) str URI.)))
:user-info (fn ([^URI self] (-> self uri user-info))
([^URI self ^String new-user-info]
(-> self uri (user-info new-user-info) str URI.)))
:host (fn ([^URI self] (-> self uri host))
([^URI self ^String new-host]
(-> self uri (host new-host) str URI.)))
:port (fn ([^URI self] (let [port (-> self uri port)]
(if (= port -1) nil port)))
([^URI self ^Integer new-port]
(-> self uri (port new-port) str URI.)))
:path (fn ([^URI self] (-> self uri path))
([^URI self ^String new-path]
(-> self uri (path new-path) str URI.)))
:query (fn ([^URI self] (-> self uri query))
([^URI self ^String new-query]
(-> self uri (query new-query) str URI.)))
:fragment (fn ([^URI self] (-> self uri fragment))
([^URI self ^String new-fragment]
(-> self uri (fragment new-fragment) str URI.)))})
(extend String
UniformResourceIdentifier
{:scheme (fn ([^String self] (-> self uri scheme))
([^String self ^String new-scheme]
(-> self uri (scheme new-scheme) str str)))
:scheme-relative (fn ([^String self]
(-> self uri scheme-relative))
([^String self ^String ssp]
(-> self uri
(scheme-relative ssp) str str)))
:authority (fn ([^String self] (-> self uri authority))
([^String self ^String new-authority]
(-> self uri (authority new-authority) str str)))
:user-info (fn ([^String self] (-> self uri user-info))
([^String self ^String new-user-info]
(-> self uri (user-info new-user-info) str str)))
:host (fn ([^String self] (-> self uri host))
([^String self ^String new-host]
(-> self uri (host new-host) str str)))
:port (fn ([^String self] (-> self uri port))
([^String self ^Integer new-port]
(-> self uri (port new-port) str str)))
:path (fn ([^String self] (-> self uri path))
([^String self ^String new-path]
(-> self uri (path new-path) str str)))
:query (fn ([^String self] (-> self uri query))
([^String self ^String new-query]
(-> self uri (query new-query) str str)))
:fragment (fn ([^String self] (-> self uri fragment))
([^String self ^String new-fragment]
(-> self uri (fragment new-fragment) str str)))})
(extend java.net.URL
UniformResourceIdentifier
{:scheme (fn ([^URL self] (-> self uri scheme))
([^URL self ^String new-scheme]
(-> self uri (scheme new-scheme) str URL.)))
:scheme-relative (fn ([^URL self]
(-> self uri scheme-relative))
([^URL self ^String ssp]
(-> self uri
(scheme-relative ssp) str URL.)))
:authority (fn ([^URL self] (-> self uri authority))
([^URL self ^String new-authority]
(-> self uri (authority new-authority) str URL.)))
:user-info (fn ([^URL self] (-> self uri user-info))
([^URL self ^String new-user-info]
(-> self uri (user-info new-user-info) str URL.)))
:host (fn ([^URL self] (-> self uri host))
([^URL self ^String new-host]
(-> self uri (host new-host) str URL.)))
:port (fn ([^URL self] (-> self uri port))
([^URL self ^Integer new-port]
(-> self uri (port new-port) str URL.)))
:path (fn ([^URL self] (-> self uri path))
([^URL self ^String new-path]
(-> self uri (path new-path) str URL.)))
:query (fn ([^URL self] (-> self uri query))
([^URL self ^String new-query]
(-> self uri (query new-query) str URL.)))
:fragment (fn ([^URL self] (-> self uri fragment))
([^URL self ^String new-fragment]
(-> self uri (fragment new-fragment) str URL.)))})
(defn uri->map
"Convert a java.net.URI into a hash-map."
[^URI uri]
(->> {:scheme (scheme uri)
:scheme-relative (scheme-relative uri)
:authority (authority uri)
:user-info (user-info uri)
:host (host uri)
:port (port uri)
:path (path uri)
:query (query uri)
:fragment (fragment uri)}
(filter val)
(into {})))
(defn ^URI map->uri
"Convert a hash-map into a java.net.URI."
[uri]
(cond (-> (:scheme-relative uri) empty? not)
(URI. (:scheme uri) (:scheme-relative uri)
(:fragment uri))
(:user-info uri)
(URI. (:scheme uri) (:user-info uri)
(:host uri) (or (:port uri) -1)
(:path uri) (:query uri)
(:fragment uri))
(:host uri)
(URI. (:scheme uri) (:host uri) (:path uri)
(:fragment uri))
:else (URI. (:scheme uri) (:authority uri)
(:path uri) (:query uri)
(:fragment uri))))
(defn string->map
"Convert a URI in string form to a map."
[^String string]
(-> string URI. uri->map))
(defn ^String map->string
"Convert a URI in map form to a string."
[uri]
(-> uri map->uri str str))
(defn query-list
"Returns a list from the query string of the given URI."
[uri]
(-> uri query qs/query-string->list))
(defn raw-pairs
"Returns an alist of the query params matching the given key. If no
key is given, an alist of all the query params is returned."
([uri key]
(->> uri qs/query-string->alist
(filter (fn [[param-key value]]
(= param-key key)))
vec))
([uri]
(-> uri query qs/query-string->alist)))
(defn- encode-param
"Encode a query key or param. If the value is nil, just return nil."
[text]
(if (string? text)
(URLEncoder/encode text (default-encoding))
text))
(defn- decode-param
"Decode a query key or param. If the value is nil, just return nil."
[text]
(if (string? text)
(URLDecoder/decode text (default-encoding))
text))
(defn query-pairs
"Returns an alist of the query params matching the given key. If no
key is given, an alist of all the query params is returned. The keys
and values of the pairs are URL decoded."
([uri key]
(->> uri raw-pairs
(map (fn [[key val]]
[(decode-param key) (decode-param val)]))
(filter (fn [[param-key value]]
(= param-key key)))
vec))
([uri]
(->> uri raw-pairs
(map (fn [[key val]]
[(decode-param key) (decode-param val)]))
vec)))
(defn params-raw
"Returns an alist of the query values whose key matches the given
key. If no key is given, all values are returned."
([uri key]
(->> uri raw-pairs
(filter (fn [[param-key value]]
(= param-key key)))
(map second)
vec))
([uri]
(->> uri raw-pairs (map second) vec)))
(defn params
"Returns an alist of the query values whose key matches the given
key. If no key is given, all values are returned."
([uri key]
(->> uri query-pairs
(filter (fn [[param-key value]]
(= param-key key)))
(map second)
vec))
([uri]
(->> uri query-pairs (map second) vec)))
(defn param-raw
"Get the last param value that matches the given key. If 3 args are
given, set the first param value that matches the given key, and
remove the remaining params that match the given key. If 4 args are
given, set the nth param value that matches the given key."
([uri key]
(-> uri (params-raw key) last))
([uri key value]
(query uri (-> uri raw-pairs
(qs/alist-replace key value)
qs/alist->query-string)))
([uri key value index]
(query uri (-> uri raw-pairs
(qs/alist-replace key value index)
qs/alist->query-string))))
(defn param
"Get the last param value that matches the given key. If 3 args are
given, set the first param value that matches the given key, and
remove the remaining params that match the given key. If 4 args are
given, set the nth param value that matches the given key."
([uri key]
(-> uri (params key) last))
([uri key value]
(query uri (->> (qs/alist-replace (query-pairs uri) key value)
(map (fn [[key val]]
[(encode-param key) (encode-param val)]))
qs/alist->query-string)))
([uri key value index]
(query uri (->> (qs/alist-replace (query-pairs uri) key value index)
(map (fn [[key val]]
[(encode-param key) (encode-param val)]))
qs/alist->query-string))))
(defn query-map
"Returns a map of the query string parameters for the given URI."
([uri]
(->> uri query-pairs (into {})))
([uri param-map]
(let [keywords-to-strings (fn [[k v]] [(name k) v])
query-params (->> (map keywords-to-strings param-map) (into {}))
add-param (fn [url [key val]] (param url key val))]
(reduce add-param uri query-params))))
(defn raw-keys
"Returns a list of the query string keys of the given URI."
[uri]
(->> uri raw-pairs (map first) vec))
(defn query-keys
"Returns a list of the query string keys of the given URI."
[uri]
(->> uri query-pairs (map first) vec))
(defn normalize-path
"Normalize the path of the given uri."
[uri]
(->> (path uri) path/normalize (path uri)))
(defn- as-path
"Ensure path"
[p]
(path (uri p)))
(defn resolve-path
"Resolve the given path against the given uri."
[the-uri the-path]
(let [current-path (or (path the-uri) "/")]
(path the-uri
(-> current-path (path/resolve-path (as-path the-path))))))
(defn absolute-path?
"Returns true if the given uri path is absolute."
[uri]
(-> uri path path/absolute?))
(defn absolute?
"Returns true if the given URI is absolute."
[uri]
(boolean (authority uri)))
(defn resolve-uri
"Resolves a target uri from a source uri.
Essentially this is an implementation of:
-> RFC 2396
-> RFC 1808
This implementation and the associated tests based on
this document: http://www.ics.uci.edu/~fielding/url/test2.html"
[src-uri target-uri]
(let [target-uri-query (query target-uri)
target-uri-fragment (fragment target-uri)]
;; need to handle this case separately:
;; resolve-uri "http://a/b/c" "//c"
;; since path is nil, the resolve fails
(cond
(re-find #"^//" (str target-uri))
(scheme target-uri
(scheme src-uri))
(absolute? target-uri) ; this is the second condition we match
target-uri ; against since (absolute? //a/b) => #t
; and we want (resolve-uri "http:/a/b"
; "http://c/d") to resolve to the target
; URI itself
:else
(-> src-uri
(resolve-path target-uri)
(query target-uri-query)
(fragment target-uri-fragment)))))
| true | ;; Copyright (c) 2011,2012,2013 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 org.bovinegenius.exploding-fish
(:require (org.bovinegenius.exploding-fish
[path :as path]
[query-string :as qs]
[parser :as parse]
[constructor :as build]))
(:import (java.net URI URL URLDecoder URLEncoder)))
(def ^:dynamic *default-encoding*
"Default encoding for query params."
(ref "UTF-8"))
(defn default-encoding
"Get the default encoding for query params."
[]
(if (string? *default-encoding*)
*default-encoding*
(deref *default-encoding*)))
(defmacro with-encoding
"Run body with the given encoding as the default-encoding."
[encoding & body]
`(binding [*default-encoding* ~encoding]
~@body))
(defprotocol UniformResourceIdentifier
"Protocol for dealing with URIs."
(scheme
[self] [self new-scheme]
"Get or set the scheme component of the URI.")
(scheme-relative
[self] [self new-scheme-relative]
"Get or set the scheme specific part of the URI.")
(authority
[self] [self new-authority]
"Get or set the authority of the URI.")
(user-info
[self] [self new-user-info]
"Get or set the user-info of the URI.")
(host
[self] [self new-host]
"Get or set the host of the URI.")
(port
[self] [self new-port]
"Get or set the port of the URI.")
(path
[self] [self new-path]
"Get or set the path of the URI.")
(query
[self] [self new-query]
"Get or set the query string of the URI.")
(fragment
[self] [self new-fragment]
"Get or set the fragment of the URI."))
(def ^{:dynamic true, :private true}
*uri-keys* #{:scheme :scheme-relative :authority
:user-info :host :port :path :query
:fragment})
(deftype Uri [data metadata]
UniformResourceIdentifier
(scheme [self] (:scheme data))
(scheme [self new-scheme] (-> (assoc data :scheme new-scheme)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata)))
(scheme-relative [self] (:scheme-relative data))
(scheme-relative [self ssp]
(let [new-data (assoc data :scheme-relative ssp)
ssp-data (parse/scheme-specific ssp)
auth-data (parse/authority (:authority ssp-data))]
(-> (merge new-data ssp-data auth-data)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(authority [self] (:authority data))
(authority [self authority]
(let [new-data (assoc data :authority authority)
auth-data (parse/authority authority)]
(-> (merge new-data auth-data)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(user-info [self] (:user-info data))
(user-info [self user-info]
(let [new-data (assoc data :user-info user-info)
authority (build/authority new-data)
new-data (assoc new-data :authority authority)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(host [self] (:host self))
(host [self host]
(let [new-data (assoc data :host host)
authority (build/authority new-data)
new-data (assoc new-data :authority authority)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(port [self] (:port self))
(port [self port]
(let [new-data (if (and port (>= port 0))
(assoc data :port port)
(dissoc data :port))
authority (build/authority new-data)
new-data (assoc new-data :authority authority)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(path [self] (:path self))
(path [self path]
(let [new-data (assoc data :path path)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(query [self] (:query self))
(query [self query]
(let [new-data (assoc data :query query)
ssp (build/scheme-specific new-data)
new-data (assoc new-data :scheme-relative ssp)]
(-> new-data
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata))))
(fragment [self] (:fragment self))
(fragment [self fragment]
(-> (assoc data :fragment fragment)
(build/prepare-map)
(parse/clean-map *uri-keys*)
(Uri. metadata)))
clojure.lang.Associative
(containsKey [self key] (contains? data key))
(assoc [self key value]
(condp = key
:scheme (scheme self value)
:scheme-relative (scheme-relative self value)
:authority (authority self value)
:user-info (user-info self value)
:host (host self value)
:port (port self value)
:path (path self value)
:query (query self value)
:fragment (fragment self value)
(Uri. (parse/clean-map (build/prepare-map (assoc data key value)) *uri-keys*) metadata)))
(entryAt [_ key] (find data key))
clojure.lang.ILookup
(valAt [self key] (get data key))
(valAt [self key value] (get data key value))
clojure.lang.Seqable
(seq [self] (seq data))
clojure.lang.IPersistentMap
(without [self key]
(condp = key
:scheme (scheme self nil)
:scheme-relative (scheme-relative self nil)
:authority (authority self nil)
:user-info (user-info self nil)
:host (host self nil)
:port (port self nil)
:path (path self nil)
:query (query self nil)
:fragment (fragment self nil)
(Uri. (parse/clean-map (build/prepare-map (dissoc data key)) *uri-keys*) metadata)))
Iterable
(iterator [_] (.iterator ^Iterable data))
clojure.lang.IFn
(invoke [self key]
(get self key))
(invoke [self key value]
(get self key value))
Object
(toString [self] (build/uri-string data))
(equals [self other]
(if (and (instance? (class self) other)
(= (into {} other) data))
true
false))
(hashCode [self]
(int (/ (+ (Integer. (.hashCode data))
(Integer. (.hashCode (str self)))) 2)))
java.io.Serializable
java.util.Map
(size [self] (count self))
(isEmpty [self] (= 0 (count self)))
(containsValue [self value] (boolean (some #{value} (vals self))))
(get [self key] (.valAt self key))
(put [_ _ _] (throw (UnsupportedOperationException.)))
(remove [_ _] (throw (UnsupportedOperationException.)))
(putAll [_ _] (throw (UnsupportedOperationException.)))
(clear [_] (throw (UnsupportedOperationException.)))
(keySet [self] (set (keys self)))
(values [self] (vals self))
(entrySet [self] (set self))
clojure.lang.IPersistentCollection
(count [_] (count data))
(empty [_] (Uri. {} metadata))
(cons [self o]
(cond (instance? java.util.Map$Entry o) (assoc self (key o) (val o))
(vector? o) (assoc self (nth o 0) (nth o 1))
:else (reduce conj self o)))
(equiv [self other] (.equals self other))
clojure.lang.IObj
(withMeta [self mdata] (Uri. data mdata))
clojure.lang.IMeta
(meta [self] metadata))
(defmethod print-method Uri [obj writer]
(.write ^java.io.Writer writer (format "#<Uri %s>"
(str obj))))
(defn uri
"Builds a Uri object. Takes a map of URI keys, a URI string, or
another Uri object."
[uri]
(condp instance? uri
Uri uri
clojure.lang.IPersistentMap (Uri. (parse/clean-map (build/prepare-map uri) *uri-keys*) (meta uri))
java.lang.String (Uri. (parse/clean-map (build/prepare-map (parse/uri uri)) *uri-keys*) nil)
(Uri. (-> uri str str parse/uri build/prepare-map (parse/clean-map *uri-keys*)) nil)))
(extend java.net.URI
UniformResourceIdentifier
{:scheme (fn ([^URI self] (-> self uri scheme))
([^URI self ^String new-scheme]
(-> self uri (scheme new-scheme) str URI.)))
:scheme-relative (fn ([^URI self]
(-> self uri scheme-relative))
([^URI self ^String ssp]
(-> self uri
(scheme-relative ssp) str URI.)))
:authority (fn ([^URI self] (-> self uri authority))
([^URI self ^String new-authority]
(-> self uri (authority new-authority) str URI.)))
:user-info (fn ([^URI self] (-> self uri user-info))
([^URI self ^String new-user-info]
(-> self uri (user-info new-user-info) str URI.)))
:host (fn ([^URI self] (-> self uri host))
([^URI self ^String new-host]
(-> self uri (host new-host) str URI.)))
:port (fn ([^URI self] (let [port (-> self uri port)]
(if (= port -1) nil port)))
([^URI self ^Integer new-port]
(-> self uri (port new-port) str URI.)))
:path (fn ([^URI self] (-> self uri path))
([^URI self ^String new-path]
(-> self uri (path new-path) str URI.)))
:query (fn ([^URI self] (-> self uri query))
([^URI self ^String new-query]
(-> self uri (query new-query) str URI.)))
:fragment (fn ([^URI self] (-> self uri fragment))
([^URI self ^String new-fragment]
(-> self uri (fragment new-fragment) str URI.)))})
(extend String
UniformResourceIdentifier
{:scheme (fn ([^String self] (-> self uri scheme))
([^String self ^String new-scheme]
(-> self uri (scheme new-scheme) str str)))
:scheme-relative (fn ([^String self]
(-> self uri scheme-relative))
([^String self ^String ssp]
(-> self uri
(scheme-relative ssp) str str)))
:authority (fn ([^String self] (-> self uri authority))
([^String self ^String new-authority]
(-> self uri (authority new-authority) str str)))
:user-info (fn ([^String self] (-> self uri user-info))
([^String self ^String new-user-info]
(-> self uri (user-info new-user-info) str str)))
:host (fn ([^String self] (-> self uri host))
([^String self ^String new-host]
(-> self uri (host new-host) str str)))
:port (fn ([^String self] (-> self uri port))
([^String self ^Integer new-port]
(-> self uri (port new-port) str str)))
:path (fn ([^String self] (-> self uri path))
([^String self ^String new-path]
(-> self uri (path new-path) str str)))
:query (fn ([^String self] (-> self uri query))
([^String self ^String new-query]
(-> self uri (query new-query) str str)))
:fragment (fn ([^String self] (-> self uri fragment))
([^String self ^String new-fragment]
(-> self uri (fragment new-fragment) str str)))})
(extend java.net.URL
UniformResourceIdentifier
{:scheme (fn ([^URL self] (-> self uri scheme))
([^URL self ^String new-scheme]
(-> self uri (scheme new-scheme) str URL.)))
:scheme-relative (fn ([^URL self]
(-> self uri scheme-relative))
([^URL self ^String ssp]
(-> self uri
(scheme-relative ssp) str URL.)))
:authority (fn ([^URL self] (-> self uri authority))
([^URL self ^String new-authority]
(-> self uri (authority new-authority) str URL.)))
:user-info (fn ([^URL self] (-> self uri user-info))
([^URL self ^String new-user-info]
(-> self uri (user-info new-user-info) str URL.)))
:host (fn ([^URL self] (-> self uri host))
([^URL self ^String new-host]
(-> self uri (host new-host) str URL.)))
:port (fn ([^URL self] (-> self uri port))
([^URL self ^Integer new-port]
(-> self uri (port new-port) str URL.)))
:path (fn ([^URL self] (-> self uri path))
([^URL self ^String new-path]
(-> self uri (path new-path) str URL.)))
:query (fn ([^URL self] (-> self uri query))
([^URL self ^String new-query]
(-> self uri (query new-query) str URL.)))
:fragment (fn ([^URL self] (-> self uri fragment))
([^URL self ^String new-fragment]
(-> self uri (fragment new-fragment) str URL.)))})
(defn uri->map
"Convert a java.net.URI into a hash-map."
[^URI uri]
(->> {:scheme (scheme uri)
:scheme-relative (scheme-relative uri)
:authority (authority uri)
:user-info (user-info uri)
:host (host uri)
:port (port uri)
:path (path uri)
:query (query uri)
:fragment (fragment uri)}
(filter val)
(into {})))
(defn ^URI map->uri
"Convert a hash-map into a java.net.URI."
[uri]
(cond (-> (:scheme-relative uri) empty? not)
(URI. (:scheme uri) (:scheme-relative uri)
(:fragment uri))
(:user-info uri)
(URI. (:scheme uri) (:user-info uri)
(:host uri) (or (:port uri) -1)
(:path uri) (:query uri)
(:fragment uri))
(:host uri)
(URI. (:scheme uri) (:host uri) (:path uri)
(:fragment uri))
:else (URI. (:scheme uri) (:authority uri)
(:path uri) (:query uri)
(:fragment uri))))
(defn string->map
"Convert a URI in string form to a map."
[^String string]
(-> string URI. uri->map))
(defn ^String map->string
"Convert a URI in map form to a string."
[uri]
(-> uri map->uri str str))
(defn query-list
"Returns a list from the query string of the given URI."
[uri]
(-> uri query qs/query-string->list))
(defn raw-pairs
"Returns an alist of the query params matching the given key. If no
key is given, an alist of all the query params is returned."
([uri key]
(->> uri qs/query-string->alist
(filter (fn [[param-key value]]
(= param-key key)))
vec))
([uri]
(-> uri query qs/query-string->alist)))
(defn- encode-param
"Encode a query key or param. If the value is nil, just return nil."
[text]
(if (string? text)
(URLEncoder/encode text (default-encoding))
text))
(defn- decode-param
"Decode a query key or param. If the value is nil, just return nil."
[text]
(if (string? text)
(URLDecoder/decode text (default-encoding))
text))
(defn query-pairs
"Returns an alist of the query params matching the given key. If no
key is given, an alist of all the query params is returned. The keys
and values of the pairs are URL decoded."
([uri key]
(->> uri raw-pairs
(map (fn [[key val]]
[(decode-param key) (decode-param val)]))
(filter (fn [[param-key value]]
(= param-key key)))
vec))
([uri]
(->> uri raw-pairs
(map (fn [[key val]]
[(decode-param key) (decode-param val)]))
vec)))
(defn params-raw
"Returns an alist of the query values whose key matches the given
key. If no key is given, all values are returned."
([uri key]
(->> uri raw-pairs
(filter (fn [[param-key value]]
(= param-key key)))
(map second)
vec))
([uri]
(->> uri raw-pairs (map second) vec)))
(defn params
"Returns an alist of the query values whose key matches the given
key. If no key is given, all values are returned."
([uri key]
(->> uri query-pairs
(filter (fn [[param-key value]]
(= param-key key)))
(map second)
vec))
([uri]
(->> uri query-pairs (map second) vec)))
(defn param-raw
"Get the last param value that matches the given key. If 3 args are
given, set the first param value that matches the given key, and
remove the remaining params that match the given key. If 4 args are
given, set the nth param value that matches the given key."
([uri key]
(-> uri (params-raw key) last))
([uri key value]
(query uri (-> uri raw-pairs
(qs/alist-replace key value)
qs/alist->query-string)))
([uri key value index]
(query uri (-> uri raw-pairs
(qs/alist-replace key value index)
qs/alist->query-string))))
(defn param
"Get the last param value that matches the given key. If 3 args are
given, set the first param value that matches the given key, and
remove the remaining params that match the given key. If 4 args are
given, set the nth param value that matches the given key."
([uri key]
(-> uri (params key) last))
([uri key value]
(query uri (->> (qs/alist-replace (query-pairs uri) key value)
(map (fn [[key val]]
[(encode-param key) (encode-param val)]))
qs/alist->query-string)))
([uri key value index]
(query uri (->> (qs/alist-replace (query-pairs uri) key value index)
(map (fn [[key val]]
[(encode-param key) (encode-param val)]))
qs/alist->query-string))))
(defn query-map
"Returns a map of the query string parameters for the given URI."
([uri]
(->> uri query-pairs (into {})))
([uri param-map]
(let [keywords-to-strings (fn [[k v]] [(name k) v])
query-params (->> (map keywords-to-strings param-map) (into {}))
add-param (fn [url [key val]] (param url key val))]
(reduce add-param uri query-params))))
(defn raw-keys
"Returns a list of the query string keys of the given URI."
[uri]
(->> uri raw-pairs (map first) vec))
(defn query-keys
"Returns a list of the query string keys of the given URI."
[uri]
(->> uri query-pairs (map first) vec))
(defn normalize-path
"Normalize the path of the given uri."
[uri]
(->> (path uri) path/normalize (path uri)))
(defn- as-path
"Ensure path"
[p]
(path (uri p)))
(defn resolve-path
"Resolve the given path against the given uri."
[the-uri the-path]
(let [current-path (or (path the-uri) "/")]
(path the-uri
(-> current-path (path/resolve-path (as-path the-path))))))
(defn absolute-path?
"Returns true if the given uri path is absolute."
[uri]
(-> uri path path/absolute?))
(defn absolute?
"Returns true if the given URI is absolute."
[uri]
(boolean (authority uri)))
(defn resolve-uri
"Resolves a target uri from a source uri.
Essentially this is an implementation of:
-> RFC 2396
-> RFC 1808
This implementation and the associated tests based on
this document: http://www.ics.uci.edu/~fielding/url/test2.html"
[src-uri target-uri]
(let [target-uri-query (query target-uri)
target-uri-fragment (fragment target-uri)]
;; need to handle this case separately:
;; resolve-uri "http://a/b/c" "//c"
;; since path is nil, the resolve fails
(cond
(re-find #"^//" (str target-uri))
(scheme target-uri
(scheme src-uri))
(absolute? target-uri) ; this is the second condition we match
target-uri ; against since (absolute? //a/b) => #t
; and we want (resolve-uri "http:/a/b"
; "http://c/d") to resolve to the target
; URI itself
:else
(-> src-uri
(resolve-path target-uri)
(query target-uri-query)
(fragment target-uri-fragment)))))
|
[
{
"context": "0\"}]}\n :user \"user-A\"\n :uris []}}\n",
"end": 15660,
"score": 0.9994307160377502,
"start": 15654,
"tag": "USERNAME",
"value": "user-A"
},
{
"context": " :value \"50\"}]}\n user \"user-a\"\n uris []\n mem {\"*\" 1000}\n ",
"end": 24109,
"score": 0.9995775818824768,
"start": 24103,
"tag": "USERNAME",
"value": "user-a"
},
{
"context": "sk-id}\n :slave-id {:value slave-id}\n :name name\n :executor {:executor-id {:value \"executor-id",
"end": 24905,
"score": 0.7283643484115601,
"start": 24901,
"tag": "NAME",
"value": "name"
},
{
"context": "id {:value \"framework-id\"}\n :name \"dummy-executor\"\n :command {:value comman",
"end": 25040,
"score": 0.6259891390800476,
"start": 25035,
"tag": "USERNAME",
"value": "dummy"
},
{
"context": " :environment env\n :user user\n :uris uris}}\n :reso",
"end": 25175,
"score": 0.9265041351318359,
"start": 25171,
"tag": "USERNAME",
"value": "user"
}
] | scheduler/test/cook/test/mesos/mesos_mock.clj | dposada/Cook | 0 | (ns cook.test.mesos.mesos-mock
(:use clojure.test)
(:require [chime :refer [chime-ch]]
[clj-time.core :as t]
[clojure.core.async :as async]
[clojure.tools.logging :as log]
[cook.mesos.mesos-mock :as mm]
[cook.mesos.share :as share]
[cook.mesos.util :as util]
[cook.test.simulator :refer (with-cook-scheduler pull-all-task-ents dump-jobs-to-csv)]
[cook.test.testutil :refer (restore-fresh-database! create-dummy-job poll-until)]
[datomic.api :as d]
[mesomatic.scheduler :as mesos]
[mesomatic.types :as mesos-types])
(:import java.util.UUID))
(defn string->uuid
"Parses the uuid if `uuid-str` is a uuid, returns nil otherwise"
[uuid-str]
(try
(UUID/fromString uuid-str)
(catch Exception e
nil)))
(defn noop-mock-scheduler
[]
(mesos/scheduler
(registered [this driver framework-id master-info])
(reregistered [this driver master-info])
(offer-rescinded [this driver offer-id])
(framework-message [this driver executor-id slave-id data])
(disconnected [this driver])
(slave-lost [this driver slave-id])
(executor-lost [this driver executor-id slave-id status])
(error [this driver message])
(resource-offers [this driver offers])
(status-update [this driver status])))
(deftest make-offer
(let [basic-host-info {:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
offer (mm/make-offer basic-host-info)]
(is (string->uuid (-> offer :id :value)))
(is (= (dissoc offer :id)
{:hostname "hosta"
:attributes {}
:resources [{:name "cpus", :role "*", :scalar 10 :type :value-scalar}
{:name "mem", :role "*", :scalar 100000 :type :value-scalar}
{:name "ports", :role "*", :ranges [{:begin 10000, :end 20000}] :type :value-ranges}]
:slave-id {:value "e8ab3892-3023-4546-888d-67cc13eac3cc"}}))))
(deftest prepare-new-offers
(let [state {:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer
{"8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"
{:id {:value "8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 12 :type :value-scalar}
{:name "mem" :role "*" :scalar 120000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 20000}] :type :value-ranges}]}}
:task-id->task {}}
[new-offers new-state] (mm/prepare-new-offers state)]
(is (= (count new-offers) 1))
(is (= (:slave-id->host new-state)
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}))
(is (= (count (vals (:offer-id->offer new-state))) 2))))
(deftest combine-ranges
(is (= (mm/combine-ranges [{:begin 16 :end 20} {:begin 0 :end 2}
{:begin 3 :end 5} {:begin 8 :end 10}])
[{:begin 0 :end 5} {:begin 8 :end 10} {:begin 16 :end 20}])))
(deftest combine-resources
(is (= (mm/combine-resources [{:name "cpus" :role "*" :scalar 1 :type :value-scalar}
{:name "cpus" :role "*" :scalar 6 :type :value-scalar}
{:name "mem" :role "*" :scalar 60000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 15000}] :type :value-ranges}
{:name "ports" :role "*" :ranges [{:begin 15001 :end 15003}] :type :value-ranges}])
{:cpus {"*" 7}
:mem {"*" 60000}
:ports {"*" [{:begin 10000 :end 15003}]}})))
(deftest range-contains?
(testing "ranges are the same"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 0 :end 5})))
(testing "range larger on left"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 1 :end 5})))
(testing "range strictly contains"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 1 :end 4})))
(testing "range contains single number"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 4 :end 4})))
(testing "range exceeds on left"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin -1 :end 5}))))
(testing "range exceeds on right"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin 1 :end 6}))))
(testing "range not contained completely on right"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin 6 :end 8}))))
(testing "range not contained completely on left"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin -2 :end -1})))))
(deftest ranges-contains?
(is (mm/ranges-contains? [{:begin 0 :end 5} {:begin 7 :end 10}] {:begin 7 :end 8}))
(is (not (mm/ranges-contains? [{:begin 0 :end 5} {:begin 7 :end 10}] {:begin 5 :end 7}))))
(deftest subtract-range
(testing "Full overlap"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 0 :end 5})
[])))
(testing "Equal on left"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 0 :end 4})
[{:begin 5 :end 5}])))
(testing "Equal on right"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 1 :end 5})
[{:begin 0 :end 0}])))
(testing "Remove from middle"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 2 :end 3})
[{:begin 0 :end 1} {:begin 4 :end 5}]))))
(deftest subtract-ranges
(is (= (mm/subtract-ranges [{:begin 0 :end 10}] [{:begin 0 :end 2} {:begin 4 :end 5} {:begin 7 :end 8}])
[{:begin 3 :end 3} {:begin 6 :end 6} {:begin 9 :end 10}])))
(deftest subtract-resources
(testing "Full subtraction test"
(is (= (mm/subtract-resources {:cpus {"*" 7
"cook" 3}
:mem {"*" 60000}
:ports {"*" [{:begin 10000 :end 15003} {:begin 16000 :end 20000}]
"cook" [{:begin 100 :end 200}]}}
{:cpus {"*" 4
"cook" 2}
:mem {"*" 30000}
:ports {"*" [{:begin 10000 :end 14003} {:begin 17000 :end 20000}]
"cook" [{:begin 100 :end 200}]}})
{:cpus {"*" 3
"cook" 1}
:mem {"*" 30000}
:ports {"*" [{:begin 14004 :end 15003} {:begin 16000 :end 16999}]
"cook" []}})))
(testing "not all resources subtracted"
(is (= (mm/subtract-resources {:cpus {"*" 7
"cook" 3}
:mem {"*" 60000}
:ports {"*" [{:begin 10000 :end 15003} {:begin 16000 :end 20000}]
"cook" [{:begin 100 :end 200}]}}
{:cpus {"*" 4
"cook" 2}
:mem {"*" 30000}})
{:cpus {"*" 3
"cook" 1}
:mem {"*" 30000}
:ports {"*" [{:begin 10000 :end 15003} {:begin 16000 :end 20000}]
"cook" [{:begin 100 :end 200}]}}))))
(deftest handle-decline-action
(let [offer-id "8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"
state {:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer
{offer-id
{:id {:value offer-id}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 7 :type :value-scalar}
{:name "mem" :role "*" :scalar 70000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 20000}] :type :value-ranges}]}
"45cb7812-1233-4546-888d-67cc13eac398"
{:id {:value "45cb7812-1233-4546-888d-67cc13eac398"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 5 :type :value-scalar}
{:name "mem" :role "*" :scalar 50000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 20001 :end 30000}] :type :value-ranges}]}}
:task-id->task {}}
new-state (mm/handle-action! :decline offer-id state nil (noop-mock-scheduler))]
(is (= (count (:offer-id->offer new-state)) 1))
(is (= (get-in new-state [:slave-id->host "a5cb3212-3023-4546-888d-67cc13eac3dd"])
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 7}
:mem {"*" 70000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}))))
(deftest handle-kill-action
(let [task-id "45cb7812-1233-4546-888d-67cc13eac398"
state {:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 7}
:mem {"*" 70000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer {}
:task-id->task
{task-id
{:task-id {:value task-id}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:name "to-kill"
:resources [{:name "cpus" :role "*" :scalar 5 :type :value-scalar}
{:name "mem" :role "*" :scalar 50000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 20001 :end 30000}] :type :value-ranges}]
:labels {}
:data ""}}}
new-state (mm/handle-action! :kill-task task-id state nil (noop-mock-scheduler))]
(is (= (count (:task-id->task new-state)) 0))
(is (= (get-in new-state [:slave-id->host "a5cb3212-3023-4546-888d-67cc13eac3dd"])
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}))))
(deftest handle-launch-action
(let [tasks [{:task-id {:value "45cb7812-1233-4546-888d-67cc13eac398"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:name "to-launch"
:executor {:executor-id {:value "executor-id"}
:framework-id {:value "framework-id"}
:name "dummy-executor"
:command {:value "10000"
:environment {:variables [{:name "EXECUTION_TIME"
:value "10000"}]}
:user "user-A"
:uris []}}
:resources [{:name "cpus" :role "*" :scalar 8 :type :value-scalar}
{:name "mem" :role "*" :scalar 80000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 12001 :end 25000}] :type :value-ranges}]
:labels {}
:data nil}]
tasks (map (comp mesos-types/pb->data (partial mesos-types/->pb :TaskInfo)) tasks)
offer-ids ["8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c" "45cb7812-1233-4546-888d-67cc13eac398"]
state {:config {:task->runtime-ms mm/default-task->runtime-ms}
:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer
{"8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"
{:id {:value "8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 7 :type :value-scalar}
{:name "mem" :role "*" :scalar 70000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 20000}] :type :value-ranges}]}
"45cb7812-1233-4546-888d-67cc13eac398"
{:id {:value "45cb7812-1233-4546-888d-67cc13eac398"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 5 :type :value-scalar}
{:name "mem" :role "*" :scalar 50000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 20001 :end 30000}] :type :value-ranges}]}}
:task-id->task {}}
new-state (mm/handle-action! :launch {:tasks tasks :offer-ids offer-ids} state nil (noop-mock-scheduler))]
(is (= (count (:offer-id->offer new-state)) 0))
(is (= (count (:task-id->task new-state)) 1))
(is (= (get-in new-state [:slave-id->host "a5cb3212-3023-4546-888d-67cc13eac3dd"])
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 4.0}
:mem {"*" 40000.0}
:ports {"*" [{:begin 10000 :end 12000} {:begin 25001 :end 30000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}))))
(defn dummy-host
[& {:keys [mem cpus ports uuid slave-id hostname attributes]
:or {mem {"*" 12000}
cpus {"*" 24}
ports {"*" [{:begin 0 :end 1000}]}
uuid (str (UUID/randomUUID))
slave-id (str (UUID/randomUUID))
attributes {}}}]
{:hostname (or hostname slave-id)
:attributes attributes
:resources {:cpus cpus
:mem mem
:ports ports}
:slave-id slave-id})
(deftest mesos-mock-offers
(testing "offers sent and received"
(let [registered-atom (atom false)
offer-atom (atom [])
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(swap! offer-atom into offers)))
host (dummy-host)
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock [host] offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 1) 20 600)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 1))
(is (= (get-in (first @offer-atom) [:slave-id :value]) (:slave-id host)))))
(testing "offers received, declined and received again"
(let [registered-atom (atom false)
offer-atom (atom [])
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/debug offers)
;; We want to make sure the offer, decline, re-offer loop works
;; but it gets confusing if we go through the cycle more than once
(when-not (seq @offer-atom)
(async/thread
(doseq [offer offers]
(try
(mesos/decline-offer driver (:id offer))
(catch Exception ex
(log/error ex))))))
(swap! offer-atom into offers)))
hosts [(dummy-host)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 2) 20 600)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 2))))
(testing "offers received, declined and received again, multiple hosts"
(let [registered-atom (atom false)
offer-atom (atom [])
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/debug offers)
;; We want to make sure the offer, decline, re-offer loop works
;; but it gets confusing if we go through the cycle more than once
(when-not (seq @offer-atom)
(async/thread
(doseq [offer offers]
(try
(mesos/decline-offer driver (:id offer))
(catch Exception ex
(log/error ex))))))
(swap! offer-atom into offers)))
hosts [(dummy-host) (dummy-host) (dummy-host)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 6) 20 1000)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 6)))))
(defn dummy-task
[& {:keys [task-id slave-id name command-str env user uris mem cpus ports labels data exec-time-ms-str]
:or {task-id (str (UUID/randomUUID))
slave-id (str (UUID/randomUUID))
name "my-cool-job"
command-str "dummy command"
env {:variables [{:name "EXECUTION_TIME"
:value "50"}]}
user "user-a"
uris []
mem {"*" 1000}
cpus {"*" 2}
ports {"*" [{:begin 1 :end 100}]}
labels {}
data nil
exec-time-ms-str "50"}}]
(let [make-scalar-resources (fn [name [role scalar]]
{:name name :role role :scalar scalar :type :value-scalar})
make-ranges-resources (fn [name [role ranges]]
{:name name :role role :ranges ranges :type :value-ranges})
resources (concat (map (partial make-scalar-resources "cpus") cpus)
(map (partial make-scalar-resources "mem") mem)
(map (partial make-ranges-resources "ports") ports))]
{:task-id {:value task-id}
:slave-id {:value slave-id}
:name name
:executor {:executor-id {:value "executor-id"}
:framework-id {:value "framework-id"}
:name "dummy-executor"
:command {:value command-str
:environment env
:user user
:uris uris}}
:resources resources
:labels labels
:data data}))
(deftest mesos-mock-launch
;; Note, both loading classes and jit-ing mesomatic files takes a long time
;; which can cause tests to fail if they rely on tight
;; timing assumptions and are only run once...
(testing "basic launch task"
(let [registered-atom (atom false)
launched-atom (atom [])
task-running-atom (atom [])
task-complete-atom (atom [])
atom-map {:registered-atom registered-atom
:launched-atom launched-atom
:task-running-atom task-running-atom
:task-complete-atom task-complete-atom}]
(try
(let [slave-id (str (UUID/randomUUID))
cpus {"*" 2}
mem {"*" 1000}
ports {"*" [{:begin 1 :end 100}]}
task (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/info {:offers offers :count (count offers) :id (map :id offers)})
(when (seq offers)
(when (= (count @launched-atom) 0)
(swap! launched-atom conj (:task-id task))
(mesos/launch-tasks! driver
(map :id offers)
[task]))))
(status-update [this driver status]
(log/info "Status update:" status)
(condp = (:state status)
:task-finished (swap! task-complete-atom conj (-> status :task-id :value))
:task-running (swap! task-running-atom conj (-> status :task-id :value))
(throw (ex-info "Unexpected status sent" {:status status})))))
hosts [(dummy-host :mem mem :cpus cpus :ports ports :slave-id slave-id)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @task-complete-atom) 1) 20 1000)
(log/warn "Calling stop")
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @launched-atom) 1))
(is (= (count @task-running-atom) 1))
(is (= (count @task-complete-atom) 1)))
(catch Throwable t
(throw (ex-info "Error while testing launch" atom-map t))))))
(testing "launch task"
(let [registered-atom (atom false)
launched-atom (atom [])
task-running-atom (atom [])
task-complete-atom (atom [])
atom-map {:registered-atom registered-atom
:launched-atom launched-atom
:task-running-atom task-running-atom
:task-complete-atom task-complete-atom}]
(try
(let [slave-id (str (UUID/randomUUID))
cpus {"*" 2}
mem {"*" 1000}
ports {"*" [{:begin 1 :end 100}]}
task-a (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
task-b (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/info {:offers offers :count (count offers) :id (map :id offers)})
(when (seq offers)
(when-let [task (condp = (count @launched-atom)
0 task-a
1 task-b
2 nil)]
(log/info "Want to schedule task" {:task task})
(swap! launched-atom conj (:task-id task))
(log/info "Sending launch to mesos")
(mesos/launch-tasks! driver
(map :id offers)
[task]))))
(status-update [this driver status]
(log/info "Status update:" status)
(condp = (:state status)
:task-finished (swap! task-complete-atom conj (-> status :task-id :value))
:task-running (swap! task-running-atom conj (-> status :task-id :value))
(throw (ex-info "Unexpected status sent" {:status status})))))
hosts [(dummy-host :mem mem :cpus cpus :ports ports :slave-id slave-id)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @task-complete-atom) 2) 20 1000)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @launched-atom) 2))
(is (= (count @task-running-atom) 2))
(is (= (count @task-complete-atom) 2)))
(catch Throwable t
(throw (ex-info "Error while testing launch" atom-map t)))))))
(deftest mesos-mock-kill
(testing "kill task"
(let [registered-atom (atom false)
offer-atom (atom [])
launched-atom (atom [])
task-running-atom (atom [])
task-complete-atom (atom [])
atom-map {:registered-atom registered-atom
:offer-atom offer-atom
:launched-atom launched-atom
:task-running-atom task-running-atom
:task-complete-atom task-complete-atom}]
(try
(let [slave-id (str (UUID/randomUUID))
cpus {"*" 2}
mem {"*" 1000}
ports {"*" [{:begin 1 :end 100}]}
task (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/info {:offers offers :count (count offers) :id (map :id offers)})
(when (seq offers)
(when (< (count @launched-atom) 1)
(swap! launched-atom conj (:task-id task))
(mesos/launch-tasks! driver
(map :id offers)
[task]))
(swap! offer-atom into offers)))
(status-update [this driver status]
(log/info "Status update:" status)
(condp = (:state status)
:task-killed (swap! task-complete-atom conj (-> status :task-id :value))
:task-running (let [task-id (-> status :task-id :value)]
(is (= (:value (:task-id task)) task-id))
(log/info "killing " task-id)
(mesos/kill-task! driver {:value task-id})
(swap! task-running-atom conj task-id))
(throw (ex-info "Unexpected status sent" {:status status})))))
hosts [(dummy-host :mem mem :cpus cpus :ports ports :slave-id slave-id)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 2) 20 1000)
(log/warn "Calling stop")
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 2))
(is (= (count @launched-atom) 1))
(is (= (count @task-running-atom) 1))
(is (= (count @task-complete-atom) 1)))
(catch Throwable t
(throw (ex-info "Error while testing launch" atom-map t)))))))
(deftest cook-scheduler-integration
;; This tests the case where one user has all the resources in the cluster
;; and then another user shows up which causes the scheduler to preempt jobs
;; so both may run.
;; TODO: Explicitly check that both users have ~same resources instead of
;; simply checking that the first user had some jobs preempted
(testing "basic scheduling / rebalancing test"
(let [mesos-datomic-conn (restore-fresh-database! (str (gensym "datomic:mem://mock-mesos")))
mem 2000.0
cpus 2.0
ports [{:begin 1 :end 100}]
num-hosts 10
hosts (for [_ (range num-hosts)]
(dummy-host :mem {"*" mem} :cpus {"*" cpus} :ports {"*" ports}))
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
make-mesos-driver-fn (fn [scheduler _] ;; _ is framework-id
(mm/mesos-mock hosts offer-trigger-chan scheduler))]
(with-cook-scheduler
mesos-datomic-conn make-mesos-driver-fn {}
(share/set-share! mesos-datomic-conn "default" nil "new cluster settings"
:mem mem :cpus cpus :gpus 1.0)
;; Note these two vars are lazy, need to realize to put them in db.
(let [user-a-job-exec-time-ms 10000
user-a-job-ent-ids (for [_ (range 20)]
(create-dummy-job mesos-datomic-conn
:user "a"
:command "dummy command"
:executor :executor/cook
:custom-executor? false
:memory mem
:ncpus cpus
:env {"EXECUTION_TIME" (str user-a-job-exec-time-ms)}))
user-b-job-exec-time-ms 1000
user-b-job-ent-ids (for [_ (range 5)]
(create-dummy-job mesos-datomic-conn
:user "b"
:command "dummy command"
:custom-executor? false
:executor :executor/cook
:memory mem
:ncpus cpus
:env {"EXECUTION_TIME" (str user-b-job-exec-time-ms)}))
update-status-error-ms 500]
;; Transact user "a"s jobs
(doall user-a-job-ent-ids)
;; Let them get scheduled
(poll-until (fn [] (>= (count (filter #(= (:job/state (d/entity (d/db mesos-datomic-conn) %))
:job.state/running)
user-a-job-ent-ids))
10))
200
10000
(fn [] (str (into [] (map (comp :job/state (partial d/entity (d/db mesos-datomic-conn)))
user-a-job-ent-ids)))))
;; Transact user "b"s jobs
(doall user-b-job-ent-ids)
;; Let the system complete
(poll-until (fn [] (every? (comp #(= (:job/state %) :job.state/completed)
(partial d/entity (d/db mesos-datomic-conn)))
user-a-job-ent-ids))
500
60000)
;; Expect all jobs to run and complete, expect some of user "a"s jobs
;; to be preempted
(let [job-ents (map (partial d/entity (d/db mesos-datomic-conn)) user-a-job-ent-ids)]
(is (some #(= (:reason/name (:instance/reason %)) :preempted-by-rebalancer) (mapcat :job/instance job-ents)))
(doseq [job-ent job-ents]
(let [instances (:job/instance job-ent)]
(is (= (:job/state job-ent) :job.state/completed))
(doseq [instance instances]
(is (or (= (:instance/status instance) :instance.status/success)
(= (:reason/name (:instance/reason instance)) :preempted-by-rebalancer)))
(when (= (:instance/status instance) :instance.status/success)
(is (< 0
(- (.getTime (:instance/end-time instance))
(.getTime (:instance/start-time instance))
user-a-job-exec-time-ms)
update-status-error-ms)))))))
(doseq [job-ent-id user-b-job-ent-ids]
(let [job-ent (d/entity (d/db mesos-datomic-conn) job-ent-id)
instances (:job/instance job-ent)
instance (first instances)]
(is (= (count instances) 1))
(is (= (:job/state job-ent) :job.state/completed))
(log/info "job i: " (d/touch job-ent))
(is (< 0
(- (.getTime (:instance/end-time instance))
(.getTime (:instance/start-time instance))
user-b-job-exec-time-ms)
update-status-error-ms)
(str "Invalid execution time of" job-ent))))
(when (log/enabled? :debug)
(dump-jobs-to-csv (pull-all-task-ents (d/db mesos-datomic-conn)) "trace-basic-scheduling-rebalancing-test.csv")))))))
| 46247 | (ns cook.test.mesos.mesos-mock
(:use clojure.test)
(:require [chime :refer [chime-ch]]
[clj-time.core :as t]
[clojure.core.async :as async]
[clojure.tools.logging :as log]
[cook.mesos.mesos-mock :as mm]
[cook.mesos.share :as share]
[cook.mesos.util :as util]
[cook.test.simulator :refer (with-cook-scheduler pull-all-task-ents dump-jobs-to-csv)]
[cook.test.testutil :refer (restore-fresh-database! create-dummy-job poll-until)]
[datomic.api :as d]
[mesomatic.scheduler :as mesos]
[mesomatic.types :as mesos-types])
(:import java.util.UUID))
(defn string->uuid
"Parses the uuid if `uuid-str` is a uuid, returns nil otherwise"
[uuid-str]
(try
(UUID/fromString uuid-str)
(catch Exception e
nil)))
(defn noop-mock-scheduler
[]
(mesos/scheduler
(registered [this driver framework-id master-info])
(reregistered [this driver master-info])
(offer-rescinded [this driver offer-id])
(framework-message [this driver executor-id slave-id data])
(disconnected [this driver])
(slave-lost [this driver slave-id])
(executor-lost [this driver executor-id slave-id status])
(error [this driver message])
(resource-offers [this driver offers])
(status-update [this driver status])))
(deftest make-offer
(let [basic-host-info {:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
offer (mm/make-offer basic-host-info)]
(is (string->uuid (-> offer :id :value)))
(is (= (dissoc offer :id)
{:hostname "hosta"
:attributes {}
:resources [{:name "cpus", :role "*", :scalar 10 :type :value-scalar}
{:name "mem", :role "*", :scalar 100000 :type :value-scalar}
{:name "ports", :role "*", :ranges [{:begin 10000, :end 20000}] :type :value-ranges}]
:slave-id {:value "e8ab3892-3023-4546-888d-67cc13eac3cc"}}))))
(deftest prepare-new-offers
(let [state {:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer
{"8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"
{:id {:value "8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 12 :type :value-scalar}
{:name "mem" :role "*" :scalar 120000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 20000}] :type :value-ranges}]}}
:task-id->task {}}
[new-offers new-state] (mm/prepare-new-offers state)]
(is (= (count new-offers) 1))
(is (= (:slave-id->host new-state)
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}))
(is (= (count (vals (:offer-id->offer new-state))) 2))))
(deftest combine-ranges
(is (= (mm/combine-ranges [{:begin 16 :end 20} {:begin 0 :end 2}
{:begin 3 :end 5} {:begin 8 :end 10}])
[{:begin 0 :end 5} {:begin 8 :end 10} {:begin 16 :end 20}])))
(deftest combine-resources
(is (= (mm/combine-resources [{:name "cpus" :role "*" :scalar 1 :type :value-scalar}
{:name "cpus" :role "*" :scalar 6 :type :value-scalar}
{:name "mem" :role "*" :scalar 60000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 15000}] :type :value-ranges}
{:name "ports" :role "*" :ranges [{:begin 15001 :end 15003}] :type :value-ranges}])
{:cpus {"*" 7}
:mem {"*" 60000}
:ports {"*" [{:begin 10000 :end 15003}]}})))
(deftest range-contains?
(testing "ranges are the same"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 0 :end 5})))
(testing "range larger on left"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 1 :end 5})))
(testing "range strictly contains"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 1 :end 4})))
(testing "range contains single number"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 4 :end 4})))
(testing "range exceeds on left"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin -1 :end 5}))))
(testing "range exceeds on right"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin 1 :end 6}))))
(testing "range not contained completely on right"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin 6 :end 8}))))
(testing "range not contained completely on left"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin -2 :end -1})))))
(deftest ranges-contains?
(is (mm/ranges-contains? [{:begin 0 :end 5} {:begin 7 :end 10}] {:begin 7 :end 8}))
(is (not (mm/ranges-contains? [{:begin 0 :end 5} {:begin 7 :end 10}] {:begin 5 :end 7}))))
(deftest subtract-range
(testing "Full overlap"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 0 :end 5})
[])))
(testing "Equal on left"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 0 :end 4})
[{:begin 5 :end 5}])))
(testing "Equal on right"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 1 :end 5})
[{:begin 0 :end 0}])))
(testing "Remove from middle"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 2 :end 3})
[{:begin 0 :end 1} {:begin 4 :end 5}]))))
(deftest subtract-ranges
(is (= (mm/subtract-ranges [{:begin 0 :end 10}] [{:begin 0 :end 2} {:begin 4 :end 5} {:begin 7 :end 8}])
[{:begin 3 :end 3} {:begin 6 :end 6} {:begin 9 :end 10}])))
(deftest subtract-resources
(testing "Full subtraction test"
(is (= (mm/subtract-resources {:cpus {"*" 7
"cook" 3}
:mem {"*" 60000}
:ports {"*" [{:begin 10000 :end 15003} {:begin 16000 :end 20000}]
"cook" [{:begin 100 :end 200}]}}
{:cpus {"*" 4
"cook" 2}
:mem {"*" 30000}
:ports {"*" [{:begin 10000 :end 14003} {:begin 17000 :end 20000}]
"cook" [{:begin 100 :end 200}]}})
{:cpus {"*" 3
"cook" 1}
:mem {"*" 30000}
:ports {"*" [{:begin 14004 :end 15003} {:begin 16000 :end 16999}]
"cook" []}})))
(testing "not all resources subtracted"
(is (= (mm/subtract-resources {:cpus {"*" 7
"cook" 3}
:mem {"*" 60000}
:ports {"*" [{:begin 10000 :end 15003} {:begin 16000 :end 20000}]
"cook" [{:begin 100 :end 200}]}}
{:cpus {"*" 4
"cook" 2}
:mem {"*" 30000}})
{:cpus {"*" 3
"cook" 1}
:mem {"*" 30000}
:ports {"*" [{:begin 10000 :end 15003} {:begin 16000 :end 20000}]
"cook" [{:begin 100 :end 200}]}}))))
(deftest handle-decline-action
(let [offer-id "8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"
state {:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer
{offer-id
{:id {:value offer-id}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 7 :type :value-scalar}
{:name "mem" :role "*" :scalar 70000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 20000}] :type :value-ranges}]}
"45cb7812-1233-4546-888d-67cc13eac398"
{:id {:value "45cb7812-1233-4546-888d-67cc13eac398"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 5 :type :value-scalar}
{:name "mem" :role "*" :scalar 50000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 20001 :end 30000}] :type :value-ranges}]}}
:task-id->task {}}
new-state (mm/handle-action! :decline offer-id state nil (noop-mock-scheduler))]
(is (= (count (:offer-id->offer new-state)) 1))
(is (= (get-in new-state [:slave-id->host "a5cb3212-3023-4546-888d-67cc13eac3dd"])
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 7}
:mem {"*" 70000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}))))
(deftest handle-kill-action
(let [task-id "45cb7812-1233-4546-888d-67cc13eac398"
state {:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 7}
:mem {"*" 70000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer {}
:task-id->task
{task-id
{:task-id {:value task-id}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:name "to-kill"
:resources [{:name "cpus" :role "*" :scalar 5 :type :value-scalar}
{:name "mem" :role "*" :scalar 50000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 20001 :end 30000}] :type :value-ranges}]
:labels {}
:data ""}}}
new-state (mm/handle-action! :kill-task task-id state nil (noop-mock-scheduler))]
(is (= (count (:task-id->task new-state)) 0))
(is (= (get-in new-state [:slave-id->host "a5cb3212-3023-4546-888d-67cc13eac3dd"])
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}))))
(deftest handle-launch-action
(let [tasks [{:task-id {:value "45cb7812-1233-4546-888d-67cc13eac398"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:name "to-launch"
:executor {:executor-id {:value "executor-id"}
:framework-id {:value "framework-id"}
:name "dummy-executor"
:command {:value "10000"
:environment {:variables [{:name "EXECUTION_TIME"
:value "10000"}]}
:user "user-A"
:uris []}}
:resources [{:name "cpus" :role "*" :scalar 8 :type :value-scalar}
{:name "mem" :role "*" :scalar 80000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 12001 :end 25000}] :type :value-ranges}]
:labels {}
:data nil}]
tasks (map (comp mesos-types/pb->data (partial mesos-types/->pb :TaskInfo)) tasks)
offer-ids ["8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c" "45cb7812-1233-4546-888d-67cc13eac398"]
state {:config {:task->runtime-ms mm/default-task->runtime-ms}
:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer
{"8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"
{:id {:value "8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 7 :type :value-scalar}
{:name "mem" :role "*" :scalar 70000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 20000}] :type :value-ranges}]}
"45cb7812-1233-4546-888d-67cc13eac398"
{:id {:value "45cb7812-1233-4546-888d-67cc13eac398"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 5 :type :value-scalar}
{:name "mem" :role "*" :scalar 50000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 20001 :end 30000}] :type :value-ranges}]}}
:task-id->task {}}
new-state (mm/handle-action! :launch {:tasks tasks :offer-ids offer-ids} state nil (noop-mock-scheduler))]
(is (= (count (:offer-id->offer new-state)) 0))
(is (= (count (:task-id->task new-state)) 1))
(is (= (get-in new-state [:slave-id->host "a5cb3212-3023-4546-888d-67cc13eac3dd"])
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 4.0}
:mem {"*" 40000.0}
:ports {"*" [{:begin 10000 :end 12000} {:begin 25001 :end 30000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}))))
(defn dummy-host
[& {:keys [mem cpus ports uuid slave-id hostname attributes]
:or {mem {"*" 12000}
cpus {"*" 24}
ports {"*" [{:begin 0 :end 1000}]}
uuid (str (UUID/randomUUID))
slave-id (str (UUID/randomUUID))
attributes {}}}]
{:hostname (or hostname slave-id)
:attributes attributes
:resources {:cpus cpus
:mem mem
:ports ports}
:slave-id slave-id})
(deftest mesos-mock-offers
(testing "offers sent and received"
(let [registered-atom (atom false)
offer-atom (atom [])
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(swap! offer-atom into offers)))
host (dummy-host)
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock [host] offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 1) 20 600)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 1))
(is (= (get-in (first @offer-atom) [:slave-id :value]) (:slave-id host)))))
(testing "offers received, declined and received again"
(let [registered-atom (atom false)
offer-atom (atom [])
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/debug offers)
;; We want to make sure the offer, decline, re-offer loop works
;; but it gets confusing if we go through the cycle more than once
(when-not (seq @offer-atom)
(async/thread
(doseq [offer offers]
(try
(mesos/decline-offer driver (:id offer))
(catch Exception ex
(log/error ex))))))
(swap! offer-atom into offers)))
hosts [(dummy-host)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 2) 20 600)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 2))))
(testing "offers received, declined and received again, multiple hosts"
(let [registered-atom (atom false)
offer-atom (atom [])
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/debug offers)
;; We want to make sure the offer, decline, re-offer loop works
;; but it gets confusing if we go through the cycle more than once
(when-not (seq @offer-atom)
(async/thread
(doseq [offer offers]
(try
(mesos/decline-offer driver (:id offer))
(catch Exception ex
(log/error ex))))))
(swap! offer-atom into offers)))
hosts [(dummy-host) (dummy-host) (dummy-host)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 6) 20 1000)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 6)))))
(defn dummy-task
[& {:keys [task-id slave-id name command-str env user uris mem cpus ports labels data exec-time-ms-str]
:or {task-id (str (UUID/randomUUID))
slave-id (str (UUID/randomUUID))
name "my-cool-job"
command-str "dummy command"
env {:variables [{:name "EXECUTION_TIME"
:value "50"}]}
user "user-a"
uris []
mem {"*" 1000}
cpus {"*" 2}
ports {"*" [{:begin 1 :end 100}]}
labels {}
data nil
exec-time-ms-str "50"}}]
(let [make-scalar-resources (fn [name [role scalar]]
{:name name :role role :scalar scalar :type :value-scalar})
make-ranges-resources (fn [name [role ranges]]
{:name name :role role :ranges ranges :type :value-ranges})
resources (concat (map (partial make-scalar-resources "cpus") cpus)
(map (partial make-scalar-resources "mem") mem)
(map (partial make-ranges-resources "ports") ports))]
{:task-id {:value task-id}
:slave-id {:value slave-id}
:name <NAME>
:executor {:executor-id {:value "executor-id"}
:framework-id {:value "framework-id"}
:name "dummy-executor"
:command {:value command-str
:environment env
:user user
:uris uris}}
:resources resources
:labels labels
:data data}))
(deftest mesos-mock-launch
;; Note, both loading classes and jit-ing mesomatic files takes a long time
;; which can cause tests to fail if they rely on tight
;; timing assumptions and are only run once...
(testing "basic launch task"
(let [registered-atom (atom false)
launched-atom (atom [])
task-running-atom (atom [])
task-complete-atom (atom [])
atom-map {:registered-atom registered-atom
:launched-atom launched-atom
:task-running-atom task-running-atom
:task-complete-atom task-complete-atom}]
(try
(let [slave-id (str (UUID/randomUUID))
cpus {"*" 2}
mem {"*" 1000}
ports {"*" [{:begin 1 :end 100}]}
task (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/info {:offers offers :count (count offers) :id (map :id offers)})
(when (seq offers)
(when (= (count @launched-atom) 0)
(swap! launched-atom conj (:task-id task))
(mesos/launch-tasks! driver
(map :id offers)
[task]))))
(status-update [this driver status]
(log/info "Status update:" status)
(condp = (:state status)
:task-finished (swap! task-complete-atom conj (-> status :task-id :value))
:task-running (swap! task-running-atom conj (-> status :task-id :value))
(throw (ex-info "Unexpected status sent" {:status status})))))
hosts [(dummy-host :mem mem :cpus cpus :ports ports :slave-id slave-id)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @task-complete-atom) 1) 20 1000)
(log/warn "Calling stop")
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @launched-atom) 1))
(is (= (count @task-running-atom) 1))
(is (= (count @task-complete-atom) 1)))
(catch Throwable t
(throw (ex-info "Error while testing launch" atom-map t))))))
(testing "launch task"
(let [registered-atom (atom false)
launched-atom (atom [])
task-running-atom (atom [])
task-complete-atom (atom [])
atom-map {:registered-atom registered-atom
:launched-atom launched-atom
:task-running-atom task-running-atom
:task-complete-atom task-complete-atom}]
(try
(let [slave-id (str (UUID/randomUUID))
cpus {"*" 2}
mem {"*" 1000}
ports {"*" [{:begin 1 :end 100}]}
task-a (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
task-b (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/info {:offers offers :count (count offers) :id (map :id offers)})
(when (seq offers)
(when-let [task (condp = (count @launched-atom)
0 task-a
1 task-b
2 nil)]
(log/info "Want to schedule task" {:task task})
(swap! launched-atom conj (:task-id task))
(log/info "Sending launch to mesos")
(mesos/launch-tasks! driver
(map :id offers)
[task]))))
(status-update [this driver status]
(log/info "Status update:" status)
(condp = (:state status)
:task-finished (swap! task-complete-atom conj (-> status :task-id :value))
:task-running (swap! task-running-atom conj (-> status :task-id :value))
(throw (ex-info "Unexpected status sent" {:status status})))))
hosts [(dummy-host :mem mem :cpus cpus :ports ports :slave-id slave-id)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @task-complete-atom) 2) 20 1000)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @launched-atom) 2))
(is (= (count @task-running-atom) 2))
(is (= (count @task-complete-atom) 2)))
(catch Throwable t
(throw (ex-info "Error while testing launch" atom-map t)))))))
(deftest mesos-mock-kill
(testing "kill task"
(let [registered-atom (atom false)
offer-atom (atom [])
launched-atom (atom [])
task-running-atom (atom [])
task-complete-atom (atom [])
atom-map {:registered-atom registered-atom
:offer-atom offer-atom
:launched-atom launched-atom
:task-running-atom task-running-atom
:task-complete-atom task-complete-atom}]
(try
(let [slave-id (str (UUID/randomUUID))
cpus {"*" 2}
mem {"*" 1000}
ports {"*" [{:begin 1 :end 100}]}
task (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/info {:offers offers :count (count offers) :id (map :id offers)})
(when (seq offers)
(when (< (count @launched-atom) 1)
(swap! launched-atom conj (:task-id task))
(mesos/launch-tasks! driver
(map :id offers)
[task]))
(swap! offer-atom into offers)))
(status-update [this driver status]
(log/info "Status update:" status)
(condp = (:state status)
:task-killed (swap! task-complete-atom conj (-> status :task-id :value))
:task-running (let [task-id (-> status :task-id :value)]
(is (= (:value (:task-id task)) task-id))
(log/info "killing " task-id)
(mesos/kill-task! driver {:value task-id})
(swap! task-running-atom conj task-id))
(throw (ex-info "Unexpected status sent" {:status status})))))
hosts [(dummy-host :mem mem :cpus cpus :ports ports :slave-id slave-id)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 2) 20 1000)
(log/warn "Calling stop")
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 2))
(is (= (count @launched-atom) 1))
(is (= (count @task-running-atom) 1))
(is (= (count @task-complete-atom) 1)))
(catch Throwable t
(throw (ex-info "Error while testing launch" atom-map t)))))))
(deftest cook-scheduler-integration
;; This tests the case where one user has all the resources in the cluster
;; and then another user shows up which causes the scheduler to preempt jobs
;; so both may run.
;; TODO: Explicitly check that both users have ~same resources instead of
;; simply checking that the first user had some jobs preempted
(testing "basic scheduling / rebalancing test"
(let [mesos-datomic-conn (restore-fresh-database! (str (gensym "datomic:mem://mock-mesos")))
mem 2000.0
cpus 2.0
ports [{:begin 1 :end 100}]
num-hosts 10
hosts (for [_ (range num-hosts)]
(dummy-host :mem {"*" mem} :cpus {"*" cpus} :ports {"*" ports}))
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
make-mesos-driver-fn (fn [scheduler _] ;; _ is framework-id
(mm/mesos-mock hosts offer-trigger-chan scheduler))]
(with-cook-scheduler
mesos-datomic-conn make-mesos-driver-fn {}
(share/set-share! mesos-datomic-conn "default" nil "new cluster settings"
:mem mem :cpus cpus :gpus 1.0)
;; Note these two vars are lazy, need to realize to put them in db.
(let [user-a-job-exec-time-ms 10000
user-a-job-ent-ids (for [_ (range 20)]
(create-dummy-job mesos-datomic-conn
:user "a"
:command "dummy command"
:executor :executor/cook
:custom-executor? false
:memory mem
:ncpus cpus
:env {"EXECUTION_TIME" (str user-a-job-exec-time-ms)}))
user-b-job-exec-time-ms 1000
user-b-job-ent-ids (for [_ (range 5)]
(create-dummy-job mesos-datomic-conn
:user "b"
:command "dummy command"
:custom-executor? false
:executor :executor/cook
:memory mem
:ncpus cpus
:env {"EXECUTION_TIME" (str user-b-job-exec-time-ms)}))
update-status-error-ms 500]
;; Transact user "a"s jobs
(doall user-a-job-ent-ids)
;; Let them get scheduled
(poll-until (fn [] (>= (count (filter #(= (:job/state (d/entity (d/db mesos-datomic-conn) %))
:job.state/running)
user-a-job-ent-ids))
10))
200
10000
(fn [] (str (into [] (map (comp :job/state (partial d/entity (d/db mesos-datomic-conn)))
user-a-job-ent-ids)))))
;; Transact user "b"s jobs
(doall user-b-job-ent-ids)
;; Let the system complete
(poll-until (fn [] (every? (comp #(= (:job/state %) :job.state/completed)
(partial d/entity (d/db mesos-datomic-conn)))
user-a-job-ent-ids))
500
60000)
;; Expect all jobs to run and complete, expect some of user "a"s jobs
;; to be preempted
(let [job-ents (map (partial d/entity (d/db mesos-datomic-conn)) user-a-job-ent-ids)]
(is (some #(= (:reason/name (:instance/reason %)) :preempted-by-rebalancer) (mapcat :job/instance job-ents)))
(doseq [job-ent job-ents]
(let [instances (:job/instance job-ent)]
(is (= (:job/state job-ent) :job.state/completed))
(doseq [instance instances]
(is (or (= (:instance/status instance) :instance.status/success)
(= (:reason/name (:instance/reason instance)) :preempted-by-rebalancer)))
(when (= (:instance/status instance) :instance.status/success)
(is (< 0
(- (.getTime (:instance/end-time instance))
(.getTime (:instance/start-time instance))
user-a-job-exec-time-ms)
update-status-error-ms)))))))
(doseq [job-ent-id user-b-job-ent-ids]
(let [job-ent (d/entity (d/db mesos-datomic-conn) job-ent-id)
instances (:job/instance job-ent)
instance (first instances)]
(is (= (count instances) 1))
(is (= (:job/state job-ent) :job.state/completed))
(log/info "job i: " (d/touch job-ent))
(is (< 0
(- (.getTime (:instance/end-time instance))
(.getTime (:instance/start-time instance))
user-b-job-exec-time-ms)
update-status-error-ms)
(str "Invalid execution time of" job-ent))))
(when (log/enabled? :debug)
(dump-jobs-to-csv (pull-all-task-ents (d/db mesos-datomic-conn)) "trace-basic-scheduling-rebalancing-test.csv")))))))
| true | (ns cook.test.mesos.mesos-mock
(:use clojure.test)
(:require [chime :refer [chime-ch]]
[clj-time.core :as t]
[clojure.core.async :as async]
[clojure.tools.logging :as log]
[cook.mesos.mesos-mock :as mm]
[cook.mesos.share :as share]
[cook.mesos.util :as util]
[cook.test.simulator :refer (with-cook-scheduler pull-all-task-ents dump-jobs-to-csv)]
[cook.test.testutil :refer (restore-fresh-database! create-dummy-job poll-until)]
[datomic.api :as d]
[mesomatic.scheduler :as mesos]
[mesomatic.types :as mesos-types])
(:import java.util.UUID))
(defn string->uuid
"Parses the uuid if `uuid-str` is a uuid, returns nil otherwise"
[uuid-str]
(try
(UUID/fromString uuid-str)
(catch Exception e
nil)))
(defn noop-mock-scheduler
[]
(mesos/scheduler
(registered [this driver framework-id master-info])
(reregistered [this driver master-info])
(offer-rescinded [this driver offer-id])
(framework-message [this driver executor-id slave-id data])
(disconnected [this driver])
(slave-lost [this driver slave-id])
(executor-lost [this driver executor-id slave-id status])
(error [this driver message])
(resource-offers [this driver offers])
(status-update [this driver status])))
(deftest make-offer
(let [basic-host-info {:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
offer (mm/make-offer basic-host-info)]
(is (string->uuid (-> offer :id :value)))
(is (= (dissoc offer :id)
{:hostname "hosta"
:attributes {}
:resources [{:name "cpus", :role "*", :scalar 10 :type :value-scalar}
{:name "mem", :role "*", :scalar 100000 :type :value-scalar}
{:name "ports", :role "*", :ranges [{:begin 10000, :end 20000}] :type :value-ranges}]
:slave-id {:value "e8ab3892-3023-4546-888d-67cc13eac3cc"}}))))
(deftest prepare-new-offers
(let [state {:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer
{"8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"
{:id {:value "8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 12 :type :value-scalar}
{:name "mem" :role "*" :scalar 120000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 20000}] :type :value-ranges}]}}
:task-id->task {}}
[new-offers new-state] (mm/prepare-new-offers state)]
(is (= (count new-offers) 1))
(is (= (:slave-id->host new-state)
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}))
(is (= (count (vals (:offer-id->offer new-state))) 2))))
(deftest combine-ranges
(is (= (mm/combine-ranges [{:begin 16 :end 20} {:begin 0 :end 2}
{:begin 3 :end 5} {:begin 8 :end 10}])
[{:begin 0 :end 5} {:begin 8 :end 10} {:begin 16 :end 20}])))
(deftest combine-resources
(is (= (mm/combine-resources [{:name "cpus" :role "*" :scalar 1 :type :value-scalar}
{:name "cpus" :role "*" :scalar 6 :type :value-scalar}
{:name "mem" :role "*" :scalar 60000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 15000}] :type :value-ranges}
{:name "ports" :role "*" :ranges [{:begin 15001 :end 15003}] :type :value-ranges}])
{:cpus {"*" 7}
:mem {"*" 60000}
:ports {"*" [{:begin 10000 :end 15003}]}})))
(deftest range-contains?
(testing "ranges are the same"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 0 :end 5})))
(testing "range larger on left"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 1 :end 5})))
(testing "range strictly contains"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 1 :end 4})))
(testing "range contains single number"
(is (mm/range-contains? {:begin 0 :end 5} {:begin 4 :end 4})))
(testing "range exceeds on left"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin -1 :end 5}))))
(testing "range exceeds on right"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin 1 :end 6}))))
(testing "range not contained completely on right"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin 6 :end 8}))))
(testing "range not contained completely on left"
(is (not (mm/range-contains? {:begin 0 :end 5} {:begin -2 :end -1})))))
(deftest ranges-contains?
(is (mm/ranges-contains? [{:begin 0 :end 5} {:begin 7 :end 10}] {:begin 7 :end 8}))
(is (not (mm/ranges-contains? [{:begin 0 :end 5} {:begin 7 :end 10}] {:begin 5 :end 7}))))
(deftest subtract-range
(testing "Full overlap"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 0 :end 5})
[])))
(testing "Equal on left"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 0 :end 4})
[{:begin 5 :end 5}])))
(testing "Equal on right"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 1 :end 5})
[{:begin 0 :end 0}])))
(testing "Remove from middle"
(is (= (mm/subtract-range {:begin 0 :end 5} {:begin 2 :end 3})
[{:begin 0 :end 1} {:begin 4 :end 5}]))))
(deftest subtract-ranges
(is (= (mm/subtract-ranges [{:begin 0 :end 10}] [{:begin 0 :end 2} {:begin 4 :end 5} {:begin 7 :end 8}])
[{:begin 3 :end 3} {:begin 6 :end 6} {:begin 9 :end 10}])))
(deftest subtract-resources
(testing "Full subtraction test"
(is (= (mm/subtract-resources {:cpus {"*" 7
"cook" 3}
:mem {"*" 60000}
:ports {"*" [{:begin 10000 :end 15003} {:begin 16000 :end 20000}]
"cook" [{:begin 100 :end 200}]}}
{:cpus {"*" 4
"cook" 2}
:mem {"*" 30000}
:ports {"*" [{:begin 10000 :end 14003} {:begin 17000 :end 20000}]
"cook" [{:begin 100 :end 200}]}})
{:cpus {"*" 3
"cook" 1}
:mem {"*" 30000}
:ports {"*" [{:begin 14004 :end 15003} {:begin 16000 :end 16999}]
"cook" []}})))
(testing "not all resources subtracted"
(is (= (mm/subtract-resources {:cpus {"*" 7
"cook" 3}
:mem {"*" 60000}
:ports {"*" [{:begin 10000 :end 15003} {:begin 16000 :end 20000}]
"cook" [{:begin 100 :end 200}]}}
{:cpus {"*" 4
"cook" 2}
:mem {"*" 30000}})
{:cpus {"*" 3
"cook" 1}
:mem {"*" 30000}
:ports {"*" [{:begin 10000 :end 15003} {:begin 16000 :end 20000}]
"cook" [{:begin 100 :end 200}]}}))))
(deftest handle-decline-action
(let [offer-id "8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"
state {:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer
{offer-id
{:id {:value offer-id}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 7 :type :value-scalar}
{:name "mem" :role "*" :scalar 70000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 20000}] :type :value-ranges}]}
"45cb7812-1233-4546-888d-67cc13eac398"
{:id {:value "45cb7812-1233-4546-888d-67cc13eac398"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 5 :type :value-scalar}
{:name "mem" :role "*" :scalar 50000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 20001 :end 30000}] :type :value-ranges}]}}
:task-id->task {}}
new-state (mm/handle-action! :decline offer-id state nil (noop-mock-scheduler))]
(is (= (count (:offer-id->offer new-state)) 1))
(is (= (get-in new-state [:slave-id->host "a5cb3212-3023-4546-888d-67cc13eac3dd"])
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 7}
:mem {"*" 70000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}))))
(deftest handle-kill-action
(let [task-id "45cb7812-1233-4546-888d-67cc13eac398"
state {:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 7}
:mem {"*" 70000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer {}
:task-id->task
{task-id
{:task-id {:value task-id}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:name "to-kill"
:resources [{:name "cpus" :role "*" :scalar 5 :type :value-scalar}
{:name "mem" :role "*" :scalar 50000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 20001 :end 30000}] :type :value-ranges}]
:labels {}
:data ""}}}
new-state (mm/handle-action! :kill-task task-id state nil (noop-mock-scheduler))]
(is (= (count (:task-id->task new-state)) 0))
(is (= (get-in new-state [:slave-id->host "a5cb3212-3023-4546-888d-67cc13eac3dd"])
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}))))
(deftest handle-launch-action
(let [tasks [{:task-id {:value "45cb7812-1233-4546-888d-67cc13eac398"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:name "to-launch"
:executor {:executor-id {:value "executor-id"}
:framework-id {:value "framework-id"}
:name "dummy-executor"
:command {:value "10000"
:environment {:variables [{:name "EXECUTION_TIME"
:value "10000"}]}
:user "user-A"
:uris []}}
:resources [{:name "cpus" :role "*" :scalar 8 :type :value-scalar}
{:name "mem" :role "*" :scalar 80000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 12001 :end 25000}] :type :value-ranges}]
:labels {}
:data nil}]
tasks (map (comp mesos-types/pb->data (partial mesos-types/->pb :TaskInfo)) tasks)
offer-ids ["8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c" "45cb7812-1233-4546-888d-67cc13eac398"]
state {:config {:task->runtime-ms mm/default-task->runtime-ms}
:slave-id->host
{"e8ab3892-3023-4546-888d-67cc13eac3cc"
{:hostname "hosta"
:attributes {}
:resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:available-resources {:cpus {"*" 10}
:mem {"*" 100000}
:ports {"*" [{:begin 10000 :end 20000}]}}
:slave-id "e8ab3892-3023-4546-888d-67cc13eac3cc"}
"a5cb3212-3023-4546-888d-67cc13eac3dd"
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {}
:mem {}
:ports {}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}}
:offer-id->offer
{"8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"
{:id {:value "8fe5bf6c-ea39-4700-b1f6-9fd8a0271d7c"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 7 :type :value-scalar}
{:name "mem" :role "*" :scalar 70000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 10000 :end 20000}] :type :value-ranges}]}
"45cb7812-1233-4546-888d-67cc13eac398"
{:id {:value "45cb7812-1233-4546-888d-67cc13eac398"}
:slave-id {:value "a5cb3212-3023-4546-888d-67cc13eac3dd"}
:hostname "hostb"
:resources [{:name "cpus" :role "*" :scalar 5 :type :value-scalar}
{:name "mem" :role "*" :scalar 50000 :type :value-scalar}
{:name "ports" :role "*" :ranges [{:begin 20001 :end 30000}] :type :value-ranges}]}}
:task-id->task {}}
new-state (mm/handle-action! :launch {:tasks tasks :offer-ids offer-ids} state nil (noop-mock-scheduler))]
(is (= (count (:offer-id->offer new-state)) 0))
(is (= (count (:task-id->task new-state)) 1))
(is (= (get-in new-state [:slave-id->host "a5cb3212-3023-4546-888d-67cc13eac3dd"])
{:hostname "hostb"
:attributes {}
:resources {:cpus {"*" 12}
:mem {"*" 120000}
:ports {"*" [{:begin 10000 :end 30000}]}}
:available-resources {:cpus {"*" 4.0}
:mem {"*" 40000.0}
:ports {"*" [{:begin 10000 :end 12000} {:begin 25001 :end 30000}]}}
:slave-id "a5cb3212-3023-4546-888d-67cc13eac3dd"}))))
(defn dummy-host
[& {:keys [mem cpus ports uuid slave-id hostname attributes]
:or {mem {"*" 12000}
cpus {"*" 24}
ports {"*" [{:begin 0 :end 1000}]}
uuid (str (UUID/randomUUID))
slave-id (str (UUID/randomUUID))
attributes {}}}]
{:hostname (or hostname slave-id)
:attributes attributes
:resources {:cpus cpus
:mem mem
:ports ports}
:slave-id slave-id})
(deftest mesos-mock-offers
(testing "offers sent and received"
(let [registered-atom (atom false)
offer-atom (atom [])
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(swap! offer-atom into offers)))
host (dummy-host)
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock [host] offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 1) 20 600)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 1))
(is (= (get-in (first @offer-atom) [:slave-id :value]) (:slave-id host)))))
(testing "offers received, declined and received again"
(let [registered-atom (atom false)
offer-atom (atom [])
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/debug offers)
;; We want to make sure the offer, decline, re-offer loop works
;; but it gets confusing if we go through the cycle more than once
(when-not (seq @offer-atom)
(async/thread
(doseq [offer offers]
(try
(mesos/decline-offer driver (:id offer))
(catch Exception ex
(log/error ex))))))
(swap! offer-atom into offers)))
hosts [(dummy-host)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 2) 20 600)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 2))))
(testing "offers received, declined and received again, multiple hosts"
(let [registered-atom (atom false)
offer-atom (atom [])
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/debug offers)
;; We want to make sure the offer, decline, re-offer loop works
;; but it gets confusing if we go through the cycle more than once
(when-not (seq @offer-atom)
(async/thread
(doseq [offer offers]
(try
(mesos/decline-offer driver (:id offer))
(catch Exception ex
(log/error ex))))))
(swap! offer-atom into offers)))
hosts [(dummy-host) (dummy-host) (dummy-host)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 6) 20 1000)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 6)))))
(defn dummy-task
[& {:keys [task-id slave-id name command-str env user uris mem cpus ports labels data exec-time-ms-str]
:or {task-id (str (UUID/randomUUID))
slave-id (str (UUID/randomUUID))
name "my-cool-job"
command-str "dummy command"
env {:variables [{:name "EXECUTION_TIME"
:value "50"}]}
user "user-a"
uris []
mem {"*" 1000}
cpus {"*" 2}
ports {"*" [{:begin 1 :end 100}]}
labels {}
data nil
exec-time-ms-str "50"}}]
(let [make-scalar-resources (fn [name [role scalar]]
{:name name :role role :scalar scalar :type :value-scalar})
make-ranges-resources (fn [name [role ranges]]
{:name name :role role :ranges ranges :type :value-ranges})
resources (concat (map (partial make-scalar-resources "cpus") cpus)
(map (partial make-scalar-resources "mem") mem)
(map (partial make-ranges-resources "ports") ports))]
{:task-id {:value task-id}
:slave-id {:value slave-id}
:name PI:NAME:<NAME>END_PI
:executor {:executor-id {:value "executor-id"}
:framework-id {:value "framework-id"}
:name "dummy-executor"
:command {:value command-str
:environment env
:user user
:uris uris}}
:resources resources
:labels labels
:data data}))
(deftest mesos-mock-launch
;; Note, both loading classes and jit-ing mesomatic files takes a long time
;; which can cause tests to fail if they rely on tight
;; timing assumptions and are only run once...
(testing "basic launch task"
(let [registered-atom (atom false)
launched-atom (atom [])
task-running-atom (atom [])
task-complete-atom (atom [])
atom-map {:registered-atom registered-atom
:launched-atom launched-atom
:task-running-atom task-running-atom
:task-complete-atom task-complete-atom}]
(try
(let [slave-id (str (UUID/randomUUID))
cpus {"*" 2}
mem {"*" 1000}
ports {"*" [{:begin 1 :end 100}]}
task (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/info {:offers offers :count (count offers) :id (map :id offers)})
(when (seq offers)
(when (= (count @launched-atom) 0)
(swap! launched-atom conj (:task-id task))
(mesos/launch-tasks! driver
(map :id offers)
[task]))))
(status-update [this driver status]
(log/info "Status update:" status)
(condp = (:state status)
:task-finished (swap! task-complete-atom conj (-> status :task-id :value))
:task-running (swap! task-running-atom conj (-> status :task-id :value))
(throw (ex-info "Unexpected status sent" {:status status})))))
hosts [(dummy-host :mem mem :cpus cpus :ports ports :slave-id slave-id)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @task-complete-atom) 1) 20 1000)
(log/warn "Calling stop")
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @launched-atom) 1))
(is (= (count @task-running-atom) 1))
(is (= (count @task-complete-atom) 1)))
(catch Throwable t
(throw (ex-info "Error while testing launch" atom-map t))))))
(testing "launch task"
(let [registered-atom (atom false)
launched-atom (atom [])
task-running-atom (atom [])
task-complete-atom (atom [])
atom-map {:registered-atom registered-atom
:launched-atom launched-atom
:task-running-atom task-running-atom
:task-complete-atom task-complete-atom}]
(try
(let [slave-id (str (UUID/randomUUID))
cpus {"*" 2}
mem {"*" 1000}
ports {"*" [{:begin 1 :end 100}]}
task-a (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
task-b (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/info {:offers offers :count (count offers) :id (map :id offers)})
(when (seq offers)
(when-let [task (condp = (count @launched-atom)
0 task-a
1 task-b
2 nil)]
(log/info "Want to schedule task" {:task task})
(swap! launched-atom conj (:task-id task))
(log/info "Sending launch to mesos")
(mesos/launch-tasks! driver
(map :id offers)
[task]))))
(status-update [this driver status]
(log/info "Status update:" status)
(condp = (:state status)
:task-finished (swap! task-complete-atom conj (-> status :task-id :value))
:task-running (swap! task-running-atom conj (-> status :task-id :value))
(throw (ex-info "Unexpected status sent" {:status status})))))
hosts [(dummy-host :mem mem :cpus cpus :ports ports :slave-id slave-id)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @task-complete-atom) 2) 20 1000)
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @launched-atom) 2))
(is (= (count @task-running-atom) 2))
(is (= (count @task-complete-atom) 2)))
(catch Throwable t
(throw (ex-info "Error while testing launch" atom-map t)))))))
(deftest mesos-mock-kill
(testing "kill task"
(let [registered-atom (atom false)
offer-atom (atom [])
launched-atom (atom [])
task-running-atom (atom [])
task-complete-atom (atom [])
atom-map {:registered-atom registered-atom
:offer-atom offer-atom
:launched-atom launched-atom
:task-running-atom task-running-atom
:task-complete-atom task-complete-atom}]
(try
(let [slave-id (str (UUID/randomUUID))
cpus {"*" 2}
mem {"*" 1000}
ports {"*" [{:begin 1 :end 100}]}
task (dummy-task :mem mem :cpus cpus :ports ports :slave-id slave-id)
scheduler (mesos/scheduler
(registered [this driver framework-id master-info]
(reset! registered-atom true))
(resource-offers [this driver offers]
(log/info {:offers offers :count (count offers) :id (map :id offers)})
(when (seq offers)
(when (< (count @launched-atom) 1)
(swap! launched-atom conj (:task-id task))
(mesos/launch-tasks! driver
(map :id offers)
[task]))
(swap! offer-atom into offers)))
(status-update [this driver status]
(log/info "Status update:" status)
(condp = (:state status)
:task-killed (swap! task-complete-atom conj (-> status :task-id :value))
:task-running (let [task-id (-> status :task-id :value)]
(is (= (:value (:task-id task)) task-id))
(log/info "killing " task-id)
(mesos/kill-task! driver {:value task-id})
(swap! task-running-atom conj task-id))
(throw (ex-info "Unexpected status sent" {:status status})))))
hosts [(dummy-host :mem mem :cpus cpus :ports ports :slave-id slave-id)]
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
mock-driver (mm/mesos-mock hosts offer-trigger-chan scheduler)]
(mesos/start! mock-driver)
(poll-until #(= (count @offer-atom) 2) 20 1000)
(log/warn "Calling stop")
(mesos/stop! mock-driver)
(is @registered-atom)
(is (= (count @offer-atom) 2))
(is (= (count @launched-atom) 1))
(is (= (count @task-running-atom) 1))
(is (= (count @task-complete-atom) 1)))
(catch Throwable t
(throw (ex-info "Error while testing launch" atom-map t)))))))
(deftest cook-scheduler-integration
;; This tests the case where one user has all the resources in the cluster
;; and then another user shows up which causes the scheduler to preempt jobs
;; so both may run.
;; TODO: Explicitly check that both users have ~same resources instead of
;; simply checking that the first user had some jobs preempted
(testing "basic scheduling / rebalancing test"
(let [mesos-datomic-conn (restore-fresh-database! (str (gensym "datomic:mem://mock-mesos")))
mem 2000.0
cpus 2.0
ports [{:begin 1 :end 100}]
num-hosts 10
hosts (for [_ (range num-hosts)]
(dummy-host :mem {"*" mem} :cpus {"*" cpus} :ports {"*" ports}))
offer-trigger-chan (chime-ch (util/time-seq (t/now) (t/millis 50)))
make-mesos-driver-fn (fn [scheduler _] ;; _ is framework-id
(mm/mesos-mock hosts offer-trigger-chan scheduler))]
(with-cook-scheduler
mesos-datomic-conn make-mesos-driver-fn {}
(share/set-share! mesos-datomic-conn "default" nil "new cluster settings"
:mem mem :cpus cpus :gpus 1.0)
;; Note these two vars are lazy, need to realize to put them in db.
(let [user-a-job-exec-time-ms 10000
user-a-job-ent-ids (for [_ (range 20)]
(create-dummy-job mesos-datomic-conn
:user "a"
:command "dummy command"
:executor :executor/cook
:custom-executor? false
:memory mem
:ncpus cpus
:env {"EXECUTION_TIME" (str user-a-job-exec-time-ms)}))
user-b-job-exec-time-ms 1000
user-b-job-ent-ids (for [_ (range 5)]
(create-dummy-job mesos-datomic-conn
:user "b"
:command "dummy command"
:custom-executor? false
:executor :executor/cook
:memory mem
:ncpus cpus
:env {"EXECUTION_TIME" (str user-b-job-exec-time-ms)}))
update-status-error-ms 500]
;; Transact user "a"s jobs
(doall user-a-job-ent-ids)
;; Let them get scheduled
(poll-until (fn [] (>= (count (filter #(= (:job/state (d/entity (d/db mesos-datomic-conn) %))
:job.state/running)
user-a-job-ent-ids))
10))
200
10000
(fn [] (str (into [] (map (comp :job/state (partial d/entity (d/db mesos-datomic-conn)))
user-a-job-ent-ids)))))
;; Transact user "b"s jobs
(doall user-b-job-ent-ids)
;; Let the system complete
(poll-until (fn [] (every? (comp #(= (:job/state %) :job.state/completed)
(partial d/entity (d/db mesos-datomic-conn)))
user-a-job-ent-ids))
500
60000)
;; Expect all jobs to run and complete, expect some of user "a"s jobs
;; to be preempted
(let [job-ents (map (partial d/entity (d/db mesos-datomic-conn)) user-a-job-ent-ids)]
(is (some #(= (:reason/name (:instance/reason %)) :preempted-by-rebalancer) (mapcat :job/instance job-ents)))
(doseq [job-ent job-ents]
(let [instances (:job/instance job-ent)]
(is (= (:job/state job-ent) :job.state/completed))
(doseq [instance instances]
(is (or (= (:instance/status instance) :instance.status/success)
(= (:reason/name (:instance/reason instance)) :preempted-by-rebalancer)))
(when (= (:instance/status instance) :instance.status/success)
(is (< 0
(- (.getTime (:instance/end-time instance))
(.getTime (:instance/start-time instance))
user-a-job-exec-time-ms)
update-status-error-ms)))))))
(doseq [job-ent-id user-b-job-ent-ids]
(let [job-ent (d/entity (d/db mesos-datomic-conn) job-ent-id)
instances (:job/instance job-ent)
instance (first instances)]
(is (= (count instances) 1))
(is (= (:job/state job-ent) :job.state/completed))
(log/info "job i: " (d/touch job-ent))
(is (< 0
(- (.getTime (:instance/end-time instance))
(.getTime (:instance/start-time instance))
user-b-job-exec-time-ms)
update-status-error-ms)
(str "Invalid execution time of" job-ent))))
(when (log/enabled? :debug)
(dump-jobs-to-csv (pull-all-task-ents (d/db mesos-datomic-conn)) "trace-basic-scheduling-rebalancing-test.csv")))))))
|
[
{
"context": "all]))\n\n\n\n(deftest hex-to-base64-test\n (def inp \"49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d\")\n (def out \"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWt",
"end": 253,
"score": 0.9986721873283386,
"start": 157,
"tag": "KEY",
"value": "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
},
{
"context": "06f69736f6e6f7573206d757368726f6f6d\")\n (def out \"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\")\n (testing \"\" (is (= out (encode inp)))))\n",
"end": 332,
"score": 0.9817784428596497,
"start": 268,
"tag": "KEY",
"value": "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
}
] | test/set1/hex_to_base64_test.clj | milapsheth/Crypto-Challenges | 3 | (ns set1.hex-to-base64-test
(:require [clojure.test :refer :all]
[set1.hex-to-base64 :refer :all]))
(deftest hex-to-base64-test
(def inp "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d")
(def out "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t")
(testing "" (is (= out (encode inp)))))
| 84726 | (ns set1.hex-to-base64-test
(:require [clojure.test :refer :all]
[set1.hex-to-base64 :refer :all]))
(deftest hex-to-base64-test
(def inp "<KEY>")
(def out "<KEY>")
(testing "" (is (= out (encode inp)))))
| true | (ns set1.hex-to-base64-test
(:require [clojure.test :refer :all]
[set1.hex-to-base64 :refer :all]))
(deftest hex-to-base64-test
(def inp "PI:KEY:<KEY>END_PI")
(def out "PI:KEY:<KEY>END_PI")
(testing "" (is (= out (encode inp)))))
|
[
{
"context": ";; Copyright (c) 2015, Dmitry Kozlov <kozlov.dmitry.a@gmail.com>\n;; Code is published ",
"end": 36,
"score": 0.9998647570610046,
"start": 23,
"tag": "NAME",
"value": "Dmitry Kozlov"
},
{
"context": ";; Copyright (c) 2015, Dmitry Kozlov <kozlov.dmitry.a@gmail.com>\n;; Code is published under BSD 2-clause license\n",
"end": 63,
"score": 0.9999318718910217,
"start": 38,
"tag": "EMAIL",
"value": "kozlov.dmitry.a@gmail.com"
}
] | src/illya/app.clj | dkz/illya | 2 | ;; Copyright (c) 2015, Dmitry Kozlov <kozlov.dmitry.a@gmail.com>
;; Code is published under BSD 2-clause license
(ns illya.app
(:gen-class)
(:use compojure.core)
(:require
[illya.views :as views]
[illya.storage :as storage]
[illya.config :as configuration]
[illya.sessions :as sessions]
[ring.adapter.jetty-async :refer [run-jetty-async]]
[compojure.route :as routes]
[compojure.handler :as handler]
[ring.util.response :as response]
[clojure.string :as string]
[spyscope.core :as spy]
[hiccup.core :as hiccup :refer [h]]))
(defn control-present? [{params :params}]
(if-let [control-key (:control params)]
(= control-key (configuration/property "control.key"))
false))
(defn check-credentials [{params :params}]
(and (= (:user params) (configuration/property "control.user"))
(= (:pass params) (configuration/property "control.pass"))))
(defn add-headers [response-body & {:keys [status] :or {status 200}}]
{:status 200
:headers {"Content-Type" "text/html;charset=utf-8"}
:body response-body})
(defn add-cookies [cookies response-body]
(assoc response-body :cookies cookies))
(defn echo-handler [request]
(add-headers (str request)))
(defn root-handler [request]
(add-headers (views/render (views/index-template))))
(defn authorization-handler [request]
(fn [request]
(let [session-id (java.util.UUID/randomUUID)]
(add-cookies {"session-id" {:value session-id :max-age 3600}}
(do
(if (and (control-present? request) (check-credentials request))
(let [ip (:remote-addr request)]
(sessions/add-session {:id session-id :ip ip})))
(root-handler request))))))
(defn ask-authorization? [{cookies :cookies :as request}]
(nil? (cookies "session-id")))
(defn has-permissions? [{cookies :cookies :as request}]
(if-let [session-id-string (:value (cookies "session-id"))]
(try
(let [session-id (java.util.UUID/fromString session-id-string)]
(if-let [session (sessions/get-session session-id)]
(= (:remote-addr request) (:ip session))
false))
(catch IllegalArgumentException e
false))
false))
(defn i404-handler [request]
(add-headers (views/render (views/not-found-template))
:status 404))
(defn thread-dispatching-middleware [handler]
(fn [request]
(let [{params :params} request]
(try
(if-let [thread-param #spy/t (:thread params)]
(let [tn (Integer/parseInt thread-param)]
(handler (assoc-in request [:params :thread] tn)))
(i404-handler request))
(catch NumberFormatException e
(i404-handler request))))))
(defn board-dispatching-middleware [handler]
(fn [request]
(let [{params :params} request
board-param (:board params)]
(if-let [bk ({"a" :a "c" :c} board-param)]
(handler (assoc-in request [:params :board] bk))
(i404-handler request)))))
(defn control-middleware [handler]
(fn [{params :params :as request}]
(if (control-present? request)
(if (ask-authorization? request)
(add-headers (views/render (views/authorization-template {:key (:control params)})))
(if (has-permissions? request)
(handler (assoc request :control {:permitted true :key (:control params)}))
(handler request)))
(handler request))))
(defn board-request-dispatcher [request board]
(add-headers
(views/render
(views/board-template
(storage/threads board)
{:control (:control request)
:board (name board)
:post-url (str "/board/" (name board) "/thread/new")
:post-header "[start a thread]"}))))
(def board-handler
(control-middleware
(board-dispatching-middleware
(fn [request]
(let [{params :params} request
board (:board params)]
(board-request-dispatcher request board))))))
(defn thread-request-dispatcher [request board thread]
(if-let [thread-model (storage/thread board thread)]
(add-headers
(views/render
(views/thread-template
thread-model
{:control (:control request)
:thread thread
:board board
:post-url (str "/board/" (name board) "/thread/" thread "/new")
:post-header "[post a reply]"})))
(i404-handler request)))
(def thread-handler
(control-middleware
(board-dispatching-middleware
(thread-dispatching-middleware
(fn [request]
(let [{params :params} request
thread (:thread params)
board (:board params)]
(thread-request-dispatcher request board thread)))))))
(defn text->html [text]
(-> (hiccup/h text)
(string/replace #"(?im)^(.+)\s*$" "$1<br/>")
(string/replace #"\s" " ")))
(def new-thread-handler
(board-dispatching-middleware
(fn [request]
(let [{params :params} request
board (:board params)
title (:title params)
text (:text params)]
(if (not (string/blank? text))
(do
(storage/post-thread board {:title (hiccup/h title) :contents (text->html text) :ip (:remote-addr request)})
(response/redirect-after-post (str "/board/" (name board))))
(add-headers
(views/render
(views/action-not-allowed-template {:action "empty post"}))))))))
(def new-post-handler
(board-dispatching-middleware
(thread-dispatching-middleware
(fn [request]
(let [{params :params} request
board (:board params)
thread (:thread params)
title (:title params)
text (:text params)]
(if (not (string/blank? text))
(do
(storage/post-reply board thread {:title (hiccup/h title) :contents (text->html text) :ip (:remote-addr request)})
(response/redirect-after-post (str "/board/" (name board) "/thread/" thread)))
(add-headers
(views/render
(views/action-not-allowed-template {:action "empty post"})))))))))
(def hide-post-handler
(control-middleware
(board-dispatching-middleware
(fn [{params :params :as request}]
(try
(if-let [number-param (:number params)]
(let [number (Integer/parseInt number-param)
board (:board params)
redirect-param (:redirect params)
control (:control request)]
(if (:permitted control)
(storage/hide-post board number))
(if redirect-param
(let [redirect (Integer/parseInt redirect-param)]
(thread-request-dispatcher request board redirect))
(board-request-dispatcher request board)))
(i404-handler request))
(catch NumberFormatException e
(i404-handler request)))))))
(def faq-handler
(fn [request]
(add-headers
(views/render
(views/faq-template)))))
(defroutes app-routes
(GET "/" [] root-handler)
(GET "/faq" [] faq-handler)
(GET "/board/:board" [board] board-handler)
(GET "/board/:board/:page" [board page] board-handler)
(GET "/board/:board/thread/:thread" [board thread] thread-handler)
(GET "/board/:board/control/hide/:number" [board number] hide-post-handler)
(POST "/auth" [] authorization-handler)
(POST "/board/:board/thread/new" [board] new-thread-handler)
(POST "/board/:board/thread/:thread/new" [board thread] new-post-handler)
(routes/resources "/static")
(routes/not-found i404-handler))
(def app-handler
(handler/site app-routes))
(defn app-init []
(sessions/init-session-store)
(configuration/load-configuration)
(storage/init-storage))
(defn -main [& args]
(app-init)
(run-jetty-async #'app-handler {:join? true :port 3000}))
(comment
(def jetty-instance (run-jetty-async #'app-handler {:join? false :port 3000}))
(.stop jetty-instance))
| 75823 | ;; Copyright (c) 2015, <NAME> <<EMAIL>>
;; Code is published under BSD 2-clause license
(ns illya.app
(:gen-class)
(:use compojure.core)
(:require
[illya.views :as views]
[illya.storage :as storage]
[illya.config :as configuration]
[illya.sessions :as sessions]
[ring.adapter.jetty-async :refer [run-jetty-async]]
[compojure.route :as routes]
[compojure.handler :as handler]
[ring.util.response :as response]
[clojure.string :as string]
[spyscope.core :as spy]
[hiccup.core :as hiccup :refer [h]]))
(defn control-present? [{params :params}]
(if-let [control-key (:control params)]
(= control-key (configuration/property "control.key"))
false))
(defn check-credentials [{params :params}]
(and (= (:user params) (configuration/property "control.user"))
(= (:pass params) (configuration/property "control.pass"))))
(defn add-headers [response-body & {:keys [status] :or {status 200}}]
{:status 200
:headers {"Content-Type" "text/html;charset=utf-8"}
:body response-body})
(defn add-cookies [cookies response-body]
(assoc response-body :cookies cookies))
(defn echo-handler [request]
(add-headers (str request)))
(defn root-handler [request]
(add-headers (views/render (views/index-template))))
(defn authorization-handler [request]
(fn [request]
(let [session-id (java.util.UUID/randomUUID)]
(add-cookies {"session-id" {:value session-id :max-age 3600}}
(do
(if (and (control-present? request) (check-credentials request))
(let [ip (:remote-addr request)]
(sessions/add-session {:id session-id :ip ip})))
(root-handler request))))))
(defn ask-authorization? [{cookies :cookies :as request}]
(nil? (cookies "session-id")))
(defn has-permissions? [{cookies :cookies :as request}]
(if-let [session-id-string (:value (cookies "session-id"))]
(try
(let [session-id (java.util.UUID/fromString session-id-string)]
(if-let [session (sessions/get-session session-id)]
(= (:remote-addr request) (:ip session))
false))
(catch IllegalArgumentException e
false))
false))
(defn i404-handler [request]
(add-headers (views/render (views/not-found-template))
:status 404))
(defn thread-dispatching-middleware [handler]
(fn [request]
(let [{params :params} request]
(try
(if-let [thread-param #spy/t (:thread params)]
(let [tn (Integer/parseInt thread-param)]
(handler (assoc-in request [:params :thread] tn)))
(i404-handler request))
(catch NumberFormatException e
(i404-handler request))))))
(defn board-dispatching-middleware [handler]
(fn [request]
(let [{params :params} request
board-param (:board params)]
(if-let [bk ({"a" :a "c" :c} board-param)]
(handler (assoc-in request [:params :board] bk))
(i404-handler request)))))
(defn control-middleware [handler]
(fn [{params :params :as request}]
(if (control-present? request)
(if (ask-authorization? request)
(add-headers (views/render (views/authorization-template {:key (:control params)})))
(if (has-permissions? request)
(handler (assoc request :control {:permitted true :key (:control params)}))
(handler request)))
(handler request))))
(defn board-request-dispatcher [request board]
(add-headers
(views/render
(views/board-template
(storage/threads board)
{:control (:control request)
:board (name board)
:post-url (str "/board/" (name board) "/thread/new")
:post-header "[start a thread]"}))))
(def board-handler
(control-middleware
(board-dispatching-middleware
(fn [request]
(let [{params :params} request
board (:board params)]
(board-request-dispatcher request board))))))
(defn thread-request-dispatcher [request board thread]
(if-let [thread-model (storage/thread board thread)]
(add-headers
(views/render
(views/thread-template
thread-model
{:control (:control request)
:thread thread
:board board
:post-url (str "/board/" (name board) "/thread/" thread "/new")
:post-header "[post a reply]"})))
(i404-handler request)))
(def thread-handler
(control-middleware
(board-dispatching-middleware
(thread-dispatching-middleware
(fn [request]
(let [{params :params} request
thread (:thread params)
board (:board params)]
(thread-request-dispatcher request board thread)))))))
(defn text->html [text]
(-> (hiccup/h text)
(string/replace #"(?im)^(.+)\s*$" "$1<br/>")
(string/replace #"\s" " ")))
(def new-thread-handler
(board-dispatching-middleware
(fn [request]
(let [{params :params} request
board (:board params)
title (:title params)
text (:text params)]
(if (not (string/blank? text))
(do
(storage/post-thread board {:title (hiccup/h title) :contents (text->html text) :ip (:remote-addr request)})
(response/redirect-after-post (str "/board/" (name board))))
(add-headers
(views/render
(views/action-not-allowed-template {:action "empty post"}))))))))
(def new-post-handler
(board-dispatching-middleware
(thread-dispatching-middleware
(fn [request]
(let [{params :params} request
board (:board params)
thread (:thread params)
title (:title params)
text (:text params)]
(if (not (string/blank? text))
(do
(storage/post-reply board thread {:title (hiccup/h title) :contents (text->html text) :ip (:remote-addr request)})
(response/redirect-after-post (str "/board/" (name board) "/thread/" thread)))
(add-headers
(views/render
(views/action-not-allowed-template {:action "empty post"})))))))))
(def hide-post-handler
(control-middleware
(board-dispatching-middleware
(fn [{params :params :as request}]
(try
(if-let [number-param (:number params)]
(let [number (Integer/parseInt number-param)
board (:board params)
redirect-param (:redirect params)
control (:control request)]
(if (:permitted control)
(storage/hide-post board number))
(if redirect-param
(let [redirect (Integer/parseInt redirect-param)]
(thread-request-dispatcher request board redirect))
(board-request-dispatcher request board)))
(i404-handler request))
(catch NumberFormatException e
(i404-handler request)))))))
(def faq-handler
(fn [request]
(add-headers
(views/render
(views/faq-template)))))
(defroutes app-routes
(GET "/" [] root-handler)
(GET "/faq" [] faq-handler)
(GET "/board/:board" [board] board-handler)
(GET "/board/:board/:page" [board page] board-handler)
(GET "/board/:board/thread/:thread" [board thread] thread-handler)
(GET "/board/:board/control/hide/:number" [board number] hide-post-handler)
(POST "/auth" [] authorization-handler)
(POST "/board/:board/thread/new" [board] new-thread-handler)
(POST "/board/:board/thread/:thread/new" [board thread] new-post-handler)
(routes/resources "/static")
(routes/not-found i404-handler))
(def app-handler
(handler/site app-routes))
(defn app-init []
(sessions/init-session-store)
(configuration/load-configuration)
(storage/init-storage))
(defn -main [& args]
(app-init)
(run-jetty-async #'app-handler {:join? true :port 3000}))
(comment
(def jetty-instance (run-jetty-async #'app-handler {:join? false :port 3000}))
(.stop jetty-instance))
| true | ;; Copyright (c) 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Code is published under BSD 2-clause license
(ns illya.app
(:gen-class)
(:use compojure.core)
(:require
[illya.views :as views]
[illya.storage :as storage]
[illya.config :as configuration]
[illya.sessions :as sessions]
[ring.adapter.jetty-async :refer [run-jetty-async]]
[compojure.route :as routes]
[compojure.handler :as handler]
[ring.util.response :as response]
[clojure.string :as string]
[spyscope.core :as spy]
[hiccup.core :as hiccup :refer [h]]))
(defn control-present? [{params :params}]
(if-let [control-key (:control params)]
(= control-key (configuration/property "control.key"))
false))
(defn check-credentials [{params :params}]
(and (= (:user params) (configuration/property "control.user"))
(= (:pass params) (configuration/property "control.pass"))))
(defn add-headers [response-body & {:keys [status] :or {status 200}}]
{:status 200
:headers {"Content-Type" "text/html;charset=utf-8"}
:body response-body})
(defn add-cookies [cookies response-body]
(assoc response-body :cookies cookies))
(defn echo-handler [request]
(add-headers (str request)))
(defn root-handler [request]
(add-headers (views/render (views/index-template))))
(defn authorization-handler [request]
(fn [request]
(let [session-id (java.util.UUID/randomUUID)]
(add-cookies {"session-id" {:value session-id :max-age 3600}}
(do
(if (and (control-present? request) (check-credentials request))
(let [ip (:remote-addr request)]
(sessions/add-session {:id session-id :ip ip})))
(root-handler request))))))
(defn ask-authorization? [{cookies :cookies :as request}]
(nil? (cookies "session-id")))
(defn has-permissions? [{cookies :cookies :as request}]
(if-let [session-id-string (:value (cookies "session-id"))]
(try
(let [session-id (java.util.UUID/fromString session-id-string)]
(if-let [session (sessions/get-session session-id)]
(= (:remote-addr request) (:ip session))
false))
(catch IllegalArgumentException e
false))
false))
(defn i404-handler [request]
(add-headers (views/render (views/not-found-template))
:status 404))
(defn thread-dispatching-middleware [handler]
(fn [request]
(let [{params :params} request]
(try
(if-let [thread-param #spy/t (:thread params)]
(let [tn (Integer/parseInt thread-param)]
(handler (assoc-in request [:params :thread] tn)))
(i404-handler request))
(catch NumberFormatException e
(i404-handler request))))))
(defn board-dispatching-middleware [handler]
(fn [request]
(let [{params :params} request
board-param (:board params)]
(if-let [bk ({"a" :a "c" :c} board-param)]
(handler (assoc-in request [:params :board] bk))
(i404-handler request)))))
(defn control-middleware [handler]
(fn [{params :params :as request}]
(if (control-present? request)
(if (ask-authorization? request)
(add-headers (views/render (views/authorization-template {:key (:control params)})))
(if (has-permissions? request)
(handler (assoc request :control {:permitted true :key (:control params)}))
(handler request)))
(handler request))))
(defn board-request-dispatcher [request board]
(add-headers
(views/render
(views/board-template
(storage/threads board)
{:control (:control request)
:board (name board)
:post-url (str "/board/" (name board) "/thread/new")
:post-header "[start a thread]"}))))
(def board-handler
(control-middleware
(board-dispatching-middleware
(fn [request]
(let [{params :params} request
board (:board params)]
(board-request-dispatcher request board))))))
(defn thread-request-dispatcher [request board thread]
(if-let [thread-model (storage/thread board thread)]
(add-headers
(views/render
(views/thread-template
thread-model
{:control (:control request)
:thread thread
:board board
:post-url (str "/board/" (name board) "/thread/" thread "/new")
:post-header "[post a reply]"})))
(i404-handler request)))
(def thread-handler
(control-middleware
(board-dispatching-middleware
(thread-dispatching-middleware
(fn [request]
(let [{params :params} request
thread (:thread params)
board (:board params)]
(thread-request-dispatcher request board thread)))))))
(defn text->html [text]
(-> (hiccup/h text)
(string/replace #"(?im)^(.+)\s*$" "$1<br/>")
(string/replace #"\s" " ")))
(def new-thread-handler
(board-dispatching-middleware
(fn [request]
(let [{params :params} request
board (:board params)
title (:title params)
text (:text params)]
(if (not (string/blank? text))
(do
(storage/post-thread board {:title (hiccup/h title) :contents (text->html text) :ip (:remote-addr request)})
(response/redirect-after-post (str "/board/" (name board))))
(add-headers
(views/render
(views/action-not-allowed-template {:action "empty post"}))))))))
(def new-post-handler
(board-dispatching-middleware
(thread-dispatching-middleware
(fn [request]
(let [{params :params} request
board (:board params)
thread (:thread params)
title (:title params)
text (:text params)]
(if (not (string/blank? text))
(do
(storage/post-reply board thread {:title (hiccup/h title) :contents (text->html text) :ip (:remote-addr request)})
(response/redirect-after-post (str "/board/" (name board) "/thread/" thread)))
(add-headers
(views/render
(views/action-not-allowed-template {:action "empty post"})))))))))
(def hide-post-handler
(control-middleware
(board-dispatching-middleware
(fn [{params :params :as request}]
(try
(if-let [number-param (:number params)]
(let [number (Integer/parseInt number-param)
board (:board params)
redirect-param (:redirect params)
control (:control request)]
(if (:permitted control)
(storage/hide-post board number))
(if redirect-param
(let [redirect (Integer/parseInt redirect-param)]
(thread-request-dispatcher request board redirect))
(board-request-dispatcher request board)))
(i404-handler request))
(catch NumberFormatException e
(i404-handler request)))))))
(def faq-handler
(fn [request]
(add-headers
(views/render
(views/faq-template)))))
(defroutes app-routes
(GET "/" [] root-handler)
(GET "/faq" [] faq-handler)
(GET "/board/:board" [board] board-handler)
(GET "/board/:board/:page" [board page] board-handler)
(GET "/board/:board/thread/:thread" [board thread] thread-handler)
(GET "/board/:board/control/hide/:number" [board number] hide-post-handler)
(POST "/auth" [] authorization-handler)
(POST "/board/:board/thread/new" [board] new-thread-handler)
(POST "/board/:board/thread/:thread/new" [board thread] new-post-handler)
(routes/resources "/static")
(routes/not-found i404-handler))
(def app-handler
(handler/site app-routes))
(defn app-init []
(sessions/init-session-store)
(configuration/load-configuration)
(storage/init-storage))
(defn -main [& args]
(app-init)
(run-jetty-async #'app-handler {:join? true :port 3000}))
(comment
(def jetty-instance (run-jetty-async #'app-handler {:join? false :port 3000}))
(.stop jetty-instance))
|
[
{
"context": "unction (cl-format) for Clojure\n\n; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 131,
"score": 0.9998801946640015,
"start": 120,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "ice, or any other, from this software.\n\n;; Author: Tom Faulhaber\n;; April 3, 2009\n\n(ns \n ^{:author \"Tom Faulhab",
"end": 590,
"score": 0.9998971819877625,
"start": 577,
"tag": "NAME",
"value": "Tom Faulhaber"
},
{
"context": "m Faulhaber\n;; April 3, 2009\n\n(ns \n ^{:author \"Tom Faulhaber\",\n :doc \"A Pretty Printer for Clojure\n\ncloju",
"end": 642,
"score": 0.9998964071273804,
"start": 629,
"tag": "NAME",
"value": "Tom Faulhaber"
}
] | Neptune/bin/Debug/clojure/pprint.clj | yasir2000/Neptune- | 14 | ;;; pprint.clj -- Pretty printer and Common Lisp compatible format function (cl-format) for Clojure
; 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.
;; Author: Tom Faulhaber
;; April 3, 2009
(ns
^{:author "Tom Faulhaber",
:doc "A Pretty Printer for Clojure
clojure.pprint implements a flexible system for printing structured data
in a pleasing, easy-to-understand format. Basic use of the pretty printer is
simple, just call pprint instead of println. More advanced users can use
the building blocks provided to create custom output formats.
Out of the box, pprint supports a simple structured format for basic data
and a specialized format for Clojure source code. More advanced formats,
including formats that don't look like Clojure data at all like XML and
JSON, can be rendered by creating custom dispatch functions.
In addition to the pprint function, this module contains cl-format, a text
formatting function which is fully compatible with the format function in
Common Lisp. Because pretty printing directives are directly integrated with
cl-format, it supports very concise custom dispatch. It also provides
a more powerful alternative to Clojure's standard format function.
See documentation for pprint and cl-format for more information or
complete documentation on the the clojure web site on github.",
:added "1.2"}
clojure.pprint
(:refer-clojure :exclude (deftype))
(:use [clojure.walk :only [walk]]))
(load "pprint/utilities")
(load "pprint/column_writer")
(load "pprint/pretty_writer")
(load "pprint/pprint_base")
(load "pprint/cl_format")
(load "pprint/dispatch")
(load "pprint/print_table")
nil
| 68030 | ;;; pprint.clj -- Pretty printer and Common Lisp compatible format function (cl-format) for Clojure
; 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.
;; Author: <NAME>
;; April 3, 2009
(ns
^{:author "<NAME>",
:doc "A Pretty Printer for Clojure
clojure.pprint implements a flexible system for printing structured data
in a pleasing, easy-to-understand format. Basic use of the pretty printer is
simple, just call pprint instead of println. More advanced users can use
the building blocks provided to create custom output formats.
Out of the box, pprint supports a simple structured format for basic data
and a specialized format for Clojure source code. More advanced formats,
including formats that don't look like Clojure data at all like XML and
JSON, can be rendered by creating custom dispatch functions.
In addition to the pprint function, this module contains cl-format, a text
formatting function which is fully compatible with the format function in
Common Lisp. Because pretty printing directives are directly integrated with
cl-format, it supports very concise custom dispatch. It also provides
a more powerful alternative to Clojure's standard format function.
See documentation for pprint and cl-format for more information or
complete documentation on the the clojure web site on github.",
:added "1.2"}
clojure.pprint
(:refer-clojure :exclude (deftype))
(:use [clojure.walk :only [walk]]))
(load "pprint/utilities")
(load "pprint/column_writer")
(load "pprint/pretty_writer")
(load "pprint/pprint_base")
(load "pprint/cl_format")
(load "pprint/dispatch")
(load "pprint/print_table")
nil
| true | ;;; pprint.clj -- Pretty printer and Common Lisp compatible format function (cl-format) for Clojure
; 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.
;; Author: PI:NAME:<NAME>END_PI
;; April 3, 2009
(ns
^{:author "PI:NAME:<NAME>END_PI",
:doc "A Pretty Printer for Clojure
clojure.pprint implements a flexible system for printing structured data
in a pleasing, easy-to-understand format. Basic use of the pretty printer is
simple, just call pprint instead of println. More advanced users can use
the building blocks provided to create custom output formats.
Out of the box, pprint supports a simple structured format for basic data
and a specialized format for Clojure source code. More advanced formats,
including formats that don't look like Clojure data at all like XML and
JSON, can be rendered by creating custom dispatch functions.
In addition to the pprint function, this module contains cl-format, a text
formatting function which is fully compatible with the format function in
Common Lisp. Because pretty printing directives are directly integrated with
cl-format, it supports very concise custom dispatch. It also provides
a more powerful alternative to Clojure's standard format function.
See documentation for pprint and cl-format for more information or
complete documentation on the the clojure web site on github.",
:added "1.2"}
clojure.pprint
(:refer-clojure :exclude (deftype))
(:use [clojure.walk :only [walk]]))
(load "pprint/utilities")
(load "pprint/column_writer")
(load "pprint/pretty_writer")
(load "pprint/pprint_base")
(load "pprint/cl_format")
(load "pprint/dispatch")
(load "pprint/print_table")
nil
|
[
{
"context": "; Copyright (C) 2008 - 2011 Stefan Marr <mail@stefan-marr.de>\n; \n; Permission is hereby g",
"end": 39,
"score": 0.9998854398727417,
"start": 28,
"tag": "NAME",
"value": "Stefan Marr"
},
{
"context": "; Copyright (C) 2008 - 2011 Stefan Marr <mail@stefan-marr.de>\n; \n; Permission is hereby granted, free of charg",
"end": 60,
"score": 0.999935507774353,
"start": 41,
"tag": "EMAIL",
"value": "mail@stefan-marr.de"
}
] | Clojure/src/snake/core.clj | smarr/Snake | 4 | ; Copyright (C) 2008 - 2011 Stefan Marr <mail@stefan-marr.de>
;
; 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 snake.core
(:use snake.input-receiver)
(:use snake.terminal-reader)
(:use snake.board)
(:use snake.player)
(:use snake.board-view)
(:use snake.game-elements)
(:use snake.game-master))
(let [human-player (create-human-player)
board (create-board :width 10
:height 10)
board-view (create-view board :x 4 :y 4)]
(start-terminal-reader human-player)
; initialize the view
(send board-view initialize-view)
(send board-view draw-borders)
; now start the actual game
(let [[game-over-promise heartbeat] (exec-game-master
board-view
board
:num-apples 5
:players [human-player])]
;; will block until the games is completed
(deref game-over-promise)
(.cancel heartbeat)
(println "GAME OVER")
(System/exit 0)))
| 36026 | ; Copyright (C) 2008 - 2011 <NAME> <<EMAIL>>
;
; 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 snake.core
(:use snake.input-receiver)
(:use snake.terminal-reader)
(:use snake.board)
(:use snake.player)
(:use snake.board-view)
(:use snake.game-elements)
(:use snake.game-master))
(let [human-player (create-human-player)
board (create-board :width 10
:height 10)
board-view (create-view board :x 4 :y 4)]
(start-terminal-reader human-player)
; initialize the view
(send board-view initialize-view)
(send board-view draw-borders)
; now start the actual game
(let [[game-over-promise heartbeat] (exec-game-master
board-view
board
:num-apples 5
:players [human-player])]
;; will block until the games is completed
(deref game-over-promise)
(.cancel heartbeat)
(println "GAME OVER")
(System/exit 0)))
| true | ; Copyright (C) 2008 - 2011 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>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 snake.core
(:use snake.input-receiver)
(:use snake.terminal-reader)
(:use snake.board)
(:use snake.player)
(:use snake.board-view)
(:use snake.game-elements)
(:use snake.game-master))
(let [human-player (create-human-player)
board (create-board :width 10
:height 10)
board-view (create-view board :x 4 :y 4)]
(start-terminal-reader human-player)
; initialize the view
(send board-view initialize-view)
(send board-view draw-borders)
; now start the actual game
(let [[game-over-promise heartbeat] (exec-game-master
board-view
board
:num-apples 5
:players [human-player])]
;; will block until the games is completed
(deref game-over-promise)
(.cancel heartbeat)
(println "GAME OVER")
(System/exit 0)))
|
[
{
"context": "ge, London, All rights reserved.\n;\n; Contributors: Jony Hudson\n;\n; Released under the MIT license..\n;\n\n(ns darwi",
"end": 134,
"score": 0.999744176864624,
"start": 123,
"tag": "NAME",
"value": "Jony Hudson"
}
] | src/darwin/evolution/transform.clj | drcode/darwin | 22 | ;
; This file is part of darwin.
;
; Copyright (C) 2014-, Imperial College, London, All rights reserved.
;
; Contributors: Jony Hudson
;
; Released under the MIT license..
;
(ns darwin.evolution.transform
"Functions for transforming individuals, and the population. These can be supplied to the EA
to perform non-EA transformations before scoring (see `darwin.evolution.core` for details.
This namespace contains general helper functions for constructing transformations, and generic
transformations that are representation independent. A given representation might implement more
specific transformations (think simplifying symbolic regression expressions, for instance)."
(:refer-clojure :exclude [rand rand-nth rand-int])
(:use [darwin.utility.random]))
;; * Helpers *
(defn apply-to-genotype
[func individual]
(assoc individual :genotype (func (:genotype individual))))
(defn apply-to-fraction-of-genotypes
"Apply a transformation to a randomly selected fraction of the population. The transformation will
be applied to the genotype of the individual. The rest of the information in the individual will be
preserved."
[transform fraction population]
(map
#(if (< (rand) fraction) ((partial apply-to-genotype transform) %) %)
population))
(defn apply-to-all-genotypes
"Apply a transformation to all of the population. The transformation will be applied to the genotype of
the individual. The rest of the information in the individual will be preserved."
[transform population]
(map (partial apply-to-genotype transform) population))
;; * Generic transformations *
(defn hill-descent
"Takes a genotype and applies the given tweak function, returns the new individual if it
scores better on the score-function, otherwise returns the individual. The tweak function and
the score function should operate on the genotype of the individual."
[tweak-function score-function genotype]
(let [tweaked (tweak-function genotype)
score (score-function genotype)
tweaked-score (score-function tweaked)]
(if (< tweaked-score score)
tweaked
genotype)))
| 57379 | ;
; This file is part of darwin.
;
; Copyright (C) 2014-, Imperial College, London, All rights reserved.
;
; Contributors: <NAME>
;
; Released under the MIT license..
;
(ns darwin.evolution.transform
"Functions for transforming individuals, and the population. These can be supplied to the EA
to perform non-EA transformations before scoring (see `darwin.evolution.core` for details.
This namespace contains general helper functions for constructing transformations, and generic
transformations that are representation independent. A given representation might implement more
specific transformations (think simplifying symbolic regression expressions, for instance)."
(:refer-clojure :exclude [rand rand-nth rand-int])
(:use [darwin.utility.random]))
;; * Helpers *
(defn apply-to-genotype
[func individual]
(assoc individual :genotype (func (:genotype individual))))
(defn apply-to-fraction-of-genotypes
"Apply a transformation to a randomly selected fraction of the population. The transformation will
be applied to the genotype of the individual. The rest of the information in the individual will be
preserved."
[transform fraction population]
(map
#(if (< (rand) fraction) ((partial apply-to-genotype transform) %) %)
population))
(defn apply-to-all-genotypes
"Apply a transformation to all of the population. The transformation will be applied to the genotype of
the individual. The rest of the information in the individual will be preserved."
[transform population]
(map (partial apply-to-genotype transform) population))
;; * Generic transformations *
(defn hill-descent
"Takes a genotype and applies the given tweak function, returns the new individual if it
scores better on the score-function, otherwise returns the individual. The tweak function and
the score function should operate on the genotype of the individual."
[tweak-function score-function genotype]
(let [tweaked (tweak-function genotype)
score (score-function genotype)
tweaked-score (score-function tweaked)]
(if (< tweaked-score score)
tweaked
genotype)))
| true | ;
; This file is part of darwin.
;
; Copyright (C) 2014-, Imperial College, London, All rights reserved.
;
; Contributors: PI:NAME:<NAME>END_PI
;
; Released under the MIT license..
;
(ns darwin.evolution.transform
"Functions for transforming individuals, and the population. These can be supplied to the EA
to perform non-EA transformations before scoring (see `darwin.evolution.core` for details.
This namespace contains general helper functions for constructing transformations, and generic
transformations that are representation independent. A given representation might implement more
specific transformations (think simplifying symbolic regression expressions, for instance)."
(:refer-clojure :exclude [rand rand-nth rand-int])
(:use [darwin.utility.random]))
;; * Helpers *
(defn apply-to-genotype
[func individual]
(assoc individual :genotype (func (:genotype individual))))
(defn apply-to-fraction-of-genotypes
"Apply a transformation to a randomly selected fraction of the population. The transformation will
be applied to the genotype of the individual. The rest of the information in the individual will be
preserved."
[transform fraction population]
(map
#(if (< (rand) fraction) ((partial apply-to-genotype transform) %) %)
population))
(defn apply-to-all-genotypes
"Apply a transformation to all of the population. The transformation will be applied to the genotype of
the individual. The rest of the information in the individual will be preserved."
[transform population]
(map (partial apply-to-genotype transform) population))
;; * Generic transformations *
(defn hill-descent
"Takes a genotype and applies the given tweak function, returns the new individual if it
scores better on the score-function, otherwise returns the individual. The tweak function and
the score function should operate on the genotype of the individual."
[tweak-function score-function genotype]
(let [tweaked (tweak-function genotype)
score (score-function genotype)
tweaked-score (score-function tweaked)]
(if (< tweaked-score score)
tweaked
genotype)))
|
[
{
"context": " \"token\" \"token-1\"}\n {\"delet",
"end": 1835,
"score": 0.7286048531532288,
"start": 1828,
"tag": "KEY",
"value": "token-1"
},
{
"context": " \"token\" \"token-3\"}\n {\"del",
"end": 2371,
"score": 0.6650509834289551,
"start": 2366,
"tag": "KEY",
"value": "token"
},
{
"context": " \"token\" \"token-3\"}\n {\"delet",
"end": 2373,
"score": 0.4707183837890625,
"start": 2372,
"tag": "PASSWORD",
"value": "3"
},
{
"context": " \"token\" \"token-4\"}\n {\"del",
"end": 2640,
"score": 0.7357791066169739,
"start": 2635,
"tag": "KEY",
"value": "token"
},
{
"context": " \"token\" \"token-4\"}\n {\"delet",
"end": 2642,
"score": 0.6096435189247131,
"start": 2641,
"tag": "PASSWORD",
"value": "4"
},
{
"context": " \"token\" \"token-E\"}\n {\"del",
"end": 2910,
"score": 0.6179472804069519,
"start": 2905,
"tag": "KEY",
"value": "token"
},
{
"context": " \"token\" \"token-E\"}\n {\"delet",
"end": 2912,
"score": 0.5475969314575195,
"start": 2911,
"tag": "PASSWORD",
"value": "E"
},
{
"context": " \"token\" \"token-6\"}])\n :store-token (fn [clust",
"end": 3180,
"score": 0.5889947414398193,
"start": 3175,
"tag": "KEY",
"value": "token"
},
{
"context": " \"token\" \"token-6\"}])\n :store-token (fn [cluster",
"end": 3182,
"score": 0.5818879008293152,
"start": 3181,
"tag": "PASSWORD",
"value": "6"
}
] | token-syncer/test/token_syncer/commands/sanitize_test.clj | geofft/waiter | 76 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; 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 token-syncer.commands.sanitize-test
(:require [clojure.string :as str]
[clojure.test :refer :all]
[token-syncer.cli :as cli]
[token-syncer.commands.sanitize :refer :all]
[token-syncer.utils :as utils])
(:import (java.util.regex Pattern)))
(deftest test-sanitize
(let [test-cluster-url "http://www.test-cluster.com"
limit 3
loaded-tokens-atom (atom #{})
stored-tokens-atom (atom #{})
waiter-api {:load-token (fn [cluster-url token]
(swap! loaded-tokens-atom conj token)
(is (= test-cluster-url cluster-url))
(when-not (= token "token-1")
{:description {"metric-group" token "name" token}
:token-etag (str "etag-" token)}))
:load-token-list (fn [cluster-url]
(is (= test-cluster-url cluster-url))
[{"etag" "etag-token-1"
"last-update-time" (utils/millis->iso8601 10000)
"token" "token-1"}
{"deleted" true
"etag" "etag-token-B"
"last-update-time" (utils/millis->iso8601 20000)
"token" "token-B"}
{"deleted" true
"etag" "etag-token-3"
"last-update-time" (utils/millis->iso8601 30000)
"token" "token-3"}
{"deleted" true
"etag" "etag-token-4"
"last-update-time" (utils/millis->iso8601 40000)
"token" "token-4"}
{"deleted" false
"etag" "etag-token-E"
"last-update-time" (utils/millis->iso8601 50000)
"token" "token-E"}
{"deleted" false
"etag" "etag-token-6"
"last-update-time" (utils/millis->iso8601 60000)
"token" "token-6"}])
:store-token (fn [cluster-url token token-etag description]
(swap! stored-tokens-atom conj token)
(is (= test-cluster-url cluster-url))
(is (= (str "etag-" token) token-etag))
(is (= {"metric-group" token "name" token} description))
{:headers {"etag" (str token-etag (when (= token "token-3") "-new"))}
:status 200})}
regex (re-pattern "token-\\d+")
actual-result (sanitize-tokens waiter-api test-cluster-url limit regex)]
(is (= {:missing #{"token-1"}
:processed #{"token-1" "token-3" "token-4"}
:updated #{"token-3"}}
actual-result))
(is (= #{"token-1" "token-3" "token-4"} @loaded-tokens-atom))
(is (= #{"token-3" "token-4"} @stored-tokens-atom))))
(deftest test-sanitize-tokens-config
(let [test-command-config (assoc sanitize-tokens-config :command-name "test-command")
waiter-api {:load-token (constantly {})
:load-token-list (constantly {})}
context {:waiter-api waiter-api}]
(let [args []]
(is (= {:exit-code 1
:message "test-command: expected one argument URL, provided 0: []"}
(cli/process-command test-command-config context args))))
(with-out-str
(let [args ["-h"]]
(is (= {:exit-code 0
:message "test-command: displayed documentation"}
(cli/process-command test-command-config context args)))))
(let [args ["some-file.txt" "cluster-1.com"]]
(is (= {:exit-code 1
:message "test-command: expected one argument URL, provided 2: [\"some-file.txt\" \"cluster-1.com\"]"}
(cli/process-command test-command-config context args))))
(let [limit-input (str 200000)
args ["--limit" limit-input "cluster-1.com"]]
(is (= {:data [(str "Failed to validate \"--limit " limit-input "\": "
"Must be between 1 and 10000")]
:exit-code 1
:message "test-command: error in parsing arguments"}
(cli/process-command test-command-config context args))))
(let [regex-input 200000
args ["--regex" regex-input "cluster-1.com"]
actual-result (cli/process-command test-command-config context args)]
(is (= {:exit-code 1
:message "test-command: error in parsing arguments"}
(dissoc actual-result :data)))
(is (str/includes? (-> actual-result :data first) (str "Error while parsing option \"--regex " regex-input "\": ")))
(is (str/includes? (-> actual-result :data first) "java.lang.ClassCastException"))
(is (str/includes? (-> actual-result :data first) "java.lang.Long"))
(is (str/includes? (-> actual-result :data first) "java.lang.String")))
(let [cluster-url "http://cluster-1.com"
make-sanitize-tokens (fn [invocation-promise]
(fn [in-waiter-api in-cluster-url count-limit token-regex]
(is (= waiter-api in-waiter-api))
(is (= cluster-url in-cluster-url))
(is (number? count-limit))
(is (instance? Pattern token-regex))
(deliver invocation-promise ::invoked)))]
(let [args [cluster-url]
invocation-promise (promise)]
(with-redefs [sanitize-tokens (make-sanitize-tokens invocation-promise)]
(is (= {:exit-code 0
:message "test-command: exiting with code 0"}
(cli/process-command test-command-config context args)))
(is (= ::invoked (deref invocation-promise 0 ::un-initialized)))))
(let [args ["--limit" (str 100) "--regex" ".*foo.*" cluster-url]
invocation-promise (promise)]
(with-redefs [sanitize-tokens (make-sanitize-tokens invocation-promise)]
(is (= {:exit-code 0
:message "test-command: exiting with code 0"}
(cli/process-command test-command-config context args)))
(is (= ::invoked (deref invocation-promise 0 ::un-initialized))))))))
| 11545 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; 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 token-syncer.commands.sanitize-test
(:require [clojure.string :as str]
[clojure.test :refer :all]
[token-syncer.cli :as cli]
[token-syncer.commands.sanitize :refer :all]
[token-syncer.utils :as utils])
(:import (java.util.regex Pattern)))
(deftest test-sanitize
(let [test-cluster-url "http://www.test-cluster.com"
limit 3
loaded-tokens-atom (atom #{})
stored-tokens-atom (atom #{})
waiter-api {:load-token (fn [cluster-url token]
(swap! loaded-tokens-atom conj token)
(is (= test-cluster-url cluster-url))
(when-not (= token "token-1")
{:description {"metric-group" token "name" token}
:token-etag (str "etag-" token)}))
:load-token-list (fn [cluster-url]
(is (= test-cluster-url cluster-url))
[{"etag" "etag-token-1"
"last-update-time" (utils/millis->iso8601 10000)
"token" "<KEY>"}
{"deleted" true
"etag" "etag-token-B"
"last-update-time" (utils/millis->iso8601 20000)
"token" "token-B"}
{"deleted" true
"etag" "etag-token-3"
"last-update-time" (utils/millis->iso8601 30000)
"token" "<KEY>-<PASSWORD>"}
{"deleted" true
"etag" "etag-token-4"
"last-update-time" (utils/millis->iso8601 40000)
"token" "<KEY>-<PASSWORD>"}
{"deleted" false
"etag" "etag-token-E"
"last-update-time" (utils/millis->iso8601 50000)
"token" "<KEY>-<PASSWORD>"}
{"deleted" false
"etag" "etag-token-6"
"last-update-time" (utils/millis->iso8601 60000)
"token" "<KEY>-<PASSWORD>"}])
:store-token (fn [cluster-url token token-etag description]
(swap! stored-tokens-atom conj token)
(is (= test-cluster-url cluster-url))
(is (= (str "etag-" token) token-etag))
(is (= {"metric-group" token "name" token} description))
{:headers {"etag" (str token-etag (when (= token "token-3") "-new"))}
:status 200})}
regex (re-pattern "token-\\d+")
actual-result (sanitize-tokens waiter-api test-cluster-url limit regex)]
(is (= {:missing #{"token-1"}
:processed #{"token-1" "token-3" "token-4"}
:updated #{"token-3"}}
actual-result))
(is (= #{"token-1" "token-3" "token-4"} @loaded-tokens-atom))
(is (= #{"token-3" "token-4"} @stored-tokens-atom))))
(deftest test-sanitize-tokens-config
(let [test-command-config (assoc sanitize-tokens-config :command-name "test-command")
waiter-api {:load-token (constantly {})
:load-token-list (constantly {})}
context {:waiter-api waiter-api}]
(let [args []]
(is (= {:exit-code 1
:message "test-command: expected one argument URL, provided 0: []"}
(cli/process-command test-command-config context args))))
(with-out-str
(let [args ["-h"]]
(is (= {:exit-code 0
:message "test-command: displayed documentation"}
(cli/process-command test-command-config context args)))))
(let [args ["some-file.txt" "cluster-1.com"]]
(is (= {:exit-code 1
:message "test-command: expected one argument URL, provided 2: [\"some-file.txt\" \"cluster-1.com\"]"}
(cli/process-command test-command-config context args))))
(let [limit-input (str 200000)
args ["--limit" limit-input "cluster-1.com"]]
(is (= {:data [(str "Failed to validate \"--limit " limit-input "\": "
"Must be between 1 and 10000")]
:exit-code 1
:message "test-command: error in parsing arguments"}
(cli/process-command test-command-config context args))))
(let [regex-input 200000
args ["--regex" regex-input "cluster-1.com"]
actual-result (cli/process-command test-command-config context args)]
(is (= {:exit-code 1
:message "test-command: error in parsing arguments"}
(dissoc actual-result :data)))
(is (str/includes? (-> actual-result :data first) (str "Error while parsing option \"--regex " regex-input "\": ")))
(is (str/includes? (-> actual-result :data first) "java.lang.ClassCastException"))
(is (str/includes? (-> actual-result :data first) "java.lang.Long"))
(is (str/includes? (-> actual-result :data first) "java.lang.String")))
(let [cluster-url "http://cluster-1.com"
make-sanitize-tokens (fn [invocation-promise]
(fn [in-waiter-api in-cluster-url count-limit token-regex]
(is (= waiter-api in-waiter-api))
(is (= cluster-url in-cluster-url))
(is (number? count-limit))
(is (instance? Pattern token-regex))
(deliver invocation-promise ::invoked)))]
(let [args [cluster-url]
invocation-promise (promise)]
(with-redefs [sanitize-tokens (make-sanitize-tokens invocation-promise)]
(is (= {:exit-code 0
:message "test-command: exiting with code 0"}
(cli/process-command test-command-config context args)))
(is (= ::invoked (deref invocation-promise 0 ::un-initialized)))))
(let [args ["--limit" (str 100) "--regex" ".*foo.*" cluster-url]
invocation-promise (promise)]
(with-redefs [sanitize-tokens (make-sanitize-tokens invocation-promise)]
(is (= {:exit-code 0
:message "test-command: exiting with code 0"}
(cli/process-command test-command-config context args)))
(is (= ::invoked (deref invocation-promise 0 ::un-initialized))))))))
| true | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; 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 token-syncer.commands.sanitize-test
(:require [clojure.string :as str]
[clojure.test :refer :all]
[token-syncer.cli :as cli]
[token-syncer.commands.sanitize :refer :all]
[token-syncer.utils :as utils])
(:import (java.util.regex Pattern)))
(deftest test-sanitize
(let [test-cluster-url "http://www.test-cluster.com"
limit 3
loaded-tokens-atom (atom #{})
stored-tokens-atom (atom #{})
waiter-api {:load-token (fn [cluster-url token]
(swap! loaded-tokens-atom conj token)
(is (= test-cluster-url cluster-url))
(when-not (= token "token-1")
{:description {"metric-group" token "name" token}
:token-etag (str "etag-" token)}))
:load-token-list (fn [cluster-url]
(is (= test-cluster-url cluster-url))
[{"etag" "etag-token-1"
"last-update-time" (utils/millis->iso8601 10000)
"token" "PI:KEY:<KEY>END_PI"}
{"deleted" true
"etag" "etag-token-B"
"last-update-time" (utils/millis->iso8601 20000)
"token" "token-B"}
{"deleted" true
"etag" "etag-token-3"
"last-update-time" (utils/millis->iso8601 30000)
"token" "PI:KEY:<KEY>END_PI-PI:PASSWORD:<PASSWORD>END_PI"}
{"deleted" true
"etag" "etag-token-4"
"last-update-time" (utils/millis->iso8601 40000)
"token" "PI:KEY:<KEY>END_PI-PI:PASSWORD:<PASSWORD>END_PI"}
{"deleted" false
"etag" "etag-token-E"
"last-update-time" (utils/millis->iso8601 50000)
"token" "PI:KEY:<KEY>END_PI-PI:PASSWORD:<PASSWORD>END_PI"}
{"deleted" false
"etag" "etag-token-6"
"last-update-time" (utils/millis->iso8601 60000)
"token" "PI:KEY:<KEY>END_PI-PI:PASSWORD:<PASSWORD>END_PI"}])
:store-token (fn [cluster-url token token-etag description]
(swap! stored-tokens-atom conj token)
(is (= test-cluster-url cluster-url))
(is (= (str "etag-" token) token-etag))
(is (= {"metric-group" token "name" token} description))
{:headers {"etag" (str token-etag (when (= token "token-3") "-new"))}
:status 200})}
regex (re-pattern "token-\\d+")
actual-result (sanitize-tokens waiter-api test-cluster-url limit regex)]
(is (= {:missing #{"token-1"}
:processed #{"token-1" "token-3" "token-4"}
:updated #{"token-3"}}
actual-result))
(is (= #{"token-1" "token-3" "token-4"} @loaded-tokens-atom))
(is (= #{"token-3" "token-4"} @stored-tokens-atom))))
(deftest test-sanitize-tokens-config
(let [test-command-config (assoc sanitize-tokens-config :command-name "test-command")
waiter-api {:load-token (constantly {})
:load-token-list (constantly {})}
context {:waiter-api waiter-api}]
(let [args []]
(is (= {:exit-code 1
:message "test-command: expected one argument URL, provided 0: []"}
(cli/process-command test-command-config context args))))
(with-out-str
(let [args ["-h"]]
(is (= {:exit-code 0
:message "test-command: displayed documentation"}
(cli/process-command test-command-config context args)))))
(let [args ["some-file.txt" "cluster-1.com"]]
(is (= {:exit-code 1
:message "test-command: expected one argument URL, provided 2: [\"some-file.txt\" \"cluster-1.com\"]"}
(cli/process-command test-command-config context args))))
(let [limit-input (str 200000)
args ["--limit" limit-input "cluster-1.com"]]
(is (= {:data [(str "Failed to validate \"--limit " limit-input "\": "
"Must be between 1 and 10000")]
:exit-code 1
:message "test-command: error in parsing arguments"}
(cli/process-command test-command-config context args))))
(let [regex-input 200000
args ["--regex" regex-input "cluster-1.com"]
actual-result (cli/process-command test-command-config context args)]
(is (= {:exit-code 1
:message "test-command: error in parsing arguments"}
(dissoc actual-result :data)))
(is (str/includes? (-> actual-result :data first) (str "Error while parsing option \"--regex " regex-input "\": ")))
(is (str/includes? (-> actual-result :data first) "java.lang.ClassCastException"))
(is (str/includes? (-> actual-result :data first) "java.lang.Long"))
(is (str/includes? (-> actual-result :data first) "java.lang.String")))
(let [cluster-url "http://cluster-1.com"
make-sanitize-tokens (fn [invocation-promise]
(fn [in-waiter-api in-cluster-url count-limit token-regex]
(is (= waiter-api in-waiter-api))
(is (= cluster-url in-cluster-url))
(is (number? count-limit))
(is (instance? Pattern token-regex))
(deliver invocation-promise ::invoked)))]
(let [args [cluster-url]
invocation-promise (promise)]
(with-redefs [sanitize-tokens (make-sanitize-tokens invocation-promise)]
(is (= {:exit-code 0
:message "test-command: exiting with code 0"}
(cli/process-command test-command-config context args)))
(is (= ::invoked (deref invocation-promise 0 ::un-initialized)))))
(let [args ["--limit" (str 100) "--regex" ".*foo.*" cluster-url]
invocation-promise (promise)]
(with-redefs [sanitize-tokens (make-sanitize-tokens invocation-promise)]
(is (= {:exit-code 0
:message "test-command: exiting with code 0"}
(cli/process-command test-command-config context args)))
(is (= ::invoked (deref invocation-promise 0 ::un-initialized))))))))
|
[
{
"context": "\"]\n [rm-hull/ring-cede \"0.1.0\"]]\n :scm {:url \"git@github.com:rm-hull/lindenmayer-systems.git\"}\n :ring {\n :",
"end": 632,
"score": 0.9986294507980347,
"start": 618,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": "/ring-cede \"0.1.0\"]]\n :scm {:url \"git@github.com:rm-hull/lindenmayer-systems.git\"}\n :ring {\n :handler ",
"end": 640,
"score": 0.9984039664268494,
"start": 633,
"tag": "USERNAME",
"value": "rm-hull"
}
] | project.clj | rm-hull/lindenmayer-systems | 38 | (defproject lindenmayer-systems "0.2.1"
:description "An L-System explorer in Clojure"
:url "http://lindenmayer-systems.destructuring-bind.org"
:license {
:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"}
:dependencies [
[org.clojure/clojure "1.9.0"]
[org.clojure/data.json "0.2.6"]
[com.taoensso/timbre "4.10.0"]
[compojure "1.6.1"]
[ring "1.7.0"]
[hiccup "1.0.5"]
[ring-logger-timbre "0.7.6"]
[metrics-clojure-ring "2.10.0"]
[rm-hull/ring-gzip-middleware "0.1.7"]
[rm-hull/turtle "0.1.11"]
[rm-hull/ring-cede "0.1.0"]]
:scm {:url "git@github.com:rm-hull/lindenmayer-systems.git"}
:ring {
:handler lindenmayer.handler/app}
:source-paths ["src"]
:resource-paths ["resources"]
:jar-exclusions [#"(?:^|/).git"]
:uberjar-exclusions [#"\.SF" #"\.RSA" #"\.DSA"]
:min-lein-version "2.8.1"
:profiles {
:uberjar {:aot :all}
:dev {
:global-vars {*warn-on-reflection* true}
:dependencies [
[org.clojure/test.check "0.9.0"]]
:plugins [
[lein-cloverage "1.0.13"]
[lein-cljfmt "0.6.1"]
[lein-ring "0.12.4"]]}})
| 48714 | (defproject lindenmayer-systems "0.2.1"
:description "An L-System explorer in Clojure"
:url "http://lindenmayer-systems.destructuring-bind.org"
:license {
:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"}
:dependencies [
[org.clojure/clojure "1.9.0"]
[org.clojure/data.json "0.2.6"]
[com.taoensso/timbre "4.10.0"]
[compojure "1.6.1"]
[ring "1.7.0"]
[hiccup "1.0.5"]
[ring-logger-timbre "0.7.6"]
[metrics-clojure-ring "2.10.0"]
[rm-hull/ring-gzip-middleware "0.1.7"]
[rm-hull/turtle "0.1.11"]
[rm-hull/ring-cede "0.1.0"]]
:scm {:url "<EMAIL>:rm-hull/lindenmayer-systems.git"}
:ring {
:handler lindenmayer.handler/app}
:source-paths ["src"]
:resource-paths ["resources"]
:jar-exclusions [#"(?:^|/).git"]
:uberjar-exclusions [#"\.SF" #"\.RSA" #"\.DSA"]
:min-lein-version "2.8.1"
:profiles {
:uberjar {:aot :all}
:dev {
:global-vars {*warn-on-reflection* true}
:dependencies [
[org.clojure/test.check "0.9.0"]]
:plugins [
[lein-cloverage "1.0.13"]
[lein-cljfmt "0.6.1"]
[lein-ring "0.12.4"]]}})
| true | (defproject lindenmayer-systems "0.2.1"
:description "An L-System explorer in Clojure"
:url "http://lindenmayer-systems.destructuring-bind.org"
:license {
:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"}
:dependencies [
[org.clojure/clojure "1.9.0"]
[org.clojure/data.json "0.2.6"]
[com.taoensso/timbre "4.10.0"]
[compojure "1.6.1"]
[ring "1.7.0"]
[hiccup "1.0.5"]
[ring-logger-timbre "0.7.6"]
[metrics-clojure-ring "2.10.0"]
[rm-hull/ring-gzip-middleware "0.1.7"]
[rm-hull/turtle "0.1.11"]
[rm-hull/ring-cede "0.1.0"]]
:scm {:url "PI:EMAIL:<EMAIL>END_PI:rm-hull/lindenmayer-systems.git"}
:ring {
:handler lindenmayer.handler/app}
:source-paths ["src"]
:resource-paths ["resources"]
:jar-exclusions [#"(?:^|/).git"]
:uberjar-exclusions [#"\.SF" #"\.RSA" #"\.DSA"]
:min-lein-version "2.8.1"
:profiles {
:uberjar {:aot :all}
:dev {
:global-vars {*warn-on-reflection* true}
:dependencies [
[org.clojure/test.check "0.9.0"]]
:plugins [
[lein-cloverage "1.0.13"]
[lein-cljfmt "0.6.1"]
[lein-ring "0.12.4"]]}})
|
[
{
"context": "/edit/password\")\n {:params {:current_password current-password\n :new_password new-password\n ",
"end": 1318,
"score": 0.8464953899383545,
"start": 1302,
"tag": "PASSWORD",
"value": "current-password"
},
{
"context": "current-password\n :new_password new-password\n :new_password_verify new-password",
"end": 1361,
"score": 0.7013295888900757,
"start": 1353,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "-password\n :new_password_verify new-password-verify}\n\n :handler (fn [data]\n ",
"end": 1411,
"score": 0.5959597229957581,
"start": 1403,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " :new_password_verify new-password-verify}\n\n :handler (fn [data]\n (i",
"end": 1418,
"score": 0.7299144268035889,
"start": 1412,
"tag": "PASSWORD",
"value": "verify"
}
] | src/cljs/salava/user/ui/edit_password.cljs | Vilikkki/salava | 0 | (ns salava.user.ui.edit-password
(:require [reagent.core :refer [atom cursor]]
[reagent.session :as session]
[clojure.string :refer [blank?]]
[salava.core.ui.ajax-utils :as ajax]
[salava.core.ui.helper :refer [input-valid? js-navigate-to path-for plugin-fun]]
[salava.core.ui.layout :as layout]
[salava.core.i18n :refer [t translate-text]]
[salava.core.common :refer [deep-merge]]
[salava.user.schemas :as schemas]
[salava.core.helper :refer [dump]]
[salava.core.countries :refer [all-countries-sorted]]
[salava.user.ui.input :as input]))
(defn clear-password-fields [state]
(do
(swap! state assoc-in [:current_password] "")
(swap! state assoc-in [:new_password] "")
(swap! state assoc-in [:new_password_verify] "")))
(defn save-user-info [state]
(let [params @state
current-password (if-not (blank? (:current_password params)) (:current_password params))
new-password (if-not (blank? (:new_password params)) (:new_password params))
new-password-verify (if-not (blank? (:new_password_verify params)) (:new_password_verify params))]
(ajax/POST
(path-for "/obpv1/user/edit/password")
{:params {:current_password current-password
:new_password new-password
:new_password_verify new-password-verify}
:handler (fn [data]
(if (= (:status data) "success")
(do
(clear-password-fields state)
(swap! state assoc :message {:class "alert-success" :content (:message data)}))
(do
(swap! state assoc :message {:class "alert-danger" :content (:message data)})
))
)})))
(defn new-password-valid? [has-password? current-password new-password new-password-verify]
(or
(and (empty? new-password)
(empty? new-password-verify)
(empty? current-password))
(and (not-empty new-password)
(not-empty new-password-verify)
(input/password-valid? new-password)
(input/password-valid? new-password-verify)
(= new-password new-password-verify)
(or (not has-password?) (not-empty current-password)))))
(defn content [state]
(let [current-password-atom (cursor state [:current_password])
new-password-atom (cursor state [:new_password])
new-password-verify-atom (cursor state [:new_password_verify])
message (:message @state)
current-password? (get-in @state [:password?])]
[:div {:class "panel" :id "edit-user"}
(if message
[:div {:class (str "alert " (:class message))}
(translate-text (:content message)) ])
[:div {:class "panel-body"}
[:form.form-horizontal
(if current-password?
[:div.form-group
[:label {:for "input-current-password" :class "col-md-3"} (t :user/Currentpassword)]
[:div {:class "col-md-9"}
[:input {:class "form-control"
:id "input-current-password"
:name name
:type "password"
:placeholder (t :user/Enteryourcurrentpassword)
:read-only true
:on-focus #(.removeAttribute (.-target %) "readonly")
:on-change #(reset! current-password-atom (.-target.value %))
:value @current-password-atom}]]])
[:div {:id "new-password" :class "form-group"}
[:div.col-md-12 (t :user/Tochangecurrentpassword)]
[:br]
[:div.flip
[:label {:for "input-new-password" :class "col-md-3"} (t :user/Newpassword)]
[:div {:class "col-md-9"}
[input/text-field {:name "new-password" :atom new-password-atom :password? true}]]]]
[:div.form-group
[:label {:for "input-new-password-verify" :class "col-md-3"} (t :user/Confirmnewpassword)]
[:div {:class "col-md-9"}
[input/text-field {:name "new-password-verify" :atom new-password-verify-atom :password? true}]]]
[:div.row
[:div.col-xs-12
[:button {:class "btn btn-primary"
:disabled (if-not (new-password-valid? current-password? @current-password-atom @new-password-atom @new-password-verify-atom)
"disabled")
:on-click #(do
(.preventDefault %)
(save-user-info state))}
(t :core/Save)]]]]]]))
(def initial-state
{:current_password nil
:new_password nil
:new_password_verify nil
:message nil}
)
(defn init-data [state]
(ajax/GET
(path-for "/obpv1/user/edit/password" true)
{:handler (fn [data]
(swap! state assoc :password? (:password? data)))}))
(defn handler [site-navi]
(let [state (atom {:new_password_verify nil
:current_password nil
:password? true
:new_password nil
:message nil} )]
(init-data state)
(fn []
(layout/default site-navi (content state)))))
| 73608 | (ns salava.user.ui.edit-password
(:require [reagent.core :refer [atom cursor]]
[reagent.session :as session]
[clojure.string :refer [blank?]]
[salava.core.ui.ajax-utils :as ajax]
[salava.core.ui.helper :refer [input-valid? js-navigate-to path-for plugin-fun]]
[salava.core.ui.layout :as layout]
[salava.core.i18n :refer [t translate-text]]
[salava.core.common :refer [deep-merge]]
[salava.user.schemas :as schemas]
[salava.core.helper :refer [dump]]
[salava.core.countries :refer [all-countries-sorted]]
[salava.user.ui.input :as input]))
(defn clear-password-fields [state]
(do
(swap! state assoc-in [:current_password] "")
(swap! state assoc-in [:new_password] "")
(swap! state assoc-in [:new_password_verify] "")))
(defn save-user-info [state]
(let [params @state
current-password (if-not (blank? (:current_password params)) (:current_password params))
new-password (if-not (blank? (:new_password params)) (:new_password params))
new-password-verify (if-not (blank? (:new_password_verify params)) (:new_password_verify params))]
(ajax/POST
(path-for "/obpv1/user/edit/password")
{:params {:current_password <PASSWORD>
:new_password new-<PASSWORD>
:new_password_verify new-<PASSWORD>-<PASSWORD>}
:handler (fn [data]
(if (= (:status data) "success")
(do
(clear-password-fields state)
(swap! state assoc :message {:class "alert-success" :content (:message data)}))
(do
(swap! state assoc :message {:class "alert-danger" :content (:message data)})
))
)})))
(defn new-password-valid? [has-password? current-password new-password new-password-verify]
(or
(and (empty? new-password)
(empty? new-password-verify)
(empty? current-password))
(and (not-empty new-password)
(not-empty new-password-verify)
(input/password-valid? new-password)
(input/password-valid? new-password-verify)
(= new-password new-password-verify)
(or (not has-password?) (not-empty current-password)))))
(defn content [state]
(let [current-password-atom (cursor state [:current_password])
new-password-atom (cursor state [:new_password])
new-password-verify-atom (cursor state [:new_password_verify])
message (:message @state)
current-password? (get-in @state [:password?])]
[:div {:class "panel" :id "edit-user"}
(if message
[:div {:class (str "alert " (:class message))}
(translate-text (:content message)) ])
[:div {:class "panel-body"}
[:form.form-horizontal
(if current-password?
[:div.form-group
[:label {:for "input-current-password" :class "col-md-3"} (t :user/Currentpassword)]
[:div {:class "col-md-9"}
[:input {:class "form-control"
:id "input-current-password"
:name name
:type "password"
:placeholder (t :user/Enteryourcurrentpassword)
:read-only true
:on-focus #(.removeAttribute (.-target %) "readonly")
:on-change #(reset! current-password-atom (.-target.value %))
:value @current-password-atom}]]])
[:div {:id "new-password" :class "form-group"}
[:div.col-md-12 (t :user/Tochangecurrentpassword)]
[:br]
[:div.flip
[:label {:for "input-new-password" :class "col-md-3"} (t :user/Newpassword)]
[:div {:class "col-md-9"}
[input/text-field {:name "new-password" :atom new-password-atom :password? true}]]]]
[:div.form-group
[:label {:for "input-new-password-verify" :class "col-md-3"} (t :user/Confirmnewpassword)]
[:div {:class "col-md-9"}
[input/text-field {:name "new-password-verify" :atom new-password-verify-atom :password? true}]]]
[:div.row
[:div.col-xs-12
[:button {:class "btn btn-primary"
:disabled (if-not (new-password-valid? current-password? @current-password-atom @new-password-atom @new-password-verify-atom)
"disabled")
:on-click #(do
(.preventDefault %)
(save-user-info state))}
(t :core/Save)]]]]]]))
(def initial-state
{:current_password nil
:new_password nil
:new_password_verify nil
:message nil}
)
(defn init-data [state]
(ajax/GET
(path-for "/obpv1/user/edit/password" true)
{:handler (fn [data]
(swap! state assoc :password? (:password? data)))}))
(defn handler [site-navi]
(let [state (atom {:new_password_verify nil
:current_password nil
:password? true
:new_password nil
:message nil} )]
(init-data state)
(fn []
(layout/default site-navi (content state)))))
| true | (ns salava.user.ui.edit-password
(:require [reagent.core :refer [atom cursor]]
[reagent.session :as session]
[clojure.string :refer [blank?]]
[salava.core.ui.ajax-utils :as ajax]
[salava.core.ui.helper :refer [input-valid? js-navigate-to path-for plugin-fun]]
[salava.core.ui.layout :as layout]
[salava.core.i18n :refer [t translate-text]]
[salava.core.common :refer [deep-merge]]
[salava.user.schemas :as schemas]
[salava.core.helper :refer [dump]]
[salava.core.countries :refer [all-countries-sorted]]
[salava.user.ui.input :as input]))
(defn clear-password-fields [state]
(do
(swap! state assoc-in [:current_password] "")
(swap! state assoc-in [:new_password] "")
(swap! state assoc-in [:new_password_verify] "")))
(defn save-user-info [state]
(let [params @state
current-password (if-not (blank? (:current_password params)) (:current_password params))
new-password (if-not (blank? (:new_password params)) (:new_password params))
new-password-verify (if-not (blank? (:new_password_verify params)) (:new_password_verify params))]
(ajax/POST
(path-for "/obpv1/user/edit/password")
{:params {:current_password PI:PASSWORD:<PASSWORD>END_PI
:new_password new-PI:PASSWORD:<PASSWORD>END_PI
:new_password_verify new-PI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI}
:handler (fn [data]
(if (= (:status data) "success")
(do
(clear-password-fields state)
(swap! state assoc :message {:class "alert-success" :content (:message data)}))
(do
(swap! state assoc :message {:class "alert-danger" :content (:message data)})
))
)})))
(defn new-password-valid? [has-password? current-password new-password new-password-verify]
(or
(and (empty? new-password)
(empty? new-password-verify)
(empty? current-password))
(and (not-empty new-password)
(not-empty new-password-verify)
(input/password-valid? new-password)
(input/password-valid? new-password-verify)
(= new-password new-password-verify)
(or (not has-password?) (not-empty current-password)))))
(defn content [state]
(let [current-password-atom (cursor state [:current_password])
new-password-atom (cursor state [:new_password])
new-password-verify-atom (cursor state [:new_password_verify])
message (:message @state)
current-password? (get-in @state [:password?])]
[:div {:class "panel" :id "edit-user"}
(if message
[:div {:class (str "alert " (:class message))}
(translate-text (:content message)) ])
[:div {:class "panel-body"}
[:form.form-horizontal
(if current-password?
[:div.form-group
[:label {:for "input-current-password" :class "col-md-3"} (t :user/Currentpassword)]
[:div {:class "col-md-9"}
[:input {:class "form-control"
:id "input-current-password"
:name name
:type "password"
:placeholder (t :user/Enteryourcurrentpassword)
:read-only true
:on-focus #(.removeAttribute (.-target %) "readonly")
:on-change #(reset! current-password-atom (.-target.value %))
:value @current-password-atom}]]])
[:div {:id "new-password" :class "form-group"}
[:div.col-md-12 (t :user/Tochangecurrentpassword)]
[:br]
[:div.flip
[:label {:for "input-new-password" :class "col-md-3"} (t :user/Newpassword)]
[:div {:class "col-md-9"}
[input/text-field {:name "new-password" :atom new-password-atom :password? true}]]]]
[:div.form-group
[:label {:for "input-new-password-verify" :class "col-md-3"} (t :user/Confirmnewpassword)]
[:div {:class "col-md-9"}
[input/text-field {:name "new-password-verify" :atom new-password-verify-atom :password? true}]]]
[:div.row
[:div.col-xs-12
[:button {:class "btn btn-primary"
:disabled (if-not (new-password-valid? current-password? @current-password-atom @new-password-atom @new-password-verify-atom)
"disabled")
:on-click #(do
(.preventDefault %)
(save-user-info state))}
(t :core/Save)]]]]]]))
(def initial-state
{:current_password nil
:new_password nil
:new_password_verify nil
:message nil}
)
(defn init-data [state]
(ajax/GET
(path-for "/obpv1/user/edit/password" true)
{:handler (fn [data]
(swap! state assoc :password? (:password? data)))}))
(defn handler [site-navi]
(let [state (atom {:new_password_verify nil
:current_password nil
:password? true
:new_password nil
:message nil} )]
(init-data state)
(fn []
(layout/default site-navi (content state)))))
|
[
{
"context": "r Say-Sila (sub)projects\n;;;;\n;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal\n;;;; -------",
"end": 422,
"score": 0.9998847842216492,
"start": 410,
"tag": "NAME",
"value": "Dennis Drown"
}
] | apps/say_sila/priv/fnode/say/src/say/check.clj | dendrown/say_sila | 0 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Checks, verification, and data analysis for Say-Sila (sub)projects
;;;;
;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.check
(:require [say.genie :refer :all]
[say.log :as log]
;[say.influence] ; <= article: Big Players
[say.senti :as senti]
[weka.core :as weka]
[weka.senti :as wsenti])
(:import (weka.classifiers Evaluation)
(weka.core Instances)))
(set! *warn-on-reflection* true)
;;; --------------------------------------------------------------------------
(defn- time-evaluation
"Runs a (preinitialized) Weka Evaluation object (audit) and reports the time
it took in milliseconds. As a convenience, the function returns the audit
object."
[^Evaluation audit
classer
insts]
(let [t0 (System/currentTimeMillis)]
(.evaluateModel audit classer insts NO-OBJS)
(log/fmt-info "Elapsed: ~3$ secs" (/ (- (System/currentTimeMillis) t0) 1000))))
;;; --------------------------------------------------------------------------
(defn eval-senti
"Handles test & verification for say-senti ontology-based learning."
([]
(eval-senti ;"resources/emo-sa/sentiment-analysis.Sentiment140.r24816.train.000.arff"
(senti/which-arff :test)))
([arff]
(eval-senti arff (senti/read-solutions))) ; Use official solutions
([arff solns]
(let [target (senti/which-target)
insts (weka/load-arff arff target)
classer (wsenti/make-classifier solns)
audit (Evaluation. (Instances. insts 0))]
(log/fmt-info "Testing ~a: arff[~a] insts[~a] solns[~a]" target
arff
(.numInstances insts)
(count solns))
(time-evaluation audit classer insts)
(log/info "Summary:\n" (.toSummaryString audit))
(log/info "Class Details\n" (.toClassDetailsString audit))
(log/info "Confusion Matrix\n" (.toMatrixString audit))
audit)))
| 5526 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Checks, verification, and data analysis for Say-Sila (sub)projects
;;;;
;;;; @copyright 2020 <NAME> et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.check
(:require [say.genie :refer :all]
[say.log :as log]
;[say.influence] ; <= article: Big Players
[say.senti :as senti]
[weka.core :as weka]
[weka.senti :as wsenti])
(:import (weka.classifiers Evaluation)
(weka.core Instances)))
(set! *warn-on-reflection* true)
;;; --------------------------------------------------------------------------
(defn- time-evaluation
"Runs a (preinitialized) Weka Evaluation object (audit) and reports the time
it took in milliseconds. As a convenience, the function returns the audit
object."
[^Evaluation audit
classer
insts]
(let [t0 (System/currentTimeMillis)]
(.evaluateModel audit classer insts NO-OBJS)
(log/fmt-info "Elapsed: ~3$ secs" (/ (- (System/currentTimeMillis) t0) 1000))))
;;; --------------------------------------------------------------------------
(defn eval-senti
"Handles test & verification for say-senti ontology-based learning."
([]
(eval-senti ;"resources/emo-sa/sentiment-analysis.Sentiment140.r24816.train.000.arff"
(senti/which-arff :test)))
([arff]
(eval-senti arff (senti/read-solutions))) ; Use official solutions
([arff solns]
(let [target (senti/which-target)
insts (weka/load-arff arff target)
classer (wsenti/make-classifier solns)
audit (Evaluation. (Instances. insts 0))]
(log/fmt-info "Testing ~a: arff[~a] insts[~a] solns[~a]" target
arff
(.numInstances insts)
(count solns))
(time-evaluation audit classer insts)
(log/info "Summary:\n" (.toSummaryString audit))
(log/info "Class Details\n" (.toClassDetailsString audit))
(log/info "Confusion Matrix\n" (.toMatrixString audit))
audit)))
| true | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Checks, verification, and data analysis for Say-Sila (sub)projects
;;;;
;;;; @copyright 2020 PI:NAME:<NAME>END_PI et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.check
(:require [say.genie :refer :all]
[say.log :as log]
;[say.influence] ; <= article: Big Players
[say.senti :as senti]
[weka.core :as weka]
[weka.senti :as wsenti])
(:import (weka.classifiers Evaluation)
(weka.core Instances)))
(set! *warn-on-reflection* true)
;;; --------------------------------------------------------------------------
(defn- time-evaluation
"Runs a (preinitialized) Weka Evaluation object (audit) and reports the time
it took in milliseconds. As a convenience, the function returns the audit
object."
[^Evaluation audit
classer
insts]
(let [t0 (System/currentTimeMillis)]
(.evaluateModel audit classer insts NO-OBJS)
(log/fmt-info "Elapsed: ~3$ secs" (/ (- (System/currentTimeMillis) t0) 1000))))
;;; --------------------------------------------------------------------------
(defn eval-senti
"Handles test & verification for say-senti ontology-based learning."
([]
(eval-senti ;"resources/emo-sa/sentiment-analysis.Sentiment140.r24816.train.000.arff"
(senti/which-arff :test)))
([arff]
(eval-senti arff (senti/read-solutions))) ; Use official solutions
([arff solns]
(let [target (senti/which-target)
insts (weka/load-arff arff target)
classer (wsenti/make-classifier solns)
audit (Evaluation. (Instances. insts 0))]
(log/fmt-info "Testing ~a: arff[~a] insts[~a] solns[~a]" target
arff
(.numInstances insts)
(count solns))
(time-evaluation audit classer insts)
(log/info "Summary:\n" (.toSummaryString audit))
(log/info "Class Details\n" (.toClassDetailsString audit))
(log/info "Confusion Matrix\n" (.toMatrixString audit))
audit)))
|
[
{
"context": "ght\" \"Age\" \"Shoes\"])\n\n(def sample-table-data [[\"Thouroughbred\" \"Bay\" 1.60 3 true]\n [\"Tho",
"end": 201,
"score": 0.5791035294532776,
"start": 190,
"tag": "NAME",
"value": "ouroughbred"
},
{
"context": "d\" \"Bay\" 1.60 3 true]\n [\"Thouroughbred\" \"Grey\" 1.55 3 true]\n ",
"end": 252,
"score": 0.5914724469184875,
"start": 250,
"tag": "NAME",
"value": "ou"
}
] | clojure/horse/test/horse/core_test.clj | poenneby/Horse-Kata | 11 | (ns horse.core-test
(:require [midje.sweet :refer :all]
[horse.core :refer :all]))
(def sample-headers ["Breed" "Colour" "Height" "Age" "Shoes"])
(def sample-table-data [["Thouroughbred" "Bay" 1.60 3 true]
["Thouroughbred" "Grey" 1.55 3 true]
["Arabian horse" "Bay" 1.51 5 true]
["Shetland Pony" "Black" 1.01 2 false]
["Shire horse" "Black" 1.71 4 true]])
(facts "When no filters, no sorting, and no pagination"
(fact "it should return all data"
(let [empty-filters []
empty-sort-metadata []
first-ten-pagination {:first-record-in-page 1
:page-size 10}]
(filter-sort-paginate-table
sample-headers
sample-table-data
empty-filters
empty-sort-metadata
first-ten-pagination)) => {:headers sample-headers
:table-data sample-table-data
:total-rows 4})) ;; FIXME: Should be 5
| 96758 | (ns horse.core-test
(:require [midje.sweet :refer :all]
[horse.core :refer :all]))
(def sample-headers ["Breed" "Colour" "Height" "Age" "Shoes"])
(def sample-table-data [["Th<NAME>" "Bay" 1.60 3 true]
["Th<NAME>roughbred" "Grey" 1.55 3 true]
["Arabian horse" "Bay" 1.51 5 true]
["Shetland Pony" "Black" 1.01 2 false]
["Shire horse" "Black" 1.71 4 true]])
(facts "When no filters, no sorting, and no pagination"
(fact "it should return all data"
(let [empty-filters []
empty-sort-metadata []
first-ten-pagination {:first-record-in-page 1
:page-size 10}]
(filter-sort-paginate-table
sample-headers
sample-table-data
empty-filters
empty-sort-metadata
first-ten-pagination)) => {:headers sample-headers
:table-data sample-table-data
:total-rows 4})) ;; FIXME: Should be 5
| true | (ns horse.core-test
(:require [midje.sweet :refer :all]
[horse.core :refer :all]))
(def sample-headers ["Breed" "Colour" "Height" "Age" "Shoes"])
(def sample-table-data [["ThPI:NAME:<NAME>END_PI" "Bay" 1.60 3 true]
["ThPI:NAME:<NAME>END_PIroughbred" "Grey" 1.55 3 true]
["Arabian horse" "Bay" 1.51 5 true]
["Shetland Pony" "Black" 1.01 2 false]
["Shire horse" "Black" 1.71 4 true]])
(facts "When no filters, no sorting, and no pagination"
(fact "it should return all data"
(let [empty-filters []
empty-sort-metadata []
first-ten-pagination {:first-record-in-page 1
:page-size 10}]
(filter-sort-paginate-table
sample-headers
sample-table-data
empty-filters
empty-sort-metadata
first-ten-pagination)) => {:headers sample-headers
:table-data sample-table-data
:total-rows 4})) ;; FIXME: Should be 5
|
[
{
"context": "gshot :refer [try+ throw+]]))\n\n(def ip-ranges\n [\"144.76.0.0/16\"\n \"5.9.0.0/16\"])\n\n(s/defn this-host?\n [fact",
"end": 297,
"score": 0.9994131326675415,
"start": 287,
"tag": "IP_ADDRESS",
"value": "144.76.0.0"
},
{
"context": "ow+]]))\n\n(def ip-ranges\n [\"144.76.0.0/16\"\n \"5.9.0.0/16\"])\n\n(s/defn this-host?\n [facter]\n (some\n ",
"end": 309,
"score": 0.5150419473648071,
"start": 309,
"tag": "IP_ADDRESS",
"value": ""
},
{
"context": "+]]))\n\n(def ip-ranges\n [\"144.76.0.0/16\"\n \"5.9.0.0/16\"])\n\n(s/defn this-host?\n [facter]\n (some\n ",
"end": 311,
"score": 0.5843876004219055,
"start": 311,
"tag": "IP_ADDRESS",
"value": ""
}
] | src/clj/runbld/hosting/hetzner.clj | ddillinger/runbld | 6 | (ns runbld.hosting.hetzner
(:require
[runbld.facts :as facts]
[runbld.hosting :refer [HostingProvider]]
[runbld.io :as io]
[runbld.schema :refer :all]
[runbld.util.cidr :as cidr]
[schema.core :as s]
[slingshot.slingshot :refer [try+ throw+]]))
(def ip-ranges
["144.76.0.0/16"
"5.9.0.0/16"])
(s/defn this-host?
[facter]
(some
(fn [ip]
(boolean
(some true?
(map #(cidr/in-range? ip %) ip-ranges))))
(facts/ip4 facter)))
(s/defn discover-datacenter
"Based on
http://wiki.hetzner.de/index.php/Rechenzentren_und_Anbindung/en,
the DC name is always present in the perimeter Juniper
hostname. Try looking for it."
([]
(let [{:keys [out]} (io/run "traceroute" "-m 5" "google.com")]
(discover-datacenter out)))
([trace]
(let [[_ dc] (re-find #"(rz[0-9]+)\.hetzner\.de" trace)]
dc)))
(defrecord HetznerHosting [facts]
HostingProvider
(datacenter [_]
(discover-datacenter))
(image-id [_])
(instance-id [_])
(instance-type [_])
(provider [_]
"hetzner")
(region [_])
(virtual [_] false))
(s/defn make
([facts]
(HetznerHosting. facts)))
| 74581 | (ns runbld.hosting.hetzner
(:require
[runbld.facts :as facts]
[runbld.hosting :refer [HostingProvider]]
[runbld.io :as io]
[runbld.schema :refer :all]
[runbld.util.cidr :as cidr]
[schema.core :as s]
[slingshot.slingshot :refer [try+ throw+]]))
(def ip-ranges
["172.16.31.10/16"
"5.9.0.0/16"])
(s/defn this-host?
[facter]
(some
(fn [ip]
(boolean
(some true?
(map #(cidr/in-range? ip %) ip-ranges))))
(facts/ip4 facter)))
(s/defn discover-datacenter
"Based on
http://wiki.hetzner.de/index.php/Rechenzentren_und_Anbindung/en,
the DC name is always present in the perimeter Juniper
hostname. Try looking for it."
([]
(let [{:keys [out]} (io/run "traceroute" "-m 5" "google.com")]
(discover-datacenter out)))
([trace]
(let [[_ dc] (re-find #"(rz[0-9]+)\.hetzner\.de" trace)]
dc)))
(defrecord HetznerHosting [facts]
HostingProvider
(datacenter [_]
(discover-datacenter))
(image-id [_])
(instance-id [_])
(instance-type [_])
(provider [_]
"hetzner")
(region [_])
(virtual [_] false))
(s/defn make
([facts]
(HetznerHosting. facts)))
| true | (ns runbld.hosting.hetzner
(:require
[runbld.facts :as facts]
[runbld.hosting :refer [HostingProvider]]
[runbld.io :as io]
[runbld.schema :refer :all]
[runbld.util.cidr :as cidr]
[schema.core :as s]
[slingshot.slingshot :refer [try+ throw+]]))
(def ip-ranges
["PI:IP_ADDRESS:172.16.31.10END_PI/16"
"5.9.0.0/16"])
(s/defn this-host?
[facter]
(some
(fn [ip]
(boolean
(some true?
(map #(cidr/in-range? ip %) ip-ranges))))
(facts/ip4 facter)))
(s/defn discover-datacenter
"Based on
http://wiki.hetzner.de/index.php/Rechenzentren_und_Anbindung/en,
the DC name is always present in the perimeter Juniper
hostname. Try looking for it."
([]
(let [{:keys [out]} (io/run "traceroute" "-m 5" "google.com")]
(discover-datacenter out)))
([trace]
(let [[_ dc] (re-find #"(rz[0-9]+)\.hetzner\.de" trace)]
dc)))
(defrecord HetznerHosting [facts]
HostingProvider
(datacenter [_]
(discover-datacenter))
(image-id [_])
(instance-id [_])
(instance-type [_])
(provider [_]
"hetzner")
(region [_])
(virtual [_] false))
(s/defn make
([facts]
(HetznerHosting. facts)))
|
[
{
"context": "thorizationToken authz)) #\":\")]\n {:username user\n :password pass\n :endpoint (:prox",
"end": 3021,
"score": 0.9714047908782959,
"start": 3017,
"tag": "USERNAME",
"value": "user"
},
{
"context": " #\":\")]\n {:username user\n :password pass\n :endpoint (:proxyEndpoint authz)})\n ",
"end": 3045,
"score": 0.998913049697876,
"start": 3041,
"tag": "PASSWORD",
"value": "pass"
}
] | src/leiningen/aws_ecr_auth.clj | slimslenderslacks/lein-jib-build | 0 | (ns leiningen.aws-ecr-auth
(:require [cognitect.aws.client.api :as aws]
[cognitect.aws.credentials :as credentials]
[clojure.string :as str]
[leiningen.core.main :as lein]
[cognitect.aws.util])
(:import [java.util Base64]
(java.io ByteArrayInputStream)))
(defn decode-base64 [to-decode]
(String. (.decode (Base64/getDecoder) to-decode)))
(defn assumed-role-credentials-provider [role-arn session-name refresh-every-n-seconds]
(credentials/auto-refreshing-credentials
(reify credentials/CredentialsProvider
(fetch [_]
;; The following is a workaround for a XML-parsing issue when using
;; the older clojure.data.xml bundled with Leiningen
(with-redefs [cognitect.aws.util/xml-read
(fn [s] (clojure.data.xml/parse (ByteArrayInputStream. (.getBytes ^String s "UTF-8"))
:namespace-aware false))]
(let [sts (aws/client {:api :sts})
sts-request {:op :AssumeRole
:request {:RoleArn role-arn
:RoleSessionName session-name}}
sts-response (aws/invoke sts sts-request)]
(lein/info "sts-resp" sts-response)
(if-let [creds (:Credentials sts-response)]
{:aws/access-key-id (:AccessKeyId creds)
:aws/secret-access-key (:SecretAccessKey creds)
:aws/session-token (:SessionToken creds)
::credentials/ttl refresh-every-n-seconds}
(throw (ex-info (str "Unable to gain STS temporary credentials:" sts-response) sts-response)))))))))
(defn get-client [api credentials-config]
(if-let [crp (case (:type credentials-config)
:assume-role
(assumed-role-credentials-provider (:role-arn credentials-config) "session" 600)
:access-key
(credentials/basic-credentials-provider (select-keys credentials-config [:access-key-id :secret-access-key]))
:system-properties
(credentials/system-property-credentials-provider)
:profile
(credentials/profile-credentials-provider (:profile-name credentials-config))
:environment
(credentials/environment-credentials-provider))]
(aws/client (merge {:api api :credentials-provider crp}
(select-keys credentials-config [:region])))
(aws/client {:api api})))
(defn ecr-auth [credentials-config]
(lein/debug "Generating ECR authorization from" (str credentials-config))
(let [ecr-response (aws/invoke (get-client :ecr credentials-config)
{:op :GetAuthorizationToken})]
(if-let [authz (get-in ecr-response
[:authorizationData 0])]
(let [[user pass] (str/split (decode-base64 (:authorizationToken authz)) #":")]
{:username user
:password pass
:endpoint (:proxyEndpoint authz)})
(throw (ex-info (str "Cannot generate ECR authorization credentials: " ecr-response) ecr-response)))))
| 61481 | (ns leiningen.aws-ecr-auth
(:require [cognitect.aws.client.api :as aws]
[cognitect.aws.credentials :as credentials]
[clojure.string :as str]
[leiningen.core.main :as lein]
[cognitect.aws.util])
(:import [java.util Base64]
(java.io ByteArrayInputStream)))
(defn decode-base64 [to-decode]
(String. (.decode (Base64/getDecoder) to-decode)))
(defn assumed-role-credentials-provider [role-arn session-name refresh-every-n-seconds]
(credentials/auto-refreshing-credentials
(reify credentials/CredentialsProvider
(fetch [_]
;; The following is a workaround for a XML-parsing issue when using
;; the older clojure.data.xml bundled with Leiningen
(with-redefs [cognitect.aws.util/xml-read
(fn [s] (clojure.data.xml/parse (ByteArrayInputStream. (.getBytes ^String s "UTF-8"))
:namespace-aware false))]
(let [sts (aws/client {:api :sts})
sts-request {:op :AssumeRole
:request {:RoleArn role-arn
:RoleSessionName session-name}}
sts-response (aws/invoke sts sts-request)]
(lein/info "sts-resp" sts-response)
(if-let [creds (:Credentials sts-response)]
{:aws/access-key-id (:AccessKeyId creds)
:aws/secret-access-key (:SecretAccessKey creds)
:aws/session-token (:SessionToken creds)
::credentials/ttl refresh-every-n-seconds}
(throw (ex-info (str "Unable to gain STS temporary credentials:" sts-response) sts-response)))))))))
(defn get-client [api credentials-config]
(if-let [crp (case (:type credentials-config)
:assume-role
(assumed-role-credentials-provider (:role-arn credentials-config) "session" 600)
:access-key
(credentials/basic-credentials-provider (select-keys credentials-config [:access-key-id :secret-access-key]))
:system-properties
(credentials/system-property-credentials-provider)
:profile
(credentials/profile-credentials-provider (:profile-name credentials-config))
:environment
(credentials/environment-credentials-provider))]
(aws/client (merge {:api api :credentials-provider crp}
(select-keys credentials-config [:region])))
(aws/client {:api api})))
(defn ecr-auth [credentials-config]
(lein/debug "Generating ECR authorization from" (str credentials-config))
(let [ecr-response (aws/invoke (get-client :ecr credentials-config)
{:op :GetAuthorizationToken})]
(if-let [authz (get-in ecr-response
[:authorizationData 0])]
(let [[user pass] (str/split (decode-base64 (:authorizationToken authz)) #":")]
{:username user
:password <PASSWORD>
:endpoint (:proxyEndpoint authz)})
(throw (ex-info (str "Cannot generate ECR authorization credentials: " ecr-response) ecr-response)))))
| true | (ns leiningen.aws-ecr-auth
(:require [cognitect.aws.client.api :as aws]
[cognitect.aws.credentials :as credentials]
[clojure.string :as str]
[leiningen.core.main :as lein]
[cognitect.aws.util])
(:import [java.util Base64]
(java.io ByteArrayInputStream)))
(defn decode-base64 [to-decode]
(String. (.decode (Base64/getDecoder) to-decode)))
(defn assumed-role-credentials-provider [role-arn session-name refresh-every-n-seconds]
(credentials/auto-refreshing-credentials
(reify credentials/CredentialsProvider
(fetch [_]
;; The following is a workaround for a XML-parsing issue when using
;; the older clojure.data.xml bundled with Leiningen
(with-redefs [cognitect.aws.util/xml-read
(fn [s] (clojure.data.xml/parse (ByteArrayInputStream. (.getBytes ^String s "UTF-8"))
:namespace-aware false))]
(let [sts (aws/client {:api :sts})
sts-request {:op :AssumeRole
:request {:RoleArn role-arn
:RoleSessionName session-name}}
sts-response (aws/invoke sts sts-request)]
(lein/info "sts-resp" sts-response)
(if-let [creds (:Credentials sts-response)]
{:aws/access-key-id (:AccessKeyId creds)
:aws/secret-access-key (:SecretAccessKey creds)
:aws/session-token (:SessionToken creds)
::credentials/ttl refresh-every-n-seconds}
(throw (ex-info (str "Unable to gain STS temporary credentials:" sts-response) sts-response)))))))))
(defn get-client [api credentials-config]
(if-let [crp (case (:type credentials-config)
:assume-role
(assumed-role-credentials-provider (:role-arn credentials-config) "session" 600)
:access-key
(credentials/basic-credentials-provider (select-keys credentials-config [:access-key-id :secret-access-key]))
:system-properties
(credentials/system-property-credentials-provider)
:profile
(credentials/profile-credentials-provider (:profile-name credentials-config))
:environment
(credentials/environment-credentials-provider))]
(aws/client (merge {:api api :credentials-provider crp}
(select-keys credentials-config [:region])))
(aws/client {:api api})))
(defn ecr-auth [credentials-config]
(lein/debug "Generating ECR authorization from" (str credentials-config))
(let [ecr-response (aws/invoke (get-client :ecr credentials-config)
{:op :GetAuthorizationToken})]
(if-let [authz (get-in ecr-response
[:authorizationData 0])]
(let [[user pass] (str/split (decode-base64 (:authorizationToken authz)) #":")]
{:username user
:password PI:PASSWORD:<PASSWORD>END_PI
:endpoint (:proxyEndpoint authz)})
(throw (ex-info (str "Cannot generate ECR authorization credentials: " ecr-response) ecr-response)))))
|
[
{
"context": "tion\n; Date: March 17, 2016.\n; Authors:\n; A01020319 Fernando Gómez Herrera\n;-----------------------",
"end": 144,
"score": 0.8369709849357605,
"start": 137,
"tag": "USERNAME",
"value": "A010203"
},
{
"context": "e: March 17, 2016.\n; Authors:\n; A01020319 Fernando Gómez Herrera\n;------------------------------------------------",
"end": 169,
"score": 0.999868631362915,
"start": 147,
"tag": "NAME",
"value": "Fernando Gómez Herrera"
}
] | 4clojure/problem_61.clj | gomezhyuuga/CEM_tc2006 | 1 | ;----------------------------------------------------------
; Problem 61: Map Construction
; Date: March 17, 2016.
; Authors:
; A01020319 Fernando Gómez Herrera
;----------------------------------------------------------
(use 'clojure.test)
(defn p
[coll1 coll2]
(->>
(map #(array-map %1 %2) coll1 coll2)
(reduce merge)))
(deftest p-test
(is (= (p [:a :b :c] [1 2 3]) {:a 1, :b 2, :c 3}))
(is (= (p [1 2 3 4] ["one" "two" "three"]) {1 "one", 2 "two", 3 "three"}))
(is (= (p [:foo :bar] ["foo" "bar" "baz"]) {:foo "foo", :bar "bar"})))
(run-tests)
| 60855 | ;----------------------------------------------------------
; Problem 61: Map Construction
; Date: March 17, 2016.
; Authors:
; A01020319 <NAME>
;----------------------------------------------------------
(use 'clojure.test)
(defn p
[coll1 coll2]
(->>
(map #(array-map %1 %2) coll1 coll2)
(reduce merge)))
(deftest p-test
(is (= (p [:a :b :c] [1 2 3]) {:a 1, :b 2, :c 3}))
(is (= (p [1 2 3 4] ["one" "two" "three"]) {1 "one", 2 "two", 3 "three"}))
(is (= (p [:foo :bar] ["foo" "bar" "baz"]) {:foo "foo", :bar "bar"})))
(run-tests)
| true | ;----------------------------------------------------------
; Problem 61: Map Construction
; Date: March 17, 2016.
; Authors:
; A01020319 PI:NAME:<NAME>END_PI
;----------------------------------------------------------
(use 'clojure.test)
(defn p
[coll1 coll2]
(->>
(map #(array-map %1 %2) coll1 coll2)
(reduce merge)))
(deftest p-test
(is (= (p [:a :b :c] [1 2 3]) {:a 1, :b 2, :c 3}))
(is (= (p [1 2 3 4] ["one" "two" "three"]) {1 "one", 2 "two", 3 "three"}))
(is (= (p [:foo :bar] ["foo" "bar" "baz"]) {:foo "foo", :bar "bar"})))
(run-tests)
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\"\n :date \"2018-04-14\"\n ",
"end": 95,
"score": 0.612036406993866,
"start": 87,
"tag": "EMAIL",
"value": "wahpenay"
}
] | src/main/clojure/taiga/flat.clj | wahpenayo/taiga | 4 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "wahpenayo at gmail dot com"
:date "2018-04-14"
:doc
"Flat (affine or linear) models.
<p>
Usual statistics 'linear' model is actually fitting an
affine functional (with intercept case) or a linear
functional (no intercept case)." }
taiga.flat
(:require [zana.api :as z])
(:import [java.util Arrays Map]
[java.io Writer]
[clojure.lang IFn IFn$OD IFn$OOD]
[org.apache.commons.math3.stat.regression
OLSMultipleLinearRegression]
[zana.java.geometry Dn]
#_[zana.java.geometry.functions AffineFunctional]
[zana.java.data AffineEmbedding LinearEmbedding]))
;;----------------------------------------------------------------
;; This ought to be just a function composition, but we need to
;; define a special class so it can be serialized.
;; As it is, an FlatModel is an affine functional (a real-valued
;; function on <b>E</b><sup>p</sup>) composed with an affine
;; embedding of the relevant record type, a function from
;; the specified attributes of record objects to
;; <b>E</b><sup>p</sup>.
;; Note: nothing here really requies the functional to be flat!
;; We are really just composing an embedding of data space into
;; a presumably flat space (though that could be more general)
;; with a 'functional', by which I just mean a real-valued
;; function.
(deftype FlatModel [^IFn$OD functional
^IFn embedding]
java.io.Serializable
IFn$OOD
(invokePrim ^double [_ bindings record]
(.invokePrim ^IFn$OD functional
(.invoke ^IFn embedding bindings record)))
IFn
(invoke [this bindings record]
(.invokePrim ^IFn$OOD this bindings record))
Object
(hashCode [_]
(let [h (int 17)
h (unchecked-multiply-int h (int 31))
h (unchecked-add-int h (.hashCode functional))
h (unchecked-multiply-int h (int 31))
h (unchecked-add-int h (.hashCode embedding))]
h))
(equals [_ that]
(and (instance? FlatModel that)
(.equals functional (.functional ^FlatModel that))
(.equals embedding (.embedding ^FlatModel that))))
(toString [_]
(str "FlatModel[" functional ", " embedding "?}")))
(defn functional ^IFn$OD [^FlatModel am]
(.functional am))
(defn embedding ^IFn [^FlatModel am]
(.embedding am))
#_(defn functional ^AffineFunctional [^FlatModel am]
(.functional am))
#_(defn embedding ^AffineEmbedding [^FlatModel am]
(.embedding am))
;;----------------------------------------------------------------
;; EDN IO
;;----------------------------------------------------------------
(defn map->FlatModel ^FlatModel [^Map m]
(FlatModel.
^IFn$OD (:functional m)
^IFn (:embedding m))
#_(FlatModel.
^AffineFunctional (:functional m)
^AffineEmbedding (:embedding m)))
(defn map<-FlatModel ^Map [^FlatModel this]
{:functional (.functional this) :embedding (.embedding this)})
(defmethod z/clojurize FlatModel [^FlatModel this]
(map<-FlatModel this))
(defmethod print-method FlatModel [^FlatModel this ^Writer w]
(if *print-readably*
(do
(.write w " #taiga.flat.FlatModel ")
(.write w (pr-str (map<-FlatModel this))))
(.write w (print-str (map<-FlatModel this)))))
;;----------------------------------------------------------------
;; EDN input (output just works?)
;;----------------------------------------------------------------
(z/add-edn-readers!
{'taiga.flat.FlatModel map->FlatModel})
;;----------------------------------------------------------------
;; training
;;----------------------------------------------------------------
(defn- check [options]
(assert (not (z/empty? (:data options)))
(print-str "no :data in"
(z/pprint-map-str options)))
(assert (:attributes options)
(str "No :attributes given."
(z/pprint-map-str options)))
(assert (instance? java.util.Map (:attributes options))
(str ":attributes is not a map."
(z/pprint-map-str options)))
;; edge case: zero predictotrs means a constant model
;; TODO: force constants to be different from affine?
(assert (<= 0 (count (dissoc (:attributes options)
:ground-truth :prediction)))
(str ":no predictors:" options))
(assert (every? ifn? (:attributes options))
(str "One of the :attributes is not a function."
(z/pprint-map-str (:attributes options))))
(assert (ifn? (:ground-truth (:attributes options)))
(str "No :ground-truth!"
(z/pprint-map-str options))))
;;----------------------------------------------------------------
(defn- linearize
"Convert the general prediction problem to pure (no intercept)
linear form."
[options]
(let [^IFn$OD y (:ground-truth (:attributes options))
data (z/drop-missing y (:data options))
_ (assert (not (z/empty? data)))
datum-name (.getSimpleName (class (z/first data)))
^doubles ys (z/map-to-doubles y data)
;; TODO: can we be sure the order of bindings and
;; (vals bindings) would be the same?
bindings (into (sorted-map)
(dissoc (:attributes options)
:ground-truth
:prediction))
xs (vals bindings)
;; need linear embedding for predictions later
e (:embedding
options
(z/linear-embedding (str datum-name "->En") xs data))]
[ys e bindings data]))
;;----------------------------------------------------------------
;; with intercept models
;;----------------------------------------------------------------
(defn affine-l2-regression
"Train an affine (aka linear) model by minimizing l2 prediction
error on the training data, using apache commons math3
<a href=\"http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.html\">
<code>OLSMultipleLinearRegression</code></a> to do the fitting
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map-to-objects (Class/forName "[D") embed data)
ols (OLSMultipleLinearRegression.)
_ (.newSampleData ols y x)
^doubles beta (.estimateRegressionParameters ols)
;; commons math has intercept as zeroth element
^IFn$OD af (z/affine-functional
(z/linear-functional
(Arrays/copyOfRange beta 1 (alength beta)))
(aget beta 0))]
(FlatModel. af le)))
;;----------------------------------------------------------------
(defn affine-l2
"Train an affine (aka linear) model by minimizing possibly
regularized l2 prediction
error on the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
l2d2 (z/l2distance2-from y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n+1 (inc (.dimension ^LinearEmbedding le))
start (double-array n+1 0.0)
#_ (println "affine" (Arrays/toString start))
adual (z/affine-dual (Dn/get n+1))
costf (z/compose l2d2 (z/compose sample adual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start start
:max-iterations 1000}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/affine-functional beta) le)))
;;----------------------------------------------------------------
(defn affine-l1
"Train an affine (aka linear) model by minimizing possibly
regularized huberized quantile regression prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
hd (z/huberdistance-from
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n+1 (inc (.dimension ^LinearEmbedding le))
adual (z/affine-dual (Dn/get n+1))
costf (z/compose hd (z/compose sample adual))
#_(println "costf" (.toString ^Object costf))
; costf (if (:trace options)
; (z/trace-function costf (:trace options))
; costf)
costf (if (:gradient-check options)
(z/gradient-check costf (:gradient-check options))
costf)
#_(println "costf" (.toString ^Object costf))
cg-options (merge {:objective costf
:start (double-array n+1 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/affine-functional beta) le)))
;;----------------------------------------------------------------
(defn affine-qr
"Train an affine (aka linear) model by minimizing possibly
regularized huberized quantile regression prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
qrd (z/qrdistance-from
(:quantile-p options)
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n+1 (inc (.dimension ^LinearEmbedding le))
adual (z/affine-dual (Dn/get n+1))
costf (z/compose qrd (z/compose sample adual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start (double-array n+1 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/affine-functional beta) le)))
;;----------------------------------------------------------------
;; no intercept models
;;----------------------------------------------------------------
(defn linear-l2-regression
"Train a linear (no intercept) model by minimizing l2 prediction
error on the training data, using apache commons math3
<a href=\"http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.html\">
<code>OLSMultipleLinearRegression</code></a> to do the fitting
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map-to-objects (Class/forName "[D") embed data)
ols (OLSMultipleLinearRegression.)
_ (.setNoIntercept ols true)
_ (.newSampleData ols y x)
^doubles beta (.estimateRegressionParameters ols)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
(defn linear-l2
"Train a linear (no intercept) model by minimizing possibly
regularized l2 prediction
error on the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
l2d2 (z/l2distance2-from y)
sample (z/sampler x)
n (.dimension ^LinearEmbedding le)
start (double-array n 0.0)
#_ (println "affine" (Arrays/toString start))
ldual (z/linear-dual (Dn/get n))
costf (z/compose l2d2 (z/compose sample ldual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start start
:max-iterations 1000}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
(defn linear-l1
"Train a linear (no intercept) model by minimizing possibly
regularized huberized l1 prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
hd (z/huberdistance-from
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n (.dimension ^LinearEmbedding le)
ldual (z/linear-dual (Dn/get n))
costf (z/compose hd (z/compose sample ldual))
#_(println "costf" (.toString ^Object costf))
; costf (if (:trace options)
; (z/trace-function costf (:trace options))
; costf)
costf (if (:gradient-check options)
(z/gradient-check costf (:gradient-check options))
costf)
#_(println "costf" (.toString ^Object costf))
cg-options (merge {:objective costf
:start (double-array n 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
(defn linear-qr
"Train a linear (no intercept) model by minimizing possibly
regularized huberized quantile regression prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
qrd (z/qrdistance-from
(:quantile-p options)
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n (.dimension ^LinearEmbedding le)
ldual (z/linear-dual (Dn/get n))
costf (z/compose qrd (z/compose sample ldual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start (double-array n 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
| 104259 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<EMAIL>o at gmail dot com"
:date "2018-04-14"
:doc
"Flat (affine or linear) models.
<p>
Usual statistics 'linear' model is actually fitting an
affine functional (with intercept case) or a linear
functional (no intercept case)." }
taiga.flat
(:require [zana.api :as z])
(:import [java.util Arrays Map]
[java.io Writer]
[clojure.lang IFn IFn$OD IFn$OOD]
[org.apache.commons.math3.stat.regression
OLSMultipleLinearRegression]
[zana.java.geometry Dn]
#_[zana.java.geometry.functions AffineFunctional]
[zana.java.data AffineEmbedding LinearEmbedding]))
;;----------------------------------------------------------------
;; This ought to be just a function composition, but we need to
;; define a special class so it can be serialized.
;; As it is, an FlatModel is an affine functional (a real-valued
;; function on <b>E</b><sup>p</sup>) composed with an affine
;; embedding of the relevant record type, a function from
;; the specified attributes of record objects to
;; <b>E</b><sup>p</sup>.
;; Note: nothing here really requies the functional to be flat!
;; We are really just composing an embedding of data space into
;; a presumably flat space (though that could be more general)
;; with a 'functional', by which I just mean a real-valued
;; function.
(deftype FlatModel [^IFn$OD functional
^IFn embedding]
java.io.Serializable
IFn$OOD
(invokePrim ^double [_ bindings record]
(.invokePrim ^IFn$OD functional
(.invoke ^IFn embedding bindings record)))
IFn
(invoke [this bindings record]
(.invokePrim ^IFn$OOD this bindings record))
Object
(hashCode [_]
(let [h (int 17)
h (unchecked-multiply-int h (int 31))
h (unchecked-add-int h (.hashCode functional))
h (unchecked-multiply-int h (int 31))
h (unchecked-add-int h (.hashCode embedding))]
h))
(equals [_ that]
(and (instance? FlatModel that)
(.equals functional (.functional ^FlatModel that))
(.equals embedding (.embedding ^FlatModel that))))
(toString [_]
(str "FlatModel[" functional ", " embedding "?}")))
(defn functional ^IFn$OD [^FlatModel am]
(.functional am))
(defn embedding ^IFn [^FlatModel am]
(.embedding am))
#_(defn functional ^AffineFunctional [^FlatModel am]
(.functional am))
#_(defn embedding ^AffineEmbedding [^FlatModel am]
(.embedding am))
;;----------------------------------------------------------------
;; EDN IO
;;----------------------------------------------------------------
(defn map->FlatModel ^FlatModel [^Map m]
(FlatModel.
^IFn$OD (:functional m)
^IFn (:embedding m))
#_(FlatModel.
^AffineFunctional (:functional m)
^AffineEmbedding (:embedding m)))
(defn map<-FlatModel ^Map [^FlatModel this]
{:functional (.functional this) :embedding (.embedding this)})
(defmethod z/clojurize FlatModel [^FlatModel this]
(map<-FlatModel this))
(defmethod print-method FlatModel [^FlatModel this ^Writer w]
(if *print-readably*
(do
(.write w " #taiga.flat.FlatModel ")
(.write w (pr-str (map<-FlatModel this))))
(.write w (print-str (map<-FlatModel this)))))
;;----------------------------------------------------------------
;; EDN input (output just works?)
;;----------------------------------------------------------------
(z/add-edn-readers!
{'taiga.flat.FlatModel map->FlatModel})
;;----------------------------------------------------------------
;; training
;;----------------------------------------------------------------
(defn- check [options]
(assert (not (z/empty? (:data options)))
(print-str "no :data in"
(z/pprint-map-str options)))
(assert (:attributes options)
(str "No :attributes given."
(z/pprint-map-str options)))
(assert (instance? java.util.Map (:attributes options))
(str ":attributes is not a map."
(z/pprint-map-str options)))
;; edge case: zero predictotrs means a constant model
;; TODO: force constants to be different from affine?
(assert (<= 0 (count (dissoc (:attributes options)
:ground-truth :prediction)))
(str ":no predictors:" options))
(assert (every? ifn? (:attributes options))
(str "One of the :attributes is not a function."
(z/pprint-map-str (:attributes options))))
(assert (ifn? (:ground-truth (:attributes options)))
(str "No :ground-truth!"
(z/pprint-map-str options))))
;;----------------------------------------------------------------
(defn- linearize
"Convert the general prediction problem to pure (no intercept)
linear form."
[options]
(let [^IFn$OD y (:ground-truth (:attributes options))
data (z/drop-missing y (:data options))
_ (assert (not (z/empty? data)))
datum-name (.getSimpleName (class (z/first data)))
^doubles ys (z/map-to-doubles y data)
;; TODO: can we be sure the order of bindings and
;; (vals bindings) would be the same?
bindings (into (sorted-map)
(dissoc (:attributes options)
:ground-truth
:prediction))
xs (vals bindings)
;; need linear embedding for predictions later
e (:embedding
options
(z/linear-embedding (str datum-name "->En") xs data))]
[ys e bindings data]))
;;----------------------------------------------------------------
;; with intercept models
;;----------------------------------------------------------------
(defn affine-l2-regression
"Train an affine (aka linear) model by minimizing l2 prediction
error on the training data, using apache commons math3
<a href=\"http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.html\">
<code>OLSMultipleLinearRegression</code></a> to do the fitting
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map-to-objects (Class/forName "[D") embed data)
ols (OLSMultipleLinearRegression.)
_ (.newSampleData ols y x)
^doubles beta (.estimateRegressionParameters ols)
;; commons math has intercept as zeroth element
^IFn$OD af (z/affine-functional
(z/linear-functional
(Arrays/copyOfRange beta 1 (alength beta)))
(aget beta 0))]
(FlatModel. af le)))
;;----------------------------------------------------------------
(defn affine-l2
"Train an affine (aka linear) model by minimizing possibly
regularized l2 prediction
error on the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
l2d2 (z/l2distance2-from y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n+1 (inc (.dimension ^LinearEmbedding le))
start (double-array n+1 0.0)
#_ (println "affine" (Arrays/toString start))
adual (z/affine-dual (Dn/get n+1))
costf (z/compose l2d2 (z/compose sample adual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start start
:max-iterations 1000}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/affine-functional beta) le)))
;;----------------------------------------------------------------
(defn affine-l1
"Train an affine (aka linear) model by minimizing possibly
regularized huberized quantile regression prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
hd (z/huberdistance-from
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n+1 (inc (.dimension ^LinearEmbedding le))
adual (z/affine-dual (Dn/get n+1))
costf (z/compose hd (z/compose sample adual))
#_(println "costf" (.toString ^Object costf))
; costf (if (:trace options)
; (z/trace-function costf (:trace options))
; costf)
costf (if (:gradient-check options)
(z/gradient-check costf (:gradient-check options))
costf)
#_(println "costf" (.toString ^Object costf))
cg-options (merge {:objective costf
:start (double-array n+1 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/affine-functional beta) le)))
;;----------------------------------------------------------------
(defn affine-qr
"Train an affine (aka linear) model by minimizing possibly
regularized huberized quantile regression prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
qrd (z/qrdistance-from
(:quantile-p options)
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n+1 (inc (.dimension ^LinearEmbedding le))
adual (z/affine-dual (Dn/get n+1))
costf (z/compose qrd (z/compose sample adual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start (double-array n+1 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/affine-functional beta) le)))
;;----------------------------------------------------------------
;; no intercept models
;;----------------------------------------------------------------
(defn linear-l2-regression
"Train a linear (no intercept) model by minimizing l2 prediction
error on the training data, using apache commons math3
<a href=\"http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.html\">
<code>OLSMultipleLinearRegression</code></a> to do the fitting
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map-to-objects (Class/forName "[D") embed data)
ols (OLSMultipleLinearRegression.)
_ (.setNoIntercept ols true)
_ (.newSampleData ols y x)
^doubles beta (.estimateRegressionParameters ols)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
(defn linear-l2
"Train a linear (no intercept) model by minimizing possibly
regularized l2 prediction
error on the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
l2d2 (z/l2distance2-from y)
sample (z/sampler x)
n (.dimension ^LinearEmbedding le)
start (double-array n 0.0)
#_ (println "affine" (Arrays/toString start))
ldual (z/linear-dual (Dn/get n))
costf (z/compose l2d2 (z/compose sample ldual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start start
:max-iterations 1000}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
(defn linear-l1
"Train a linear (no intercept) model by minimizing possibly
regularized huberized l1 prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
hd (z/huberdistance-from
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n (.dimension ^LinearEmbedding le)
ldual (z/linear-dual (Dn/get n))
costf (z/compose hd (z/compose sample ldual))
#_(println "costf" (.toString ^Object costf))
; costf (if (:trace options)
; (z/trace-function costf (:trace options))
; costf)
costf (if (:gradient-check options)
(z/gradient-check costf (:gradient-check options))
costf)
#_(println "costf" (.toString ^Object costf))
cg-options (merge {:objective costf
:start (double-array n 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
(defn linear-qr
"Train a linear (no intercept) model by minimizing possibly
regularized huberized quantile regression prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
qrd (z/qrdistance-from
(:quantile-p options)
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n (.dimension ^LinearEmbedding le)
ldual (z/linear-dual (Dn/get n))
costf (z/compose qrd (z/compose sample ldual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start (double-array n 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:EMAIL:<EMAIL>END_PIo at gmail dot com"
:date "2018-04-14"
:doc
"Flat (affine or linear) models.
<p>
Usual statistics 'linear' model is actually fitting an
affine functional (with intercept case) or a linear
functional (no intercept case)." }
taiga.flat
(:require [zana.api :as z])
(:import [java.util Arrays Map]
[java.io Writer]
[clojure.lang IFn IFn$OD IFn$OOD]
[org.apache.commons.math3.stat.regression
OLSMultipleLinearRegression]
[zana.java.geometry Dn]
#_[zana.java.geometry.functions AffineFunctional]
[zana.java.data AffineEmbedding LinearEmbedding]))
;;----------------------------------------------------------------
;; This ought to be just a function composition, but we need to
;; define a special class so it can be serialized.
;; As it is, an FlatModel is an affine functional (a real-valued
;; function on <b>E</b><sup>p</sup>) composed with an affine
;; embedding of the relevant record type, a function from
;; the specified attributes of record objects to
;; <b>E</b><sup>p</sup>.
;; Note: nothing here really requies the functional to be flat!
;; We are really just composing an embedding of data space into
;; a presumably flat space (though that could be more general)
;; with a 'functional', by which I just mean a real-valued
;; function.
(deftype FlatModel [^IFn$OD functional
^IFn embedding]
java.io.Serializable
IFn$OOD
(invokePrim ^double [_ bindings record]
(.invokePrim ^IFn$OD functional
(.invoke ^IFn embedding bindings record)))
IFn
(invoke [this bindings record]
(.invokePrim ^IFn$OOD this bindings record))
Object
(hashCode [_]
(let [h (int 17)
h (unchecked-multiply-int h (int 31))
h (unchecked-add-int h (.hashCode functional))
h (unchecked-multiply-int h (int 31))
h (unchecked-add-int h (.hashCode embedding))]
h))
(equals [_ that]
(and (instance? FlatModel that)
(.equals functional (.functional ^FlatModel that))
(.equals embedding (.embedding ^FlatModel that))))
(toString [_]
(str "FlatModel[" functional ", " embedding "?}")))
(defn functional ^IFn$OD [^FlatModel am]
(.functional am))
(defn embedding ^IFn [^FlatModel am]
(.embedding am))
#_(defn functional ^AffineFunctional [^FlatModel am]
(.functional am))
#_(defn embedding ^AffineEmbedding [^FlatModel am]
(.embedding am))
;;----------------------------------------------------------------
;; EDN IO
;;----------------------------------------------------------------
(defn map->FlatModel ^FlatModel [^Map m]
(FlatModel.
^IFn$OD (:functional m)
^IFn (:embedding m))
#_(FlatModel.
^AffineFunctional (:functional m)
^AffineEmbedding (:embedding m)))
(defn map<-FlatModel ^Map [^FlatModel this]
{:functional (.functional this) :embedding (.embedding this)})
(defmethod z/clojurize FlatModel [^FlatModel this]
(map<-FlatModel this))
(defmethod print-method FlatModel [^FlatModel this ^Writer w]
(if *print-readably*
(do
(.write w " #taiga.flat.FlatModel ")
(.write w (pr-str (map<-FlatModel this))))
(.write w (print-str (map<-FlatModel this)))))
;;----------------------------------------------------------------
;; EDN input (output just works?)
;;----------------------------------------------------------------
(z/add-edn-readers!
{'taiga.flat.FlatModel map->FlatModel})
;;----------------------------------------------------------------
;; training
;;----------------------------------------------------------------
(defn- check [options]
(assert (not (z/empty? (:data options)))
(print-str "no :data in"
(z/pprint-map-str options)))
(assert (:attributes options)
(str "No :attributes given."
(z/pprint-map-str options)))
(assert (instance? java.util.Map (:attributes options))
(str ":attributes is not a map."
(z/pprint-map-str options)))
;; edge case: zero predictotrs means a constant model
;; TODO: force constants to be different from affine?
(assert (<= 0 (count (dissoc (:attributes options)
:ground-truth :prediction)))
(str ":no predictors:" options))
(assert (every? ifn? (:attributes options))
(str "One of the :attributes is not a function."
(z/pprint-map-str (:attributes options))))
(assert (ifn? (:ground-truth (:attributes options)))
(str "No :ground-truth!"
(z/pprint-map-str options))))
;;----------------------------------------------------------------
(defn- linearize
"Convert the general prediction problem to pure (no intercept)
linear form."
[options]
(let [^IFn$OD y (:ground-truth (:attributes options))
data (z/drop-missing y (:data options))
_ (assert (not (z/empty? data)))
datum-name (.getSimpleName (class (z/first data)))
^doubles ys (z/map-to-doubles y data)
;; TODO: can we be sure the order of bindings and
;; (vals bindings) would be the same?
bindings (into (sorted-map)
(dissoc (:attributes options)
:ground-truth
:prediction))
xs (vals bindings)
;; need linear embedding for predictions later
e (:embedding
options
(z/linear-embedding (str datum-name "->En") xs data))]
[ys e bindings data]))
;;----------------------------------------------------------------
;; with intercept models
;;----------------------------------------------------------------
(defn affine-l2-regression
"Train an affine (aka linear) model by minimizing l2 prediction
error on the training data, using apache commons math3
<a href=\"http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.html\">
<code>OLSMultipleLinearRegression</code></a> to do the fitting
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map-to-objects (Class/forName "[D") embed data)
ols (OLSMultipleLinearRegression.)
_ (.newSampleData ols y x)
^doubles beta (.estimateRegressionParameters ols)
;; commons math has intercept as zeroth element
^IFn$OD af (z/affine-functional
(z/linear-functional
(Arrays/copyOfRange beta 1 (alength beta)))
(aget beta 0))]
(FlatModel. af le)))
;;----------------------------------------------------------------
(defn affine-l2
"Train an affine (aka linear) model by minimizing possibly
regularized l2 prediction
error on the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
l2d2 (z/l2distance2-from y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n+1 (inc (.dimension ^LinearEmbedding le))
start (double-array n+1 0.0)
#_ (println "affine" (Arrays/toString start))
adual (z/affine-dual (Dn/get n+1))
costf (z/compose l2d2 (z/compose sample adual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start start
:max-iterations 1000}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/affine-functional beta) le)))
;;----------------------------------------------------------------
(defn affine-l1
"Train an affine (aka linear) model by minimizing possibly
regularized huberized quantile regression prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
hd (z/huberdistance-from
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n+1 (inc (.dimension ^LinearEmbedding le))
adual (z/affine-dual (Dn/get n+1))
costf (z/compose hd (z/compose sample adual))
#_(println "costf" (.toString ^Object costf))
; costf (if (:trace options)
; (z/trace-function costf (:trace options))
; costf)
costf (if (:gradient-check options)
(z/gradient-check costf (:gradient-check options))
costf)
#_(println "costf" (.toString ^Object costf))
cg-options (merge {:objective costf
:start (double-array n+1 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/affine-functional beta) le)))
;;----------------------------------------------------------------
(defn affine-qr
"Train an affine (aka linear) model by minimizing possibly
regularized huberized quantile regression prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
qrd (z/qrdistance-from
(:quantile-p options)
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n+1 (inc (.dimension ^LinearEmbedding le))
adual (z/affine-dual (Dn/get n+1))
costf (z/compose qrd (z/compose sample adual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start (double-array n+1 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/affine-functional beta) le)))
;;----------------------------------------------------------------
;; no intercept models
;;----------------------------------------------------------------
(defn linear-l2-regression
"Train a linear (no intercept) model by minimizing l2 prediction
error on the training data, using apache commons math3
<a href=\"http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.html\">
<code>OLSMultipleLinearRegression</code></a> to do the fitting
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map-to-objects (Class/forName "[D") embed data)
ols (OLSMultipleLinearRegression.)
_ (.setNoIntercept ols true)
_ (.newSampleData ols y x)
^doubles beta (.estimateRegressionParameters ols)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
(defn linear-l2
"Train a linear (no intercept) model by minimizing possibly
regularized l2 prediction
error on the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
l2d2 (z/l2distance2-from y)
sample (z/sampler x)
n (.dimension ^LinearEmbedding le)
start (double-array n 0.0)
#_ (println "affine" (Arrays/toString start))
ldual (z/linear-dual (Dn/get n))
costf (z/compose l2d2 (z/compose sample ldual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start start
:max-iterations 1000}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
(defn linear-l1
"Train a linear (no intercept) model by minimizing possibly
regularized huberized l1 prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
hd (z/huberdistance-from
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n (.dimension ^LinearEmbedding le)
ldual (z/linear-dual (Dn/get n))
costf (z/compose hd (z/compose sample ldual))
#_(println "costf" (.toString ^Object costf))
; costf (if (:trace options)
; (z/trace-function costf (:trace options))
; costf)
costf (if (:gradient-check options)
(z/gradient-check costf (:gradient-check options))
costf)
#_(println "costf" (.toString ^Object costf))
cg-options (merge {:objective costf
:start (double-array n 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
(defn linear-qr
"Train a linear (no intercept) model by minimizing possibly
regularized huberized quantile regression prediction cost on
the training data, using nonlinear conjugate gradients
(<code>zana/optimize-cg</code>) to do the fitting.
<p>
<code>^clojure.lang.IPersistentMap options</code></dt>
a map containing options used directly by
<code>l2</code> and passed to functions called by
<code>l2</code>:
<dl>
<dt><code>:attributes</code></dt>
<dd>
a map from keywords to attribute functions, functions which can
be applied to the elements of <code>:data</code>.
Must include <code>:ground-truth</code>. Key-value pairs other
than <code>:ground-truth</code> and <code>:prediction</code>
are used as predictors in the forest.<br>
Attribute functions are treated as numerical if they implement
<code>clojure.lang.IFn$OD</code> or if their value on every
element of <code>:data</code> is a <code>Number</code>.
Implementing <code>clojure.lang.IFn$OD</code> will result in
much higher performance.
<br>
Missing data for numerical attributes is represented by
returning <code>Double/NaN</code>.
<br>
Any other attribute functions are treated as categorical. There
is no hard limit on the number of categories allowed. Too large
a number of categories is likely to result in overfitting. The
best way to detect overfitting is to compare accuracy on the
training data to accuracy on a fair test set. If training
accuracy is much better, looking at the number of distinct
values for the categorical attributes is one of the first
things to check.
</dd>
<dt><code>:data</code></dt>
<dd>
a finite <code>Iterable</code> whose elements are valid inputs
to the attribute functions.
</dd>
<dt><code>:embedding</code></dt>
<dd>
TODO
</dd>
</dl>"
^IFn$OOD [options]
#_(println (z/pprint-map-str options))
(check options)
;; TODO: straighten out affine vs linear embeddings
(let [[y le bindings data] (linearize options)
embed (fn ^doubles [datum] (le bindings datum))
x (z/map embed data)
qrd (z/qrdistance-from
(:quantile-p options)
(:huber-epsilon options)
y)
sample (z/sampler x)
;; dimension of linear homogeneous coordinate space
n (.dimension ^LinearEmbedding le)
ldual (z/linear-dual (Dn/get n))
costf (z/compose qrd (z/compose sample ldual))
#_(println "costf" costf)
cg-options (merge {:objective costf
:start (double-array n 0.0)
:max-iterations 100}
options)
[^doubles beta ^double cost] (z/optimize-cg cg-options)]
(FlatModel. (z/linear-functional beta) le)))
;;----------------------------------------------------------------
|
[
{
"context": "refer [make-styles]]))\n\n(def suit-names {:acorns \"Eichel\"\n :leaves \"Gras\"\n ",
"end": 248,
"score": 0.7541513442993164,
"start": 242,
"tag": "NAME",
"value": "Eichel"
},
{
"context": " :leaves \"Gras\"\n :hearts \"Herz\"\n :bells \"Schellen\"})\n\n(def rank-",
"end": 312,
"score": 0.6695711016654968,
"start": 311,
"tag": "NAME",
"value": "z"
},
{
"context": " :bells \"Schellen\"})\n\n(def rank-names {:unter \"Unter\"\n :ober \"Ober\"\n :",
"end": 382,
"score": 0.6452849507331848,
"start": 377,
"tag": "NAME",
"value": "Unter"
}
] | src/schafkopf/frontend/components/playing_card.cljs | ferdinand-beyer/schafkopf | 1 | (ns schafkopf.frontend.components.playing-card
(:require [mui-bien.core.button-base :refer [button-base]]
[mui-bien.core.paper :refer [paper]]
[mui-bien.core.styles :refer [make-styles]]))
(def suit-names {:acorns "Eichel"
:leaves "Gras"
:hearts "Herz"
:bells "Schellen"})
(def rank-names {:unter "Unter"
:ober "Ober"
:king "König"
:deuce "Daus"})
(defn card-key [[rank suit]]
(str (if (keyword? rank) (name rank) rank) "-" (name suit)))
(defn card-name [[rank suit]]
(str (get suit-names suit) " " (get rank-names rank rank)))
(def w 224)
(def h 400)
(def border-radius 24)
(def scale 0.5)
(def sprites-url (str "/assets/img/decks/fxs/sprites-" w "x" h ".webp"))
(defn rank-class [rank]
(if (keyword? rank)
rank
(keyword (str "r-" rank))))
(def ranks [:deuce :king :ober :unter :r-10 :r-9 :r-8 :r-7])
(def suits [:acorns :leaves :hearts :bells])
(def styles
(->
{:root {:max-width w
:max-height h
:width (* w scale)
:height (* h scale)
:border-radius (str (* (/ border-radius w) 100) "%/"
(* (/ border-radius h) 100) "%")
:overflow :hidden}
:sprite {:max-width w
:max-height h
:width (* w scale)
:height (* h scale)}
:texture {:width "100%"
:height 0
:padding-bottom (str (* (/ h w) 100) "%")
:background-image (str "url('" sprites-url "')")
:background-repeat "no-repeat"
:background-size "800%"}}
(into (map-indexed
(fn [i r]
[(rank-class r)
{:background-position-x (str (* i (/ 100 7)) "%")}])
ranks))
(into (map-indexed
(fn [i s]
[s {:background-position-y (str (* i (/ 100 3)) "%")}])
suits))))
(def use-styles (make-styles styles {:name "card"}))
(defn card-sprite*
[{:keys [card classes]}]
(let [[rank suit] card]
[:div
{:class (:sprite classes)}
[:div
{:class [(:texture classes)
(classes (rank-class rank))
(classes suit)]}]]))
(defn playing-card*
[{:keys [card class elevation
button? disabled? on-click]
:or {elevation 1
button? false}}]
(let [classes (use-styles)
sprite [:f> card-sprite* {:card card, :classes classes}]]
[paper
{:elevation elevation
:class class
:classes {:root (:root classes)}}
(if button?
[button-base
{:focus-ripple true
:disabled disabled?
:on-click on-click}
sprite]
sprite)]))
(defn playing-card
[props]
[:f> playing-card* props])
| 3820 | (ns schafkopf.frontend.components.playing-card
(:require [mui-bien.core.button-base :refer [button-base]]
[mui-bien.core.paper :refer [paper]]
[mui-bien.core.styles :refer [make-styles]]))
(def suit-names {:acorns "<NAME>"
:leaves "Gras"
:hearts "Her<NAME>"
:bells "Schellen"})
(def rank-names {:unter "<NAME>"
:ober "Ober"
:king "König"
:deuce "Daus"})
(defn card-key [[rank suit]]
(str (if (keyword? rank) (name rank) rank) "-" (name suit)))
(defn card-name [[rank suit]]
(str (get suit-names suit) " " (get rank-names rank rank)))
(def w 224)
(def h 400)
(def border-radius 24)
(def scale 0.5)
(def sprites-url (str "/assets/img/decks/fxs/sprites-" w "x" h ".webp"))
(defn rank-class [rank]
(if (keyword? rank)
rank
(keyword (str "r-" rank))))
(def ranks [:deuce :king :ober :unter :r-10 :r-9 :r-8 :r-7])
(def suits [:acorns :leaves :hearts :bells])
(def styles
(->
{:root {:max-width w
:max-height h
:width (* w scale)
:height (* h scale)
:border-radius (str (* (/ border-radius w) 100) "%/"
(* (/ border-radius h) 100) "%")
:overflow :hidden}
:sprite {:max-width w
:max-height h
:width (* w scale)
:height (* h scale)}
:texture {:width "100%"
:height 0
:padding-bottom (str (* (/ h w) 100) "%")
:background-image (str "url('" sprites-url "')")
:background-repeat "no-repeat"
:background-size "800%"}}
(into (map-indexed
(fn [i r]
[(rank-class r)
{:background-position-x (str (* i (/ 100 7)) "%")}])
ranks))
(into (map-indexed
(fn [i s]
[s {:background-position-y (str (* i (/ 100 3)) "%")}])
suits))))
(def use-styles (make-styles styles {:name "card"}))
(defn card-sprite*
[{:keys [card classes]}]
(let [[rank suit] card]
[:div
{:class (:sprite classes)}
[:div
{:class [(:texture classes)
(classes (rank-class rank))
(classes suit)]}]]))
(defn playing-card*
[{:keys [card class elevation
button? disabled? on-click]
:or {elevation 1
button? false}}]
(let [classes (use-styles)
sprite [:f> card-sprite* {:card card, :classes classes}]]
[paper
{:elevation elevation
:class class
:classes {:root (:root classes)}}
(if button?
[button-base
{:focus-ripple true
:disabled disabled?
:on-click on-click}
sprite]
sprite)]))
(defn playing-card
[props]
[:f> playing-card* props])
| true | (ns schafkopf.frontend.components.playing-card
(:require [mui-bien.core.button-base :refer [button-base]]
[mui-bien.core.paper :refer [paper]]
[mui-bien.core.styles :refer [make-styles]]))
(def suit-names {:acorns "PI:NAME:<NAME>END_PI"
:leaves "Gras"
:hearts "HerPI:NAME:<NAME>END_PI"
:bells "Schellen"})
(def rank-names {:unter "PI:NAME:<NAME>END_PI"
:ober "Ober"
:king "König"
:deuce "Daus"})
(defn card-key [[rank suit]]
(str (if (keyword? rank) (name rank) rank) "-" (name suit)))
(defn card-name [[rank suit]]
(str (get suit-names suit) " " (get rank-names rank rank)))
(def w 224)
(def h 400)
(def border-radius 24)
(def scale 0.5)
(def sprites-url (str "/assets/img/decks/fxs/sprites-" w "x" h ".webp"))
(defn rank-class [rank]
(if (keyword? rank)
rank
(keyword (str "r-" rank))))
(def ranks [:deuce :king :ober :unter :r-10 :r-9 :r-8 :r-7])
(def suits [:acorns :leaves :hearts :bells])
(def styles
(->
{:root {:max-width w
:max-height h
:width (* w scale)
:height (* h scale)
:border-radius (str (* (/ border-radius w) 100) "%/"
(* (/ border-radius h) 100) "%")
:overflow :hidden}
:sprite {:max-width w
:max-height h
:width (* w scale)
:height (* h scale)}
:texture {:width "100%"
:height 0
:padding-bottom (str (* (/ h w) 100) "%")
:background-image (str "url('" sprites-url "')")
:background-repeat "no-repeat"
:background-size "800%"}}
(into (map-indexed
(fn [i r]
[(rank-class r)
{:background-position-x (str (* i (/ 100 7)) "%")}])
ranks))
(into (map-indexed
(fn [i s]
[s {:background-position-y (str (* i (/ 100 3)) "%")}])
suits))))
(def use-styles (make-styles styles {:name "card"}))
(defn card-sprite*
[{:keys [card classes]}]
(let [[rank suit] card]
[:div
{:class (:sprite classes)}
[:div
{:class [(:texture classes)
(classes (rank-class rank))
(classes suit)]}]]))
(defn playing-card*
[{:keys [card class elevation
button? disabled? on-click]
:or {elevation 1
button? false}}]
(let [classes (use-styles)
sprite [:f> card-sprite* {:card card, :classes classes}]]
[paper
{:elevation elevation
:class class
:classes {:root (:root classes)}}
(if button?
[button-base
{:focus-ripple true
:disabled disabled?
:on-click on-click}
sprite]
sprite)]))
(defn playing-card
[props]
[:f> playing-card* props])
|
[
{
"context": ";-\n; Copyright 2009-2011 (c) Meikel Brandmeyer.\n; All rights reserved.\n;\n; Permission is hereby ",
"end": 46,
"score": 0.9998601675033569,
"start": 29,
"tag": "NAME",
"value": "Meikel Brandmeyer"
},
{
"context": " in a dedicated daemon thread. host defaults\n to 127.0.0.1, port to 2113.\"\n ([] (start-server-thread \"1",
"end": 1791,
"score": 0.9997198581695557,
"start": 1782,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "1, port to 2113.\"\n ([] (start-server-thread \"127.0.0.1\" 2113))\n ([host] (start-server-thread host 2113)",
"end": 1849,
"score": 0.9997422695159912,
"start": 1840,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | data/clojure/42916f4650c72236faca1c797ebd0014_nails.clj | maxim5/code-inspector | 5 | ;-
; Copyright 2009-2011 (c) Meikel Brandmeyer.
; All rights reserved.
;
; 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 vimclojure.nails
(:require
[vimclojure.repl :as repl]
[vimclojure.util :as util]
[vimclojure.backend :as backend]
clojure.set
clojure.test)
(:import
java.io.BufferedReader
java.io.ByteArrayOutputStream
java.io.InputStreamReader
java.io.OutputStreamWriter
java.io.PrintStream
java.io.PrintWriter
clojure.lang.LineNumberingPushbackReader
vimclojure.nailgun.NGContext
vimclojure.nailgun.NGServer
vimclojure.nailgun.ThreadLocalInputStream
vimclojure.nailgun.ThreadLocalPrintStream))
(defn start-server-thread
"Start a nailgun server in a dedicated daemon thread. host defaults
to 127.0.0.1, port to 2113."
([] (start-server-thread "127.0.0.1" 2113))
([host] (start-server-thread host 2113))
([host port]
(doto (Thread. #(NGServer/main (into-array [(str host ":" port)])))
(.setDaemon true)
(.start))))
(defn- make-stream-set
[in out err encoding]
[(-> in (InputStreamReader. encoding) LineNumberingPushbackReader.)
(-> out (OutputStreamWriter. encoding))
(-> err (OutputStreamWriter. encoding) PrintWriter.)])
(defn- set-input-stream
[#^ThreadLocalInputStream sys local]
(let [old (.getInputStream sys)]
(.init sys local)
old))
(defn- set-output-stream
[#^ThreadLocalPrintStream sys local]
(let [old (.getPrintStream sys)]
(.init sys local)
old))
(defn nail-driver
"Driver for the defnail macro."
[#^NGContext ctx nail]
(let [out (ByteArrayOutputStream.)
err (ByteArrayOutputStream.)
encoding (System/getProperty "clojure.vim.encoding" "UTF-8")
[clj-in clj-out clj-err] (make-stream-set (.in ctx) out err encoding)
sys-in (set-input-stream System/in (.in ctx))
sys-out (set-output-stream System/out (PrintStream. out))
sys-err (set-output-stream System/err (PrintStream. err))
result (binding [*in* clj-in
*out* clj-out
*err* clj-err]
(try
(nail ctx)
(catch Throwable e
(.printStackTrace e))))]
(.flush clj-out)
(.flush clj-err)
(set-input-stream System/in sys-in)
(set-output-stream System/out sys-out)
(set-output-stream System/err sys-err)
(let [output (.getBytes
(print-str
(util/clj->vim
{:value result
:stdout (.toString out encoding)
:stderr (.toString err encoding)}))
encoding)]
(.write (.out ctx) output 0 (alength output)))
(.flush (.out ctx))))
(defmacro defnail
"Define a new Nail of the given name. The arguments is a command line
arguments specification vector suitable for with-command-line. The body
will be installed as the body of the nail with the command-line arguments
available according to the specification and the nailgun context as
'nailContext'."
[nail usage arguments & body]
`(defn ~nail
[ctx#]
(nail-driver ctx#
(fn [~(with-meta 'nailContext {:tag `NGContext})]
(util/with-command-line (next (.getArgs ~'nailContext))
~usage
~arguments
~@body)))))
(defnail DocLookup
"Usage: ng vimclojure.nails.DocString [options] symbol ..."
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)]
(backend/doc-lookup nspace (read))))
(defnail FindDoc
"Usage: ng vimclojure.nails.FindDoc"
[]
(backend/find-documentation (.readLine *in*)))
(defnail JavadocPath
"Usage: ng vimclojure.nails.JavadocPath [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
backend/javadoc-path-for-class)))
(defnail SourceLookup
"Usage: ng vimclojure.nails.SourceLookup [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
backend/get-source
println)))
(defnail MetaLookup
"Usage: ng vimclojure.nails.MetaLookup [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
meta
util/pretty-print)))
(defnail SourceLocation
"Usage: ng vimclojure.nails.SourceLocation [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
backend/source-position)))
(defnail DynamicHighlighting
"Usage: ng vimclojure.nails.DynamicHighlighting"
[]
(let [nspace (read)
c-c (the-ns 'clojure.core)
the-space (util/resolve-and-load-namespace nspace)
refers (remove #(= c-c (-> % second meta :ns)) (ns-refers the-space))
aliases (mapcat (fn [[the-alias the-alias-space]]
(map #(vector (symbol (name the-alias)
(name (first %)))
(second %))
(ns-publics the-alias-space)))
(ns-aliases the-space))
namespaces (mapcat (fn [the-namespace]
(map #(vector (symbol
(name (ns-name the-namespace))
(name (first %)))
(second %))
(ns-publics the-namespace)))
(remove #(= c-c %) (all-ns)))
vars (set (concat refers aliases namespaces))
macros (set (filter #(-> % second meta :macro) vars))
vars (clojure.set/difference vars macros)
fns (set (filter #(let [v (util/safe-var-get (second %))]
(or (fn? v)
(instance? clojure.lang.MultiFn v)))
vars))
vars (clojure.set/difference vars fns)]
(hash-map "Func" (map first fns)
"Macro" (map first macros)
"Variable" (map first vars))))
(defnail NamespaceOfFile
"Usage: ng vimclojure.nails.NamespaceOfFile"
[]
(let [of-interest '#{in-ns ns clojure.core/in-ns clojure.core/ns}
in-seq (util/stream->seq *in*)
candidate (first
(drop-while #(or (not (instance? clojure.lang.ISeq %))
(not (contains? of-interest (first %))))
in-seq))]
(cond
(not (instance? clojure.lang.ISeq candidate)) "user"
('#{ns clojure.core/ns} (first candidate)) (second candidate)
('#{in-ns clojure.core/in-ns} (first candidate)) (-> candidate
second
second))))
(defnail NamespaceInfo
"Usage: ng vimclojure.nails.NamespaceInfo"
[]
(println (util/clj->vim (map #(-> % symbol find-ns backend/ns-info)
(line-seq (BufferedReader. *in*))))))
(defnail MacroExpand
"Usage: ng vimclojure.nails.MacroExpand [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]
[one? o "Expand only the first macro."]]
(let [nspace (util/resolve-and-load-namespace nspace)
expand (if one
#(macroexpand-1 %)
#(macroexpand %))]
(binding [*ns* nspace]
(-> (read)
expand
util/pretty-print-code))))
(defnail Repl
"Usage: ng vimclojure.nails.Repl [options]"
[[start? s "Start a new Repl."]
[stop? S "Stop the Repl of the given id."]
[run? r "Run the input in the Repl context of the given id."]
[id i "The id of the repl to act on." "-1"]
[nspace n "Change to namespace before executing the input." ""]
[file f "The filename to be set." "REPL"]
[line l "The initial line to be set." "0"]
[ignore? I "Ignore the command with respect to *1, *2, *3"]]
(let [id (Integer/parseInt id)
line (Integer/parseInt line)
nspace (when (not= nspace "")
(util/resolve-and-load-namespace nspace))]
(cond
start {:id (repl/start nspace)}
stop (repl/stop id)
run (repl/run id nspace file line ignore))))
(defnail ReplNamespace
"Usage: ng vimclojure.nails.Repl [options]"
[[id i "The id of the repl to act on."]]
(let [id (Integer/parseInt id)]
(get (get @repl/*repls* id {:ns "user"}) :ns)))
(defnail CheckSyntax
"Usage: ng vimclojure.nails.CheckSyntax"
[[nspace n "Change to namespace before executing the input." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)]
(binding [*ns* nspace]
(try
(let [eof (Object.)]
(loop [x nil]
(if (identical? x eof)
true
(recur (read *in* false eof)))))
(catch clojure.lang.LispReader$ReaderException exc
(let [e (.getCause exc)]
(if (.startsWith (.getMessage e) "EOF while reading")
false
(throw exc))))))))
(defnail Complete
"Usage: ng vimclojure.nails.Complete"
[[nspace n "Start completion in this namespace." "user"]
[prefix p "Prefix used for the match, ie. the part before /." ""]
[base b "Base pattern to be matched."]]
(let [nspace (util/resolve-and-load-namespace nspace)
prefix (symbol prefix)
to-complete (util/decide-completion-in nspace prefix base)
completions (mapcat #(backend/complete % nspace prefix base)
to-complete)]
(map #(apply util/make-completion-item %) completions)))
(defnail RunTests
"Usage: ng vimclojure.nails.RunTests"
[[nspace n "Run tests in the given namespace." "user"]
[all? a "Reload all or only the namespace under test"]]
(when (not= "user" nspace)
(if all
(require :reload-all (symbol nspace))
(require :reload (symbol nspace))))
(binding [clojure.test/*test-out* *out*]
(clojure.test/run-tests (symbol nspace)))
nil)
| 120319 | ;-
; Copyright 2009-2011 (c) <NAME>.
; All rights reserved.
;
; 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 vimclojure.nails
(:require
[vimclojure.repl :as repl]
[vimclojure.util :as util]
[vimclojure.backend :as backend]
clojure.set
clojure.test)
(:import
java.io.BufferedReader
java.io.ByteArrayOutputStream
java.io.InputStreamReader
java.io.OutputStreamWriter
java.io.PrintStream
java.io.PrintWriter
clojure.lang.LineNumberingPushbackReader
vimclojure.nailgun.NGContext
vimclojure.nailgun.NGServer
vimclojure.nailgun.ThreadLocalInputStream
vimclojure.nailgun.ThreadLocalPrintStream))
(defn start-server-thread
"Start a nailgun server in a dedicated daemon thread. host defaults
to 127.0.0.1, port to 2113."
([] (start-server-thread "127.0.0.1" 2113))
([host] (start-server-thread host 2113))
([host port]
(doto (Thread. #(NGServer/main (into-array [(str host ":" port)])))
(.setDaemon true)
(.start))))
(defn- make-stream-set
[in out err encoding]
[(-> in (InputStreamReader. encoding) LineNumberingPushbackReader.)
(-> out (OutputStreamWriter. encoding))
(-> err (OutputStreamWriter. encoding) PrintWriter.)])
(defn- set-input-stream
[#^ThreadLocalInputStream sys local]
(let [old (.getInputStream sys)]
(.init sys local)
old))
(defn- set-output-stream
[#^ThreadLocalPrintStream sys local]
(let [old (.getPrintStream sys)]
(.init sys local)
old))
(defn nail-driver
"Driver for the defnail macro."
[#^NGContext ctx nail]
(let [out (ByteArrayOutputStream.)
err (ByteArrayOutputStream.)
encoding (System/getProperty "clojure.vim.encoding" "UTF-8")
[clj-in clj-out clj-err] (make-stream-set (.in ctx) out err encoding)
sys-in (set-input-stream System/in (.in ctx))
sys-out (set-output-stream System/out (PrintStream. out))
sys-err (set-output-stream System/err (PrintStream. err))
result (binding [*in* clj-in
*out* clj-out
*err* clj-err]
(try
(nail ctx)
(catch Throwable e
(.printStackTrace e))))]
(.flush clj-out)
(.flush clj-err)
(set-input-stream System/in sys-in)
(set-output-stream System/out sys-out)
(set-output-stream System/err sys-err)
(let [output (.getBytes
(print-str
(util/clj->vim
{:value result
:stdout (.toString out encoding)
:stderr (.toString err encoding)}))
encoding)]
(.write (.out ctx) output 0 (alength output)))
(.flush (.out ctx))))
(defmacro defnail
"Define a new Nail of the given name. The arguments is a command line
arguments specification vector suitable for with-command-line. The body
will be installed as the body of the nail with the command-line arguments
available according to the specification and the nailgun context as
'nailContext'."
[nail usage arguments & body]
`(defn ~nail
[ctx#]
(nail-driver ctx#
(fn [~(with-meta 'nailContext {:tag `NGContext})]
(util/with-command-line (next (.getArgs ~'nailContext))
~usage
~arguments
~@body)))))
(defnail DocLookup
"Usage: ng vimclojure.nails.DocString [options] symbol ..."
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)]
(backend/doc-lookup nspace (read))))
(defnail FindDoc
"Usage: ng vimclojure.nails.FindDoc"
[]
(backend/find-documentation (.readLine *in*)))
(defnail JavadocPath
"Usage: ng vimclojure.nails.JavadocPath [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
backend/javadoc-path-for-class)))
(defnail SourceLookup
"Usage: ng vimclojure.nails.SourceLookup [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
backend/get-source
println)))
(defnail MetaLookup
"Usage: ng vimclojure.nails.MetaLookup [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
meta
util/pretty-print)))
(defnail SourceLocation
"Usage: ng vimclojure.nails.SourceLocation [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
backend/source-position)))
(defnail DynamicHighlighting
"Usage: ng vimclojure.nails.DynamicHighlighting"
[]
(let [nspace (read)
c-c (the-ns 'clojure.core)
the-space (util/resolve-and-load-namespace nspace)
refers (remove #(= c-c (-> % second meta :ns)) (ns-refers the-space))
aliases (mapcat (fn [[the-alias the-alias-space]]
(map #(vector (symbol (name the-alias)
(name (first %)))
(second %))
(ns-publics the-alias-space)))
(ns-aliases the-space))
namespaces (mapcat (fn [the-namespace]
(map #(vector (symbol
(name (ns-name the-namespace))
(name (first %)))
(second %))
(ns-publics the-namespace)))
(remove #(= c-c %) (all-ns)))
vars (set (concat refers aliases namespaces))
macros (set (filter #(-> % second meta :macro) vars))
vars (clojure.set/difference vars macros)
fns (set (filter #(let [v (util/safe-var-get (second %))]
(or (fn? v)
(instance? clojure.lang.MultiFn v)))
vars))
vars (clojure.set/difference vars fns)]
(hash-map "Func" (map first fns)
"Macro" (map first macros)
"Variable" (map first vars))))
(defnail NamespaceOfFile
"Usage: ng vimclojure.nails.NamespaceOfFile"
[]
(let [of-interest '#{in-ns ns clojure.core/in-ns clojure.core/ns}
in-seq (util/stream->seq *in*)
candidate (first
(drop-while #(or (not (instance? clojure.lang.ISeq %))
(not (contains? of-interest (first %))))
in-seq))]
(cond
(not (instance? clojure.lang.ISeq candidate)) "user"
('#{ns clojure.core/ns} (first candidate)) (second candidate)
('#{in-ns clojure.core/in-ns} (first candidate)) (-> candidate
second
second))))
(defnail NamespaceInfo
"Usage: ng vimclojure.nails.NamespaceInfo"
[]
(println (util/clj->vim (map #(-> % symbol find-ns backend/ns-info)
(line-seq (BufferedReader. *in*))))))
(defnail MacroExpand
"Usage: ng vimclojure.nails.MacroExpand [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]
[one? o "Expand only the first macro."]]
(let [nspace (util/resolve-and-load-namespace nspace)
expand (if one
#(macroexpand-1 %)
#(macroexpand %))]
(binding [*ns* nspace]
(-> (read)
expand
util/pretty-print-code))))
(defnail Repl
"Usage: ng vimclojure.nails.Repl [options]"
[[start? s "Start a new Repl."]
[stop? S "Stop the Repl of the given id."]
[run? r "Run the input in the Repl context of the given id."]
[id i "The id of the repl to act on." "-1"]
[nspace n "Change to namespace before executing the input." ""]
[file f "The filename to be set." "REPL"]
[line l "The initial line to be set." "0"]
[ignore? I "Ignore the command with respect to *1, *2, *3"]]
(let [id (Integer/parseInt id)
line (Integer/parseInt line)
nspace (when (not= nspace "")
(util/resolve-and-load-namespace nspace))]
(cond
start {:id (repl/start nspace)}
stop (repl/stop id)
run (repl/run id nspace file line ignore))))
(defnail ReplNamespace
"Usage: ng vimclojure.nails.Repl [options]"
[[id i "The id of the repl to act on."]]
(let [id (Integer/parseInt id)]
(get (get @repl/*repls* id {:ns "user"}) :ns)))
(defnail CheckSyntax
"Usage: ng vimclojure.nails.CheckSyntax"
[[nspace n "Change to namespace before executing the input." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)]
(binding [*ns* nspace]
(try
(let [eof (Object.)]
(loop [x nil]
(if (identical? x eof)
true
(recur (read *in* false eof)))))
(catch clojure.lang.LispReader$ReaderException exc
(let [e (.getCause exc)]
(if (.startsWith (.getMessage e) "EOF while reading")
false
(throw exc))))))))
(defnail Complete
"Usage: ng vimclojure.nails.Complete"
[[nspace n "Start completion in this namespace." "user"]
[prefix p "Prefix used for the match, ie. the part before /." ""]
[base b "Base pattern to be matched."]]
(let [nspace (util/resolve-and-load-namespace nspace)
prefix (symbol prefix)
to-complete (util/decide-completion-in nspace prefix base)
completions (mapcat #(backend/complete % nspace prefix base)
to-complete)]
(map #(apply util/make-completion-item %) completions)))
(defnail RunTests
"Usage: ng vimclojure.nails.RunTests"
[[nspace n "Run tests in the given namespace." "user"]
[all? a "Reload all or only the namespace under test"]]
(when (not= "user" nspace)
(if all
(require :reload-all (symbol nspace))
(require :reload (symbol nspace))))
(binding [clojure.test/*test-out* *out*]
(clojure.test/run-tests (symbol nspace)))
nil)
| true | ;-
; Copyright 2009-2011 (c) PI:NAME:<NAME>END_PI.
; All rights reserved.
;
; 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 vimclojure.nails
(:require
[vimclojure.repl :as repl]
[vimclojure.util :as util]
[vimclojure.backend :as backend]
clojure.set
clojure.test)
(:import
java.io.BufferedReader
java.io.ByteArrayOutputStream
java.io.InputStreamReader
java.io.OutputStreamWriter
java.io.PrintStream
java.io.PrintWriter
clojure.lang.LineNumberingPushbackReader
vimclojure.nailgun.NGContext
vimclojure.nailgun.NGServer
vimclojure.nailgun.ThreadLocalInputStream
vimclojure.nailgun.ThreadLocalPrintStream))
(defn start-server-thread
"Start a nailgun server in a dedicated daemon thread. host defaults
to 127.0.0.1, port to 2113."
([] (start-server-thread "127.0.0.1" 2113))
([host] (start-server-thread host 2113))
([host port]
(doto (Thread. #(NGServer/main (into-array [(str host ":" port)])))
(.setDaemon true)
(.start))))
(defn- make-stream-set
[in out err encoding]
[(-> in (InputStreamReader. encoding) LineNumberingPushbackReader.)
(-> out (OutputStreamWriter. encoding))
(-> err (OutputStreamWriter. encoding) PrintWriter.)])
(defn- set-input-stream
[#^ThreadLocalInputStream sys local]
(let [old (.getInputStream sys)]
(.init sys local)
old))
(defn- set-output-stream
[#^ThreadLocalPrintStream sys local]
(let [old (.getPrintStream sys)]
(.init sys local)
old))
(defn nail-driver
"Driver for the defnail macro."
[#^NGContext ctx nail]
(let [out (ByteArrayOutputStream.)
err (ByteArrayOutputStream.)
encoding (System/getProperty "clojure.vim.encoding" "UTF-8")
[clj-in clj-out clj-err] (make-stream-set (.in ctx) out err encoding)
sys-in (set-input-stream System/in (.in ctx))
sys-out (set-output-stream System/out (PrintStream. out))
sys-err (set-output-stream System/err (PrintStream. err))
result (binding [*in* clj-in
*out* clj-out
*err* clj-err]
(try
(nail ctx)
(catch Throwable e
(.printStackTrace e))))]
(.flush clj-out)
(.flush clj-err)
(set-input-stream System/in sys-in)
(set-output-stream System/out sys-out)
(set-output-stream System/err sys-err)
(let [output (.getBytes
(print-str
(util/clj->vim
{:value result
:stdout (.toString out encoding)
:stderr (.toString err encoding)}))
encoding)]
(.write (.out ctx) output 0 (alength output)))
(.flush (.out ctx))))
(defmacro defnail
"Define a new Nail of the given name. The arguments is a command line
arguments specification vector suitable for with-command-line. The body
will be installed as the body of the nail with the command-line arguments
available according to the specification and the nailgun context as
'nailContext'."
[nail usage arguments & body]
`(defn ~nail
[ctx#]
(nail-driver ctx#
(fn [~(with-meta 'nailContext {:tag `NGContext})]
(util/with-command-line (next (.getArgs ~'nailContext))
~usage
~arguments
~@body)))))
(defnail DocLookup
"Usage: ng vimclojure.nails.DocString [options] symbol ..."
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)]
(backend/doc-lookup nspace (read))))
(defnail FindDoc
"Usage: ng vimclojure.nails.FindDoc"
[]
(backend/find-documentation (.readLine *in*)))
(defnail JavadocPath
"Usage: ng vimclojure.nails.JavadocPath [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
backend/javadoc-path-for-class)))
(defnail SourceLookup
"Usage: ng vimclojure.nails.SourceLookup [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
backend/get-source
println)))
(defnail MetaLookup
"Usage: ng vimclojure.nails.MetaLookup [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
meta
util/pretty-print)))
(defnail SourceLocation
"Usage: ng vimclojure.nails.SourceLocation [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)
our-ns-resolve #(ns-resolve nspace %)]
(-> (read)
our-ns-resolve
backend/source-position)))
(defnail DynamicHighlighting
"Usage: ng vimclojure.nails.DynamicHighlighting"
[]
(let [nspace (read)
c-c (the-ns 'clojure.core)
the-space (util/resolve-and-load-namespace nspace)
refers (remove #(= c-c (-> % second meta :ns)) (ns-refers the-space))
aliases (mapcat (fn [[the-alias the-alias-space]]
(map #(vector (symbol (name the-alias)
(name (first %)))
(second %))
(ns-publics the-alias-space)))
(ns-aliases the-space))
namespaces (mapcat (fn [the-namespace]
(map #(vector (symbol
(name (ns-name the-namespace))
(name (first %)))
(second %))
(ns-publics the-namespace)))
(remove #(= c-c %) (all-ns)))
vars (set (concat refers aliases namespaces))
macros (set (filter #(-> % second meta :macro) vars))
vars (clojure.set/difference vars macros)
fns (set (filter #(let [v (util/safe-var-get (second %))]
(or (fn? v)
(instance? clojure.lang.MultiFn v)))
vars))
vars (clojure.set/difference vars fns)]
(hash-map "Func" (map first fns)
"Macro" (map first macros)
"Variable" (map first vars))))
(defnail NamespaceOfFile
"Usage: ng vimclojure.nails.NamespaceOfFile"
[]
(let [of-interest '#{in-ns ns clojure.core/in-ns clojure.core/ns}
in-seq (util/stream->seq *in*)
candidate (first
(drop-while #(or (not (instance? clojure.lang.ISeq %))
(not (contains? of-interest (first %))))
in-seq))]
(cond
(not (instance? clojure.lang.ISeq candidate)) "user"
('#{ns clojure.core/ns} (first candidate)) (second candidate)
('#{in-ns clojure.core/in-ns} (first candidate)) (-> candidate
second
second))))
(defnail NamespaceInfo
"Usage: ng vimclojure.nails.NamespaceInfo"
[]
(println (util/clj->vim (map #(-> % symbol find-ns backend/ns-info)
(line-seq (BufferedReader. *in*))))))
(defnail MacroExpand
"Usage: ng vimclojure.nails.MacroExpand [options]"
[[nspace n "Lookup the symbols in the given namespace." "user"]
[one? o "Expand only the first macro."]]
(let [nspace (util/resolve-and-load-namespace nspace)
expand (if one
#(macroexpand-1 %)
#(macroexpand %))]
(binding [*ns* nspace]
(-> (read)
expand
util/pretty-print-code))))
(defnail Repl
"Usage: ng vimclojure.nails.Repl [options]"
[[start? s "Start a new Repl."]
[stop? S "Stop the Repl of the given id."]
[run? r "Run the input in the Repl context of the given id."]
[id i "The id of the repl to act on." "-1"]
[nspace n "Change to namespace before executing the input." ""]
[file f "The filename to be set." "REPL"]
[line l "The initial line to be set." "0"]
[ignore? I "Ignore the command with respect to *1, *2, *3"]]
(let [id (Integer/parseInt id)
line (Integer/parseInt line)
nspace (when (not= nspace "")
(util/resolve-and-load-namespace nspace))]
(cond
start {:id (repl/start nspace)}
stop (repl/stop id)
run (repl/run id nspace file line ignore))))
(defnail ReplNamespace
"Usage: ng vimclojure.nails.Repl [options]"
[[id i "The id of the repl to act on."]]
(let [id (Integer/parseInt id)]
(get (get @repl/*repls* id {:ns "user"}) :ns)))
(defnail CheckSyntax
"Usage: ng vimclojure.nails.CheckSyntax"
[[nspace n "Change to namespace before executing the input." "user"]]
(let [nspace (util/resolve-and-load-namespace nspace)]
(binding [*ns* nspace]
(try
(let [eof (Object.)]
(loop [x nil]
(if (identical? x eof)
true
(recur (read *in* false eof)))))
(catch clojure.lang.LispReader$ReaderException exc
(let [e (.getCause exc)]
(if (.startsWith (.getMessage e) "EOF while reading")
false
(throw exc))))))))
(defnail Complete
"Usage: ng vimclojure.nails.Complete"
[[nspace n "Start completion in this namespace." "user"]
[prefix p "Prefix used for the match, ie. the part before /." ""]
[base b "Base pattern to be matched."]]
(let [nspace (util/resolve-and-load-namespace nspace)
prefix (symbol prefix)
to-complete (util/decide-completion-in nspace prefix base)
completions (mapcat #(backend/complete % nspace prefix base)
to-complete)]
(map #(apply util/make-completion-item %) completions)))
(defnail RunTests
"Usage: ng vimclojure.nails.RunTests"
[[nspace n "Run tests in the given namespace." "user"]
[all? a "Reload all or only the namespace under test"]]
(when (not= "user" nspace)
(if all
(require :reload-all (symbol nspace))
(require :reload (symbol nspace))))
(binding [clojure.test/*test-out* *out*]
(clojure.test/run-tests (symbol nspace)))
nil)
|
[
{
"context": "ient/wrap-basic-auth\n {:basic-auth [\"Aladdin\" \"open sesame\"]}\n {:headers {\"Author",
"end": 5895,
"score": 0.817812442779541,
"start": 5888,
"tag": "PASSWORD",
"value": "Aladdin"
}
] | test/clj_http/client_test.clj | revelytix/clj-http | 1 | (ns clj-http.client-test
(:use [clojure.test]
[clj-http.core-test :only [run-server]])
(:require [clj-http.client :as client]
[clj-http.util :as util])
(:import (java.util Arrays)))
(def base-req
{:scheme "http"
:server-name "localhost"
:server-port 18080})
(deftest ^{:integration true} roundtrip
(run-server)
(let [resp (client/request (merge base-req {:uri "/get" :method :get}))]
(is (= 200 (:status resp)))
(is (= "close" (get-in resp [:headers "connection"])))
(is (= "get" (:body resp)))))
(defn is-passed [middleware req]
(let [client (middleware identity)]
(is (= req (client req)))))
(defn is-applied [middleware req-in req-out]
(let [client (middleware identity)]
(is (= req-out (client req-in)))))
(deftest redirect-on-get
(let [client (fn [req]
(if (= "foo.com" (:server-name req))
{:status 302
:headers {"location" "http://bar.com/bat"}}
{:status 200
:req req}))
r-client (-> client client/wrap-url client/wrap-redirects)
resp (r-client {:server-name "foo.com" :request-method :get})]
(is (= 200 (:status resp)))
(is (= :get (:request-method (:req resp))))
(is (= "http" (:scheme (:req resp))))
(is (= "/bat" (:uri (:req resp))))))
(deftest redirect-to-get-on-head
(let [client (fn [req]
(if (= "foo.com" (:server-name req))
{:status 303
:headers {"location" "http://bar.com/bat"}}
{:status 200
:req req}))
r-client (-> client client/wrap-url client/wrap-redirects)
resp (r-client {:server-name "foo.com" :request-method :head})]
(is (= 200 (:status resp)))
(is (= :get (:request-method (:req resp))))
(is (= "http" (:scheme (:req resp))))
(is (= "/bat" (:uri (:req resp))))))
(deftest pass-on-non-redirect
(let [client (fn [req] {:status 200 :body (:body req)})
r-client (client/wrap-redirects client)
resp (r-client {:body "ok"})]
(is (= 200 (:status resp)))
(is (= "ok" (:body resp)))))
(deftest throw-on-exceptional
(let [client (fn [req] {:status 500})
e-client (client/wrap-exceptions client)]
(is (thrown-with-msg? Exception #"500"
(e-client {})))))
(deftest pass-on-non-exceptional
(let [client (fn [req] {:status 200})
e-client (client/wrap-exceptions client)
resp (e-client {})]
(is (= 200 (:status resp)))))
(deftest pass-on-exceptional-when-surpressed
(let [client (fn [req] {:status 500})
e-client (client/wrap-exceptions client)
resp (e-client {:throw-exceptions false})]
(is (= 500 (:status resp)))))
(deftest apply-on-compressed
(let [client (fn [req]
(is (= "gzip, deflate" (get-in req [:headers "Accept-Encoding"])))
{:body (util/gzip (util/utf8-bytes "foofoofoo"))
:headers {"Content-Encoding" "gzip"}})
c-client (client/wrap-decompression client)
resp (c-client {})]
(is (= "foofoofoo" (util/utf8-string (:body resp))))))
(deftest apply-on-deflated
(let [client (fn [req]
(is (= "gzip, deflate" (get-in req [:headers "Accept-Encoding"])))
{:body (util/deflate (util/utf8-bytes "barbarbar"))
:headers {"Content-Encoding" "deflate"}})
c-client (client/wrap-decompression client)
resp (c-client {})]
(is (= "barbarbar" (util/utf8-string (:body resp))))))
(deftest pass-on-non-compressed
(let [c-client (client/wrap-decompression (fn [req] {:body "foo"}))
resp (c-client {:uri "/foo"})]
(is (= "foo" (:body resp)))))
(deftest apply-on-accept
(is-applied client/wrap-accept
{:accept :json}
{:headers {"Accept" "application/json"}}))
(deftest pass-on-no-accept
(is-passed client/wrap-accept
{:uri "/foo"}))
(deftest apply-on-accept-encoding
(is-applied client/wrap-accept-encoding
{:accept-encoding [:identity :gzip]}
{:headers {"Accept-Encoding" "identity, gzip"}}))
(deftest pass-on-no-accept-encoding
(is-passed client/wrap-accept-encoding
{:uri "/foo"}))
(deftest apply-on-output-coercion
(let [client (fn [req] {:body (util/utf8-bytes "foo")})
o-client (client/wrap-output-coercion client)
resp (o-client {:uri "/foo"})]
(is (= "foo" (:body resp)))))
(deftest pass-on-no-output-coercion
(let [client (fn [req] {:body nil})
o-client (client/wrap-output-coercion client)
resp (o-client {:uri "/foo"})]
(is (nil? (:body resp))))
(let [client (fn [req] {:body :thebytes})
o-client (client/wrap-output-coercion client)
resp (o-client {:uri "/foo" :as :byte-array})]
(is (= :thebytes (:body resp)))))
(deftest apply-on-input-coercion
(let [i-client (client/wrap-input-coercion identity)
resp (i-client {:body "foo"})]
(is (= "UTF-8" (:character-encoding resp)))
(is (Arrays/equals (util/utf8-bytes "foo") (:body resp)))))
(deftest pass-on-no-input-coercion
(is-passed client/wrap-input-coercion
{:body (util/utf8-bytes "foo")}))
(deftest apply-on-content-type
(is-applied client/wrap-content-type
{:content-type :json}
{:content-type "application/json"}))
(deftest pass-on-no-content-type
(is-passed client/wrap-content-type
{:uri "/foo"}))
(deftest apply-on-query-params
(is-applied client/wrap-query-params
{:query-params {"foo" "bar" "dir" "<<"}}
{:query-string "foo=bar&dir=%3C%3C"}))
(deftest pass-on-no-query-params
(is-passed client/wrap-query-params
{:uri "/foo"}))
(deftest apply-on-basic-auth
(is-applied client/wrap-basic-auth
{:basic-auth ["Aladdin" "open sesame"]}
{:headers {"Authorization"
"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="}}))
(deftest pass-on-no-basic-auth
(is-passed client/wrap-basic-auth
{:uri "/foo"}))
(deftest apply-on-method
(let [m-client (client/wrap-method identity)
echo (m-client {:key :val :method :post})]
(is (= :val (:key echo)))
(is (= :post (:request-method echo)))
(is (not (:method echo)))))
(deftest pass-on-no-method
(let [m-client (client/wrap-method identity)
echo (m-client {:key :val})]
(is (= :val (:key echo)))
(is (not (:request-method echo)))))
(deftest apply-on-url
(let [u-client (client/wrap-url identity)
resp (u-client {:url "http://google.com:8080/foo?bar=bat"})]
(is (= "http" (:scheme resp)))
(is (= "google.com" (:server-name resp)))
(is (= 8080 (:server-port resp)))
(is (= "/foo" (:uri resp)))
(is (= "bar=bat" (:query-string resp)))))
(deftest pass-on-no-url
(let [u-client (client/wrap-url identity)
resp (u-client {:uri "/foo"})]
(is (= "/foo" (:uri resp)))))
(deftest provide-default-port
(is (= 80 (-> "http://example.com/" client/parse-url :server-port)))
(is (= 8080 (-> "http://example.com:8080/" client/parse-url :server-port)))
(is (= 443 (-> "https://example.com/" client/parse-url :server-port)))
(is (= 8443 (-> "https://example.com:8443/" client/parse-url :server-port))))
(deftest apply-on-form-params
(testing "With form params"
(let [param-client (client/wrap-form-params identity)
resp (param-client {:form-params {:param1 "value1"
:param2 "value2"}})]
(is (= "param1=value1¶m2=value2" (:body resp)))
(is (= "application/x-www-form-urlencoded" (:content-type resp)))
(is (not (contains? resp :form-params)))))
(testing "with no form params"
(let [param-client (client/wrap-form-params identity)
resp (param-client {:body "untouched"})]
(is (= "untouched" (:body resp)))
(is (not (contains? resp :content-type))))))
| 5029 | (ns clj-http.client-test
(:use [clojure.test]
[clj-http.core-test :only [run-server]])
(:require [clj-http.client :as client]
[clj-http.util :as util])
(:import (java.util Arrays)))
(def base-req
{:scheme "http"
:server-name "localhost"
:server-port 18080})
(deftest ^{:integration true} roundtrip
(run-server)
(let [resp (client/request (merge base-req {:uri "/get" :method :get}))]
(is (= 200 (:status resp)))
(is (= "close" (get-in resp [:headers "connection"])))
(is (= "get" (:body resp)))))
(defn is-passed [middleware req]
(let [client (middleware identity)]
(is (= req (client req)))))
(defn is-applied [middleware req-in req-out]
(let [client (middleware identity)]
(is (= req-out (client req-in)))))
(deftest redirect-on-get
(let [client (fn [req]
(if (= "foo.com" (:server-name req))
{:status 302
:headers {"location" "http://bar.com/bat"}}
{:status 200
:req req}))
r-client (-> client client/wrap-url client/wrap-redirects)
resp (r-client {:server-name "foo.com" :request-method :get})]
(is (= 200 (:status resp)))
(is (= :get (:request-method (:req resp))))
(is (= "http" (:scheme (:req resp))))
(is (= "/bat" (:uri (:req resp))))))
(deftest redirect-to-get-on-head
(let [client (fn [req]
(if (= "foo.com" (:server-name req))
{:status 303
:headers {"location" "http://bar.com/bat"}}
{:status 200
:req req}))
r-client (-> client client/wrap-url client/wrap-redirects)
resp (r-client {:server-name "foo.com" :request-method :head})]
(is (= 200 (:status resp)))
(is (= :get (:request-method (:req resp))))
(is (= "http" (:scheme (:req resp))))
(is (= "/bat" (:uri (:req resp))))))
(deftest pass-on-non-redirect
(let [client (fn [req] {:status 200 :body (:body req)})
r-client (client/wrap-redirects client)
resp (r-client {:body "ok"})]
(is (= 200 (:status resp)))
(is (= "ok" (:body resp)))))
(deftest throw-on-exceptional
(let [client (fn [req] {:status 500})
e-client (client/wrap-exceptions client)]
(is (thrown-with-msg? Exception #"500"
(e-client {})))))
(deftest pass-on-non-exceptional
(let [client (fn [req] {:status 200})
e-client (client/wrap-exceptions client)
resp (e-client {})]
(is (= 200 (:status resp)))))
(deftest pass-on-exceptional-when-surpressed
(let [client (fn [req] {:status 500})
e-client (client/wrap-exceptions client)
resp (e-client {:throw-exceptions false})]
(is (= 500 (:status resp)))))
(deftest apply-on-compressed
(let [client (fn [req]
(is (= "gzip, deflate" (get-in req [:headers "Accept-Encoding"])))
{:body (util/gzip (util/utf8-bytes "foofoofoo"))
:headers {"Content-Encoding" "gzip"}})
c-client (client/wrap-decompression client)
resp (c-client {})]
(is (= "foofoofoo" (util/utf8-string (:body resp))))))
(deftest apply-on-deflated
(let [client (fn [req]
(is (= "gzip, deflate" (get-in req [:headers "Accept-Encoding"])))
{:body (util/deflate (util/utf8-bytes "barbarbar"))
:headers {"Content-Encoding" "deflate"}})
c-client (client/wrap-decompression client)
resp (c-client {})]
(is (= "barbarbar" (util/utf8-string (:body resp))))))
(deftest pass-on-non-compressed
(let [c-client (client/wrap-decompression (fn [req] {:body "foo"}))
resp (c-client {:uri "/foo"})]
(is (= "foo" (:body resp)))))
(deftest apply-on-accept
(is-applied client/wrap-accept
{:accept :json}
{:headers {"Accept" "application/json"}}))
(deftest pass-on-no-accept
(is-passed client/wrap-accept
{:uri "/foo"}))
(deftest apply-on-accept-encoding
(is-applied client/wrap-accept-encoding
{:accept-encoding [:identity :gzip]}
{:headers {"Accept-Encoding" "identity, gzip"}}))
(deftest pass-on-no-accept-encoding
(is-passed client/wrap-accept-encoding
{:uri "/foo"}))
(deftest apply-on-output-coercion
(let [client (fn [req] {:body (util/utf8-bytes "foo")})
o-client (client/wrap-output-coercion client)
resp (o-client {:uri "/foo"})]
(is (= "foo" (:body resp)))))
(deftest pass-on-no-output-coercion
(let [client (fn [req] {:body nil})
o-client (client/wrap-output-coercion client)
resp (o-client {:uri "/foo"})]
(is (nil? (:body resp))))
(let [client (fn [req] {:body :thebytes})
o-client (client/wrap-output-coercion client)
resp (o-client {:uri "/foo" :as :byte-array})]
(is (= :thebytes (:body resp)))))
(deftest apply-on-input-coercion
(let [i-client (client/wrap-input-coercion identity)
resp (i-client {:body "foo"})]
(is (= "UTF-8" (:character-encoding resp)))
(is (Arrays/equals (util/utf8-bytes "foo") (:body resp)))))
(deftest pass-on-no-input-coercion
(is-passed client/wrap-input-coercion
{:body (util/utf8-bytes "foo")}))
(deftest apply-on-content-type
(is-applied client/wrap-content-type
{:content-type :json}
{:content-type "application/json"}))
(deftest pass-on-no-content-type
(is-passed client/wrap-content-type
{:uri "/foo"}))
(deftest apply-on-query-params
(is-applied client/wrap-query-params
{:query-params {"foo" "bar" "dir" "<<"}}
{:query-string "foo=bar&dir=%3C%3C"}))
(deftest pass-on-no-query-params
(is-passed client/wrap-query-params
{:uri "/foo"}))
(deftest apply-on-basic-auth
(is-applied client/wrap-basic-auth
{:basic-auth ["<PASSWORD>" "open sesame"]}
{:headers {"Authorization"
"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="}}))
(deftest pass-on-no-basic-auth
(is-passed client/wrap-basic-auth
{:uri "/foo"}))
(deftest apply-on-method
(let [m-client (client/wrap-method identity)
echo (m-client {:key :val :method :post})]
(is (= :val (:key echo)))
(is (= :post (:request-method echo)))
(is (not (:method echo)))))
(deftest pass-on-no-method
(let [m-client (client/wrap-method identity)
echo (m-client {:key :val})]
(is (= :val (:key echo)))
(is (not (:request-method echo)))))
(deftest apply-on-url
(let [u-client (client/wrap-url identity)
resp (u-client {:url "http://google.com:8080/foo?bar=bat"})]
(is (= "http" (:scheme resp)))
(is (= "google.com" (:server-name resp)))
(is (= 8080 (:server-port resp)))
(is (= "/foo" (:uri resp)))
(is (= "bar=bat" (:query-string resp)))))
(deftest pass-on-no-url
(let [u-client (client/wrap-url identity)
resp (u-client {:uri "/foo"})]
(is (= "/foo" (:uri resp)))))
(deftest provide-default-port
(is (= 80 (-> "http://example.com/" client/parse-url :server-port)))
(is (= 8080 (-> "http://example.com:8080/" client/parse-url :server-port)))
(is (= 443 (-> "https://example.com/" client/parse-url :server-port)))
(is (= 8443 (-> "https://example.com:8443/" client/parse-url :server-port))))
(deftest apply-on-form-params
(testing "With form params"
(let [param-client (client/wrap-form-params identity)
resp (param-client {:form-params {:param1 "value1"
:param2 "value2"}})]
(is (= "param1=value1¶m2=value2" (:body resp)))
(is (= "application/x-www-form-urlencoded" (:content-type resp)))
(is (not (contains? resp :form-params)))))
(testing "with no form params"
(let [param-client (client/wrap-form-params identity)
resp (param-client {:body "untouched"})]
(is (= "untouched" (:body resp)))
(is (not (contains? resp :content-type))))))
| true | (ns clj-http.client-test
(:use [clojure.test]
[clj-http.core-test :only [run-server]])
(:require [clj-http.client :as client]
[clj-http.util :as util])
(:import (java.util Arrays)))
(def base-req
{:scheme "http"
:server-name "localhost"
:server-port 18080})
(deftest ^{:integration true} roundtrip
(run-server)
(let [resp (client/request (merge base-req {:uri "/get" :method :get}))]
(is (= 200 (:status resp)))
(is (= "close" (get-in resp [:headers "connection"])))
(is (= "get" (:body resp)))))
(defn is-passed [middleware req]
(let [client (middleware identity)]
(is (= req (client req)))))
(defn is-applied [middleware req-in req-out]
(let [client (middleware identity)]
(is (= req-out (client req-in)))))
(deftest redirect-on-get
(let [client (fn [req]
(if (= "foo.com" (:server-name req))
{:status 302
:headers {"location" "http://bar.com/bat"}}
{:status 200
:req req}))
r-client (-> client client/wrap-url client/wrap-redirects)
resp (r-client {:server-name "foo.com" :request-method :get})]
(is (= 200 (:status resp)))
(is (= :get (:request-method (:req resp))))
(is (= "http" (:scheme (:req resp))))
(is (= "/bat" (:uri (:req resp))))))
(deftest redirect-to-get-on-head
(let [client (fn [req]
(if (= "foo.com" (:server-name req))
{:status 303
:headers {"location" "http://bar.com/bat"}}
{:status 200
:req req}))
r-client (-> client client/wrap-url client/wrap-redirects)
resp (r-client {:server-name "foo.com" :request-method :head})]
(is (= 200 (:status resp)))
(is (= :get (:request-method (:req resp))))
(is (= "http" (:scheme (:req resp))))
(is (= "/bat" (:uri (:req resp))))))
(deftest pass-on-non-redirect
(let [client (fn [req] {:status 200 :body (:body req)})
r-client (client/wrap-redirects client)
resp (r-client {:body "ok"})]
(is (= 200 (:status resp)))
(is (= "ok" (:body resp)))))
(deftest throw-on-exceptional
(let [client (fn [req] {:status 500})
e-client (client/wrap-exceptions client)]
(is (thrown-with-msg? Exception #"500"
(e-client {})))))
(deftest pass-on-non-exceptional
(let [client (fn [req] {:status 200})
e-client (client/wrap-exceptions client)
resp (e-client {})]
(is (= 200 (:status resp)))))
(deftest pass-on-exceptional-when-surpressed
(let [client (fn [req] {:status 500})
e-client (client/wrap-exceptions client)
resp (e-client {:throw-exceptions false})]
(is (= 500 (:status resp)))))
(deftest apply-on-compressed
(let [client (fn [req]
(is (= "gzip, deflate" (get-in req [:headers "Accept-Encoding"])))
{:body (util/gzip (util/utf8-bytes "foofoofoo"))
:headers {"Content-Encoding" "gzip"}})
c-client (client/wrap-decompression client)
resp (c-client {})]
(is (= "foofoofoo" (util/utf8-string (:body resp))))))
(deftest apply-on-deflated
(let [client (fn [req]
(is (= "gzip, deflate" (get-in req [:headers "Accept-Encoding"])))
{:body (util/deflate (util/utf8-bytes "barbarbar"))
:headers {"Content-Encoding" "deflate"}})
c-client (client/wrap-decompression client)
resp (c-client {})]
(is (= "barbarbar" (util/utf8-string (:body resp))))))
(deftest pass-on-non-compressed
(let [c-client (client/wrap-decompression (fn [req] {:body "foo"}))
resp (c-client {:uri "/foo"})]
(is (= "foo" (:body resp)))))
(deftest apply-on-accept
(is-applied client/wrap-accept
{:accept :json}
{:headers {"Accept" "application/json"}}))
(deftest pass-on-no-accept
(is-passed client/wrap-accept
{:uri "/foo"}))
(deftest apply-on-accept-encoding
(is-applied client/wrap-accept-encoding
{:accept-encoding [:identity :gzip]}
{:headers {"Accept-Encoding" "identity, gzip"}}))
(deftest pass-on-no-accept-encoding
(is-passed client/wrap-accept-encoding
{:uri "/foo"}))
(deftest apply-on-output-coercion
(let [client (fn [req] {:body (util/utf8-bytes "foo")})
o-client (client/wrap-output-coercion client)
resp (o-client {:uri "/foo"})]
(is (= "foo" (:body resp)))))
(deftest pass-on-no-output-coercion
(let [client (fn [req] {:body nil})
o-client (client/wrap-output-coercion client)
resp (o-client {:uri "/foo"})]
(is (nil? (:body resp))))
(let [client (fn [req] {:body :thebytes})
o-client (client/wrap-output-coercion client)
resp (o-client {:uri "/foo" :as :byte-array})]
(is (= :thebytes (:body resp)))))
(deftest apply-on-input-coercion
(let [i-client (client/wrap-input-coercion identity)
resp (i-client {:body "foo"})]
(is (= "UTF-8" (:character-encoding resp)))
(is (Arrays/equals (util/utf8-bytes "foo") (:body resp)))))
(deftest pass-on-no-input-coercion
(is-passed client/wrap-input-coercion
{:body (util/utf8-bytes "foo")}))
(deftest apply-on-content-type
(is-applied client/wrap-content-type
{:content-type :json}
{:content-type "application/json"}))
(deftest pass-on-no-content-type
(is-passed client/wrap-content-type
{:uri "/foo"}))
(deftest apply-on-query-params
(is-applied client/wrap-query-params
{:query-params {"foo" "bar" "dir" "<<"}}
{:query-string "foo=bar&dir=%3C%3C"}))
(deftest pass-on-no-query-params
(is-passed client/wrap-query-params
{:uri "/foo"}))
(deftest apply-on-basic-auth
(is-applied client/wrap-basic-auth
{:basic-auth ["PI:PASSWORD:<PASSWORD>END_PI" "open sesame"]}
{:headers {"Authorization"
"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="}}))
(deftest pass-on-no-basic-auth
(is-passed client/wrap-basic-auth
{:uri "/foo"}))
(deftest apply-on-method
(let [m-client (client/wrap-method identity)
echo (m-client {:key :val :method :post})]
(is (= :val (:key echo)))
(is (= :post (:request-method echo)))
(is (not (:method echo)))))
(deftest pass-on-no-method
(let [m-client (client/wrap-method identity)
echo (m-client {:key :val})]
(is (= :val (:key echo)))
(is (not (:request-method echo)))))
(deftest apply-on-url
(let [u-client (client/wrap-url identity)
resp (u-client {:url "http://google.com:8080/foo?bar=bat"})]
(is (= "http" (:scheme resp)))
(is (= "google.com" (:server-name resp)))
(is (= 8080 (:server-port resp)))
(is (= "/foo" (:uri resp)))
(is (= "bar=bat" (:query-string resp)))))
(deftest pass-on-no-url
(let [u-client (client/wrap-url identity)
resp (u-client {:uri "/foo"})]
(is (= "/foo" (:uri resp)))))
(deftest provide-default-port
(is (= 80 (-> "http://example.com/" client/parse-url :server-port)))
(is (= 8080 (-> "http://example.com:8080/" client/parse-url :server-port)))
(is (= 443 (-> "https://example.com/" client/parse-url :server-port)))
(is (= 8443 (-> "https://example.com:8443/" client/parse-url :server-port))))
(deftest apply-on-form-params
(testing "With form params"
(let [param-client (client/wrap-form-params identity)
resp (param-client {:form-params {:param1 "value1"
:param2 "value2"}})]
(is (= "param1=value1¶m2=value2" (:body resp)))
(is (= "application/x-www-form-urlencoded" (:content-type resp)))
(is (not (contains? resp :form-params)))))
(testing "with no form params"
(let [param-client (client/wrap-form-params identity)
resp (param-client {:body "untouched"})]
(is (= "untouched" (:body resp)))
(is (not (contains? resp :content-type))))))
|
[
{
"context": "rver-port 9443\n :admin-user-id \"garygeeke\"}\n\n ::sut-server {:admin-platform ",
"end": 564,
"score": 0.9987550973892212,
"start": 555,
"tag": "USERNAME",
"value": "garygeeke"
},
{
"context": "\n :server-password \"SUTpassw0rd\"\n :server-name ",
"end": 821,
"score": 0.9993875622749329,
"start": 810,
"tag": "PASSWORD",
"value": "SUTpassw0rd"
},
{
"context": "1npa\"\n :server-password \"CTS1passw0rd\"\n :server-name \"CTS_",
"end": 1748,
"score": 0.999421238899231,
"start": 1736,
"tag": "PASSWORD",
"value": "CTS1passw0rd"
},
{
"context": " (http/post url\n {:query-params {\"password\" password}\n :insecure? true})))\n\n(defn configure-m",
"end": 3764,
"score": 0.9967337846755981,
"start": 3756,
"tag": "PASSWORD",
"value": "password"
}
] | dev/cts.clj | keytiong/egeria-crux-omrs | 1 | (ns cts
(:require [integrant.repl :refer [clear go halt prep init reset reset-all]]
[integrant.core :as ig]
[clj-http.client :as http]
[clojure.java.io :as io]
[clojure.data.json :as json])
(:import [org.testcontainers.containers KafkaContainer]
[org.testcontainers.utility DockerImageName]))
(def config
{::event-bus {}
::platform {:version "3.3"
:egeria-home "/opt/egeria/egeria-omag"
:server-port 9443
:admin-user-id "garygeeke"}
::sut-server {:admin-platform (ig/ref ::platform)
:platform (ig/ref ::platform)
:server-user-id "SUTnpa"
:server-password "SUTpassw0rd"
:server-name "SUT_Server"
:server-type "Metadata Repository Server"
:event-bus (ig/ref ::event-bus)
:cohort "devCohort"
:metadata-collection-name "SUT_MDR"
:metadata-repository-type "repository-proxy"
:metadata-repository-connector {:connector-provider "io.kosong.egeria.omrs.xtdb.XtdbOMRSRepositoryConnectorProvider"
:additional-properties {}}
}
::cts-server {:admin-platform (ig/ref ::platform)
:platform (ig/ref ::platform)
:sut-server (ig/ref ::sut-server)
:server-user-id "CTS1npa"
:server-password "CTS1passw0rd"
:server-name "CTS_Server"
:server-type "Conformance Suite Server"
:event-bus (ig/ref ::event-bus)
:cohort "devCohort"
:metadata-repository-type "in-memory-repository"}})
(integrant.repl/set-prep! (constantly config))
(defn system []
integrant.repl.state/system)
(defn admin-command-url [{:keys [admin-user-id
platform-url]}]
(str platform-url "/open-metadata/admin-services/users/" admin-user-id "/servers/"))
(defn origin [platform]
(http/get (str (:platform-url platform) "/open-metadata/platform-services/users/garygeeke/server-platform/origin/")
{:insecure? true}))
(defn configure-platform-url
[admin-platform server-name target-platform]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-url-root")
target-platform-url (:platform-url target-platform)]
(http/post url
{:query-params {"url" target-platform-url}
:insecure? true})))
(defn configure-server-type
[admin-platform server-name server-type]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-type")]
(http/post url
{:query-params {"typeName" server-type}
:insecure? true})))
(defn configure-user-id
[admin-platform server-name user-id]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-user-id")]
(http/post url
{:query-params {"id" user-id}
:insecure? true})))
(defn configure-password
[admin-platform server-name password]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-user-password")]
(http/post url
{:query-params {"password" password}
:insecure? true})))
(defn configure-metadata-repository
[admin-platform server-name repository-type]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/local-repository/mode/" repository-type)]
(http/post url
{:insecure? true})))
(defn configure-plugin-metadata-repository
[admin-platform server-name metadata-repository-connector]
(let [admin-command-url (admin-command-url admin-platform)
connector-provider (:connector-provider metadata-repository-connector)
additional-properties (:additional-properties metadata-repository-connector)
url (str admin-command-url server-name "/local-repository/mode/plugin-repository/details")
query-params {:connectorProvider connector-provider}
additional-properties-body (json/json-str additional-properties)]
(http/post url
{:insecure? true
:content-type :json
:query-params query-params
:body additional-properties-body})))
(defn configure-descriptive-name
[admin-platform server-name collection-name]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/local-repository/metadata-collection-name/" collection-name)]
(http/post url
{:insecure? true})))
(defn configure-event-bus
[admin-platform server-name event-bus-root-url]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/event-bus")
event-bus-body (json/json-str
{"producer" {"bootstrap.servers" event-bus-root-url}
"consumer" {"bootstrap.servers" event-bus-root-url}})]
(http/post url
{:insecure? true
:content-type :json
:body event-bus-body})))
(defn configure-cohort-membership
[admin-platform server-name cohort-name]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/cohorts/" cohort-name)]
(http/post url
{:insecure? true})))
(defn configure-repository-workbench
[admin-platform server-name sut-server-name]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/conformance-suite-workbenches/repository-workbench/repositories")
workbench-config-body (json/json-str
{"class" "RepositoryConformanceWorkbenchConfig"
"tutRepositoryServerName" sut-server-name
"maxSearchResults" 10})]
(http/post url
{:insecure? true
:content-type :json
:body workbench-config-body})))
(defn deploy-server
[admin-platform server-name target-platform]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/configuration/deploy")
target-platform-url (:platform-url target-platform)
request-body (json/json-str
{"class" "URLRequestBody"
"urlRoot" target-platform-url})]
(http/post url
{:insecure? true
:content-type :json
:body request-body})))
(defn start-server
[platform server-name]
(let [platform-url (:platform-url platform)
admin-user-id (:admin-user-id platform)
url (str platform-url "/open-metadata/admin-services/users/" admin-user-id "/servers/" server-name "/instance")]
(http/post url
{:insecure? true})))
(defn stop-server
[platform server-name]
(let [platform-url (:platform-url platform)
admin-user-id (:admin-user-id platform)
url (str platform-url "/open-metadata/admin-services/users/" admin-user-id "/servers/" server-name "/instance")]
(http/delete url
{:insecure? true})))
(defn start-sut-server []
(let [system (system)
platform (::platform system)
server-name (get-in system [::sut-server :server-name])]
(start-server platform server-name)))
(defn start-cts-server []
(let [system (system)
platform (::platform system)
server-name (get-in system [::cts-server :server-name])]
(start-server platform server-name)))
(defn start-kafka-container []
(let [kafka (doto (KafkaContainer. (DockerImageName/parse "confluentinc/cp-kafka:5.4.3"))
(.withExposedPorts (into-array Integer [(int 9093)]))
(.start))
root-url (str "localhost:" (.getMappedPort kafka 9093))]
{:kafka-container kafka
:root-url root-url}))
(defn start-omag-platform [{:keys [egeria-home version server-port admin-user-id]}]
(let [server-jar-path (str egeria-home "/server/server-chassis-spring-" version ".jar")
jvm-opts (str "-Dserver.port=" server-port)
process-builder (doto (ProcessBuilder. ["/usr/bin/java" jvm-opts "-jar" server-jar-path])
(.directory (io/file egeria-home)))
platform-process (.start process-builder)
platform-url (str "https://localhost:" server-port)]
(Thread/sleep 15000)
{:platform-process platform-process
:platform-url platform-url
:admin-user-id admin-user-id}))
(defmethod ig/init-key ::event-bus [_ _]
(start-kafka-container))
(defmethod ig/halt-key! ::event-bus [_ {:keys [^KafkaContainer kafka-container]}]
(when kafka-container
(.stop kafka-container)))
(defmethod ig/init-key ::platform [_ config]
(start-omag-platform config))
(defmethod ig/halt-key! ::platform [_ {:keys [^Process platform-process]}]
(when platform-process
(.destroy platform-process)))
(defmethod ig/init-key ::sut-server
[_ {:keys [admin-platform server-name event-bus server-user-id server-password server-type
platform metadata-repository-connector metadata-collection-name
cohort metadata-repository-connector-provider additional-properties]
:as server-config}]
(let [event-bus-root-url (:root-url event-bus)]
(configure-platform-url admin-platform server-name platform)
(configure-server-type admin-platform server-name server-type)
(configure-user-id admin-platform server-name server-user-id)
(configure-password admin-platform server-name server-password)
(configure-plugin-metadata-repository admin-platform server-name metadata-repository-connector)
;;(configure-metadata-repository admin-platform server-name metadata-repository-type)
(configure-descriptive-name admin-platform server-name metadata-collection-name)
(configure-event-bus admin-platform server-name event-bus-root-url)
(configure-cohort-membership admin-platform server-name cohort)
(deploy-server admin-platform server-name platform)
#_(start-server platform server-name)
server-config))
(defmethod ig/halt-key! ::sut-server [_ {:keys [platform server-name]}]
(stop-server platform server-name))
(defmethod ig/init-key ::cts-server
[_ {:keys [admin-platform server-name event-bus server-user-id server-password server-type
platform metadata-repository-type sut-server
cohort]
:as server-config}]
(let [event-bus-root-url (:root-url event-bus)
sut-server-name (:server-name sut-server)]
(configure-platform-url admin-platform server-name platform)
(configure-server-type admin-platform server-name server-type)
(configure-user-id admin-platform server-name server-user-id)
(configure-password admin-platform server-name server-password)
(configure-metadata-repository admin-platform server-name metadata-repository-type)
(configure-event-bus admin-platform server-name event-bus-root-url)
(configure-cohort-membership admin-platform server-name cohort)
(configure-repository-workbench admin-platform server-name sut-server-name)
(deploy-server admin-platform server-name platform)
#_(start-server platform server-name)
server-config))
(defmethod ig/halt-key! ::cts-server [_ {:keys [platform server-name]}]
(stop-server platform server-name))
;; https://localhost:9443/open-metadata/admin-services/users/garygeeke/servers/SUT_Server/configuration
;; https://localhost:9443/open-metadata/admin-services/users/garygeeke/servers/SUT_Server/configuration
;; https://localhost:9443/servers/CTS_Server/open-metadata/conformance-suite/users/garygeeke/report/summary
;; https://localhost:9443/servers/CTS_Server/open-metadata/conformance-suite/users/garygeeke/report/test-cases/failed | 111814 | (ns cts
(:require [integrant.repl :refer [clear go halt prep init reset reset-all]]
[integrant.core :as ig]
[clj-http.client :as http]
[clojure.java.io :as io]
[clojure.data.json :as json])
(:import [org.testcontainers.containers KafkaContainer]
[org.testcontainers.utility DockerImageName]))
(def config
{::event-bus {}
::platform {:version "3.3"
:egeria-home "/opt/egeria/egeria-omag"
:server-port 9443
:admin-user-id "garygeeke"}
::sut-server {:admin-platform (ig/ref ::platform)
:platform (ig/ref ::platform)
:server-user-id "SUTnpa"
:server-password "<PASSWORD>"
:server-name "SUT_Server"
:server-type "Metadata Repository Server"
:event-bus (ig/ref ::event-bus)
:cohort "devCohort"
:metadata-collection-name "SUT_MDR"
:metadata-repository-type "repository-proxy"
:metadata-repository-connector {:connector-provider "io.kosong.egeria.omrs.xtdb.XtdbOMRSRepositoryConnectorProvider"
:additional-properties {}}
}
::cts-server {:admin-platform (ig/ref ::platform)
:platform (ig/ref ::platform)
:sut-server (ig/ref ::sut-server)
:server-user-id "CTS1npa"
:server-password "<PASSWORD>"
:server-name "CTS_Server"
:server-type "Conformance Suite Server"
:event-bus (ig/ref ::event-bus)
:cohort "devCohort"
:metadata-repository-type "in-memory-repository"}})
(integrant.repl/set-prep! (constantly config))
(defn system []
integrant.repl.state/system)
(defn admin-command-url [{:keys [admin-user-id
platform-url]}]
(str platform-url "/open-metadata/admin-services/users/" admin-user-id "/servers/"))
(defn origin [platform]
(http/get (str (:platform-url platform) "/open-metadata/platform-services/users/garygeeke/server-platform/origin/")
{:insecure? true}))
(defn configure-platform-url
[admin-platform server-name target-platform]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-url-root")
target-platform-url (:platform-url target-platform)]
(http/post url
{:query-params {"url" target-platform-url}
:insecure? true})))
(defn configure-server-type
[admin-platform server-name server-type]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-type")]
(http/post url
{:query-params {"typeName" server-type}
:insecure? true})))
(defn configure-user-id
[admin-platform server-name user-id]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-user-id")]
(http/post url
{:query-params {"id" user-id}
:insecure? true})))
(defn configure-password
[admin-platform server-name password]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-user-password")]
(http/post url
{:query-params {"password" <PASSWORD>}
:insecure? true})))
(defn configure-metadata-repository
[admin-platform server-name repository-type]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/local-repository/mode/" repository-type)]
(http/post url
{:insecure? true})))
(defn configure-plugin-metadata-repository
[admin-platform server-name metadata-repository-connector]
(let [admin-command-url (admin-command-url admin-platform)
connector-provider (:connector-provider metadata-repository-connector)
additional-properties (:additional-properties metadata-repository-connector)
url (str admin-command-url server-name "/local-repository/mode/plugin-repository/details")
query-params {:connectorProvider connector-provider}
additional-properties-body (json/json-str additional-properties)]
(http/post url
{:insecure? true
:content-type :json
:query-params query-params
:body additional-properties-body})))
(defn configure-descriptive-name
[admin-platform server-name collection-name]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/local-repository/metadata-collection-name/" collection-name)]
(http/post url
{:insecure? true})))
(defn configure-event-bus
[admin-platform server-name event-bus-root-url]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/event-bus")
event-bus-body (json/json-str
{"producer" {"bootstrap.servers" event-bus-root-url}
"consumer" {"bootstrap.servers" event-bus-root-url}})]
(http/post url
{:insecure? true
:content-type :json
:body event-bus-body})))
(defn configure-cohort-membership
[admin-platform server-name cohort-name]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/cohorts/" cohort-name)]
(http/post url
{:insecure? true})))
(defn configure-repository-workbench
[admin-platform server-name sut-server-name]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/conformance-suite-workbenches/repository-workbench/repositories")
workbench-config-body (json/json-str
{"class" "RepositoryConformanceWorkbenchConfig"
"tutRepositoryServerName" sut-server-name
"maxSearchResults" 10})]
(http/post url
{:insecure? true
:content-type :json
:body workbench-config-body})))
(defn deploy-server
[admin-platform server-name target-platform]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/configuration/deploy")
target-platform-url (:platform-url target-platform)
request-body (json/json-str
{"class" "URLRequestBody"
"urlRoot" target-platform-url})]
(http/post url
{:insecure? true
:content-type :json
:body request-body})))
(defn start-server
[platform server-name]
(let [platform-url (:platform-url platform)
admin-user-id (:admin-user-id platform)
url (str platform-url "/open-metadata/admin-services/users/" admin-user-id "/servers/" server-name "/instance")]
(http/post url
{:insecure? true})))
(defn stop-server
[platform server-name]
(let [platform-url (:platform-url platform)
admin-user-id (:admin-user-id platform)
url (str platform-url "/open-metadata/admin-services/users/" admin-user-id "/servers/" server-name "/instance")]
(http/delete url
{:insecure? true})))
(defn start-sut-server []
(let [system (system)
platform (::platform system)
server-name (get-in system [::sut-server :server-name])]
(start-server platform server-name)))
(defn start-cts-server []
(let [system (system)
platform (::platform system)
server-name (get-in system [::cts-server :server-name])]
(start-server platform server-name)))
(defn start-kafka-container []
(let [kafka (doto (KafkaContainer. (DockerImageName/parse "confluentinc/cp-kafka:5.4.3"))
(.withExposedPorts (into-array Integer [(int 9093)]))
(.start))
root-url (str "localhost:" (.getMappedPort kafka 9093))]
{:kafka-container kafka
:root-url root-url}))
(defn start-omag-platform [{:keys [egeria-home version server-port admin-user-id]}]
(let [server-jar-path (str egeria-home "/server/server-chassis-spring-" version ".jar")
jvm-opts (str "-Dserver.port=" server-port)
process-builder (doto (ProcessBuilder. ["/usr/bin/java" jvm-opts "-jar" server-jar-path])
(.directory (io/file egeria-home)))
platform-process (.start process-builder)
platform-url (str "https://localhost:" server-port)]
(Thread/sleep 15000)
{:platform-process platform-process
:platform-url platform-url
:admin-user-id admin-user-id}))
(defmethod ig/init-key ::event-bus [_ _]
(start-kafka-container))
(defmethod ig/halt-key! ::event-bus [_ {:keys [^KafkaContainer kafka-container]}]
(when kafka-container
(.stop kafka-container)))
(defmethod ig/init-key ::platform [_ config]
(start-omag-platform config))
(defmethod ig/halt-key! ::platform [_ {:keys [^Process platform-process]}]
(when platform-process
(.destroy platform-process)))
(defmethod ig/init-key ::sut-server
[_ {:keys [admin-platform server-name event-bus server-user-id server-password server-type
platform metadata-repository-connector metadata-collection-name
cohort metadata-repository-connector-provider additional-properties]
:as server-config}]
(let [event-bus-root-url (:root-url event-bus)]
(configure-platform-url admin-platform server-name platform)
(configure-server-type admin-platform server-name server-type)
(configure-user-id admin-platform server-name server-user-id)
(configure-password admin-platform server-name server-password)
(configure-plugin-metadata-repository admin-platform server-name metadata-repository-connector)
;;(configure-metadata-repository admin-platform server-name metadata-repository-type)
(configure-descriptive-name admin-platform server-name metadata-collection-name)
(configure-event-bus admin-platform server-name event-bus-root-url)
(configure-cohort-membership admin-platform server-name cohort)
(deploy-server admin-platform server-name platform)
#_(start-server platform server-name)
server-config))
(defmethod ig/halt-key! ::sut-server [_ {:keys [platform server-name]}]
(stop-server platform server-name))
(defmethod ig/init-key ::cts-server
[_ {:keys [admin-platform server-name event-bus server-user-id server-password server-type
platform metadata-repository-type sut-server
cohort]
:as server-config}]
(let [event-bus-root-url (:root-url event-bus)
sut-server-name (:server-name sut-server)]
(configure-platform-url admin-platform server-name platform)
(configure-server-type admin-platform server-name server-type)
(configure-user-id admin-platform server-name server-user-id)
(configure-password admin-platform server-name server-password)
(configure-metadata-repository admin-platform server-name metadata-repository-type)
(configure-event-bus admin-platform server-name event-bus-root-url)
(configure-cohort-membership admin-platform server-name cohort)
(configure-repository-workbench admin-platform server-name sut-server-name)
(deploy-server admin-platform server-name platform)
#_(start-server platform server-name)
server-config))
(defmethod ig/halt-key! ::cts-server [_ {:keys [platform server-name]}]
(stop-server platform server-name))
;; https://localhost:9443/open-metadata/admin-services/users/garygeeke/servers/SUT_Server/configuration
;; https://localhost:9443/open-metadata/admin-services/users/garygeeke/servers/SUT_Server/configuration
;; https://localhost:9443/servers/CTS_Server/open-metadata/conformance-suite/users/garygeeke/report/summary
;; https://localhost:9443/servers/CTS_Server/open-metadata/conformance-suite/users/garygeeke/report/test-cases/failed | true | (ns cts
(:require [integrant.repl :refer [clear go halt prep init reset reset-all]]
[integrant.core :as ig]
[clj-http.client :as http]
[clojure.java.io :as io]
[clojure.data.json :as json])
(:import [org.testcontainers.containers KafkaContainer]
[org.testcontainers.utility DockerImageName]))
(def config
{::event-bus {}
::platform {:version "3.3"
:egeria-home "/opt/egeria/egeria-omag"
:server-port 9443
:admin-user-id "garygeeke"}
::sut-server {:admin-platform (ig/ref ::platform)
:platform (ig/ref ::platform)
:server-user-id "SUTnpa"
:server-password "PI:PASSWORD:<PASSWORD>END_PI"
:server-name "SUT_Server"
:server-type "Metadata Repository Server"
:event-bus (ig/ref ::event-bus)
:cohort "devCohort"
:metadata-collection-name "SUT_MDR"
:metadata-repository-type "repository-proxy"
:metadata-repository-connector {:connector-provider "io.kosong.egeria.omrs.xtdb.XtdbOMRSRepositoryConnectorProvider"
:additional-properties {}}
}
::cts-server {:admin-platform (ig/ref ::platform)
:platform (ig/ref ::platform)
:sut-server (ig/ref ::sut-server)
:server-user-id "CTS1npa"
:server-password "PI:PASSWORD:<PASSWORD>END_PI"
:server-name "CTS_Server"
:server-type "Conformance Suite Server"
:event-bus (ig/ref ::event-bus)
:cohort "devCohort"
:metadata-repository-type "in-memory-repository"}})
(integrant.repl/set-prep! (constantly config))
(defn system []
integrant.repl.state/system)
(defn admin-command-url [{:keys [admin-user-id
platform-url]}]
(str platform-url "/open-metadata/admin-services/users/" admin-user-id "/servers/"))
(defn origin [platform]
(http/get (str (:platform-url platform) "/open-metadata/platform-services/users/garygeeke/server-platform/origin/")
{:insecure? true}))
(defn configure-platform-url
[admin-platform server-name target-platform]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-url-root")
target-platform-url (:platform-url target-platform)]
(http/post url
{:query-params {"url" target-platform-url}
:insecure? true})))
(defn configure-server-type
[admin-platform server-name server-type]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-type")]
(http/post url
{:query-params {"typeName" server-type}
:insecure? true})))
(defn configure-user-id
[admin-platform server-name user-id]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-user-id")]
(http/post url
{:query-params {"id" user-id}
:insecure? true})))
(defn configure-password
[admin-platform server-name password]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/server-user-password")]
(http/post url
{:query-params {"password" PI:PASSWORD:<PASSWORD>END_PI}
:insecure? true})))
(defn configure-metadata-repository
[admin-platform server-name repository-type]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/local-repository/mode/" repository-type)]
(http/post url
{:insecure? true})))
(defn configure-plugin-metadata-repository
[admin-platform server-name metadata-repository-connector]
(let [admin-command-url (admin-command-url admin-platform)
connector-provider (:connector-provider metadata-repository-connector)
additional-properties (:additional-properties metadata-repository-connector)
url (str admin-command-url server-name "/local-repository/mode/plugin-repository/details")
query-params {:connectorProvider connector-provider}
additional-properties-body (json/json-str additional-properties)]
(http/post url
{:insecure? true
:content-type :json
:query-params query-params
:body additional-properties-body})))
(defn configure-descriptive-name
[admin-platform server-name collection-name]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/local-repository/metadata-collection-name/" collection-name)]
(http/post url
{:insecure? true})))
(defn configure-event-bus
[admin-platform server-name event-bus-root-url]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/event-bus")
event-bus-body (json/json-str
{"producer" {"bootstrap.servers" event-bus-root-url}
"consumer" {"bootstrap.servers" event-bus-root-url}})]
(http/post url
{:insecure? true
:content-type :json
:body event-bus-body})))
(defn configure-cohort-membership
[admin-platform server-name cohort-name]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/cohorts/" cohort-name)]
(http/post url
{:insecure? true})))
(defn configure-repository-workbench
[admin-platform server-name sut-server-name]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/conformance-suite-workbenches/repository-workbench/repositories")
workbench-config-body (json/json-str
{"class" "RepositoryConformanceWorkbenchConfig"
"tutRepositoryServerName" sut-server-name
"maxSearchResults" 10})]
(http/post url
{:insecure? true
:content-type :json
:body workbench-config-body})))
(defn deploy-server
[admin-platform server-name target-platform]
(let [admin-command-url (admin-command-url admin-platform)
url (str admin-command-url server-name "/configuration/deploy")
target-platform-url (:platform-url target-platform)
request-body (json/json-str
{"class" "URLRequestBody"
"urlRoot" target-platform-url})]
(http/post url
{:insecure? true
:content-type :json
:body request-body})))
(defn start-server
[platform server-name]
(let [platform-url (:platform-url platform)
admin-user-id (:admin-user-id platform)
url (str platform-url "/open-metadata/admin-services/users/" admin-user-id "/servers/" server-name "/instance")]
(http/post url
{:insecure? true})))
(defn stop-server
[platform server-name]
(let [platform-url (:platform-url platform)
admin-user-id (:admin-user-id platform)
url (str platform-url "/open-metadata/admin-services/users/" admin-user-id "/servers/" server-name "/instance")]
(http/delete url
{:insecure? true})))
(defn start-sut-server []
(let [system (system)
platform (::platform system)
server-name (get-in system [::sut-server :server-name])]
(start-server platform server-name)))
(defn start-cts-server []
(let [system (system)
platform (::platform system)
server-name (get-in system [::cts-server :server-name])]
(start-server platform server-name)))
(defn start-kafka-container []
(let [kafka (doto (KafkaContainer. (DockerImageName/parse "confluentinc/cp-kafka:5.4.3"))
(.withExposedPorts (into-array Integer [(int 9093)]))
(.start))
root-url (str "localhost:" (.getMappedPort kafka 9093))]
{:kafka-container kafka
:root-url root-url}))
(defn start-omag-platform [{:keys [egeria-home version server-port admin-user-id]}]
(let [server-jar-path (str egeria-home "/server/server-chassis-spring-" version ".jar")
jvm-opts (str "-Dserver.port=" server-port)
process-builder (doto (ProcessBuilder. ["/usr/bin/java" jvm-opts "-jar" server-jar-path])
(.directory (io/file egeria-home)))
platform-process (.start process-builder)
platform-url (str "https://localhost:" server-port)]
(Thread/sleep 15000)
{:platform-process platform-process
:platform-url platform-url
:admin-user-id admin-user-id}))
(defmethod ig/init-key ::event-bus [_ _]
(start-kafka-container))
(defmethod ig/halt-key! ::event-bus [_ {:keys [^KafkaContainer kafka-container]}]
(when kafka-container
(.stop kafka-container)))
(defmethod ig/init-key ::platform [_ config]
(start-omag-platform config))
(defmethod ig/halt-key! ::platform [_ {:keys [^Process platform-process]}]
(when platform-process
(.destroy platform-process)))
(defmethod ig/init-key ::sut-server
[_ {:keys [admin-platform server-name event-bus server-user-id server-password server-type
platform metadata-repository-connector metadata-collection-name
cohort metadata-repository-connector-provider additional-properties]
:as server-config}]
(let [event-bus-root-url (:root-url event-bus)]
(configure-platform-url admin-platform server-name platform)
(configure-server-type admin-platform server-name server-type)
(configure-user-id admin-platform server-name server-user-id)
(configure-password admin-platform server-name server-password)
(configure-plugin-metadata-repository admin-platform server-name metadata-repository-connector)
;;(configure-metadata-repository admin-platform server-name metadata-repository-type)
(configure-descriptive-name admin-platform server-name metadata-collection-name)
(configure-event-bus admin-platform server-name event-bus-root-url)
(configure-cohort-membership admin-platform server-name cohort)
(deploy-server admin-platform server-name platform)
#_(start-server platform server-name)
server-config))
(defmethod ig/halt-key! ::sut-server [_ {:keys [platform server-name]}]
(stop-server platform server-name))
(defmethod ig/init-key ::cts-server
[_ {:keys [admin-platform server-name event-bus server-user-id server-password server-type
platform metadata-repository-type sut-server
cohort]
:as server-config}]
(let [event-bus-root-url (:root-url event-bus)
sut-server-name (:server-name sut-server)]
(configure-platform-url admin-platform server-name platform)
(configure-server-type admin-platform server-name server-type)
(configure-user-id admin-platform server-name server-user-id)
(configure-password admin-platform server-name server-password)
(configure-metadata-repository admin-platform server-name metadata-repository-type)
(configure-event-bus admin-platform server-name event-bus-root-url)
(configure-cohort-membership admin-platform server-name cohort)
(configure-repository-workbench admin-platform server-name sut-server-name)
(deploy-server admin-platform server-name platform)
#_(start-server platform server-name)
server-config))
(defmethod ig/halt-key! ::cts-server [_ {:keys [platform server-name]}]
(stop-server platform server-name))
;; https://localhost:9443/open-metadata/admin-services/users/garygeeke/servers/SUT_Server/configuration
;; https://localhost:9443/open-metadata/admin-services/users/garygeeke/servers/SUT_Server/configuration
;; https://localhost:9443/servers/CTS_Server/open-metadata/conformance-suite/users/garygeeke/report/summary
;; https://localhost:9443/servers/CTS_Server/open-metadata/conformance-suite/users/garygeeke/report/test-cases/failed |
[
{
"context": "cc {x (phi journal x)})))))))\n\n(defn -main\n \"save Jacques\"\n []\n (list-correlations journal))\n",
"end": 8075,
"score": 0.7663242220878601,
"start": 8068,
"tag": "NAME",
"value": "Jacques"
}
] | src/weresquirrel/core.clj | ird/weresquirrel | 0 | (ns weresquirrel.core
(:gen-class))
(def journal
[{:events ["carrot" "exercise" "weekend"] :squirrel false}
{:events ["bread" "pudding" "brushed teeth" "weekend" "touched tree"] :squirrel false}
{:events ["carrot" "nachos" "brushed teeth" "cycling" "weekend"] :squirrel false}
{:events ["brussel sprouts" "ice cream" "brushed teeth" "computer" "weekend"] :squirrel false}
{:events ["potatoes" "candy" "brushed teeth" "exercise" "weekend" "dentist"] :squirrel false}
{:events ["brussel sprouts" "pudding" "brushed teeth" "running" "weekend"] :squirrel false}
{:events ["pizza" "brushed teeth" "computer" "work" "touched tree"] :squirrel false}
{:events ["bread" "beer" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["cauliflower" "brushed teeth" "work"] :squirrel false}
{:events ["pizza" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["lasagna" "nachos" "brushed teeth" "work"] :squirrel false}
{:events ["brushed teeth" "weekend" "touched tree"] :squirrel false}
{:events ["lettuce" "brushed teeth" "television" "weekend"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "work"] :squirrel false}
{:events ["brushed teeth" "computer" "work"] :squirrel false}
{:events ["lettuce" "nachos" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "brushed teeth" "running" "work"] :squirrel false}
{:events ["brushed teeth" "work"] :squirrel false}
{:events ["cauliflower" "reading" "weekend"] :squirrel false}
{:events ["bread" "brushed teeth" "weekend"] :squirrel false}
{:events ["lasagna" "brushed teeth" "exercise" "work"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "reading" "work"] :squirrel false}
{:events ["carrot" "ice cream" "brushed teeth" "television" "work"] :squirrel false}
{:events ["spaghetti" "nachos" "work"] :squirrel false}
{:events ["cauliflower" "ice cream" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["spaghetti" "peanuts" "computer" "weekend"] :squirrel true}
{:events ["potatoes" "ice cream" "brushed teeth" "computer" "weekend"] :squirrel false}
{:events ["potatoes" "ice cream" "brushed teeth" "work"] :squirrel false}
{:events ["peanuts" "brushed teeth" "running" "work"] :squirrel false}
{:events ["potatoes" "exercise" "work"] :squirrel false}
{:events ["pizza" "ice cream" "computer" "work"] :squirrel false}
{:events ["lasagna" "ice cream" "work"] :squirrel false}
{:events ["cauliflower" "candy" "reading" "weekend"] :squirrel false}
{:events ["lasagna" "nachos" "brushed teeth" "running" "weekend"] :squirrel false}
{:events ["potatoes" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "work"] :squirrel false}
{:events ["pizza" "beer" "work" "dentist"] :squirrel false}
{:events ["lasagna" "pudding" "cycling" "work"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "reading" "work"] :squirrel false}
{:events ["spaghetti" "pudding" "television" "weekend"] :squirrel false}
{:events ["bread" "brushed teeth" "exercise" "weekend"] :squirrel false}
{:events ["lasagna" "peanuts" "work"] :squirrel true}
{:events ["pizza" "work"] :squirrel false}
{:events ["potatoes" "exercise" "work"] :squirrel false}
{:events ["brushed teeth" "exercise" "work"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "television" "work"] :squirrel false}
{:events ["pizza" "cycling" "weekend"] :squirrel false}
{:events ["carrot" "brushed teeth" "weekend"] :squirrel false}
{:events ["carrot" "beer" "brushed teeth" "work"] :squirrel false}
{:events ["pizza" "peanuts" "candy" "work"] :squirrel true}
{:events ["carrot" "peanuts" "brushed teeth" "reading" "work"] :squirrel false}
{:events ["potatoes" "peanuts" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "nachos" "brushed teeth" "exercise" "work"] :squirrel false}
{:events ["pizza" "peanuts" "brushed teeth" "television" "weekend"] :squirrel false}
{:events ["lasagna" "brushed teeth" "cycling" "weekend"] :squirrel false}
{:events ["cauliflower" "peanuts" "brushed teeth" "computer" "work" "touched tree"] :squirrel false}
{:events ["lettuce" "brushed teeth" "television" "work"] :squirrel false}
{:events ["potatoes" "brushed teeth" "computer" "work"] :squirrel false}
{:events ["bread" "candy" "work"] :squirrel false}
{:events ["potatoes" "nachos" "work"] :squirrel false}
{:events ["carrot" "pudding" "brushed teeth" "weekend"] :squirrel false}
{:events ["carrot" "brushed teeth" "exercise" "weekend" "touched tree"] :squirrel false}
{:events ["brussel sprouts" "running" "work"] :squirrel false}
{:events ["brushed teeth" "work"] :squirrel false}
{:events ["lettuce" "brushed teeth" "running" "work"] :squirrel false}
{:events ["candy" "brushed teeth" "work"] :squirrel false}
{:events ["brussel sprouts" "brushed teeth" "computer" "work"] :squirrel false}
{:events ["bread" "brushed teeth" "weekend"] :squirrel false}
{:events ["cauliflower" "brushed teeth" "weekend"] :squirrel false}
{:events ["spaghetti" "candy" "television" "work" "touched tree"] :squirrel false}
{:events ["carrot" "pudding" "brushed teeth" "work"] :squirrel false}
{:events ["lettuce" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "ice cream" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["pizza" "brushed teeth" "work"] :squirrel false}
{:events ["spaghetti" "peanuts" "exercise" "weekend"] :squirrel true}
{:events ["bread" "beer" "computer" "weekend" "touched tree"] :squirrel false}
{:events ["brushed teeth" "running" "work"] :squirrel false}
{:events ["lettuce" "peanuts" "brushed teeth" "work" "touched tree"] :squirrel false}
{:events ["lasagna" "brushed teeth" "television" "work"] :squirrel false}
{:events ["cauliflower" "brushed teeth" "running" "work"] :squirrel false}
{:events ["carrot" "brushed teeth" "running" "work"] :squirrel false}
{:events ["carrot" "reading" "weekend"] :squirrel false}
{:events ["carrot" "peanuts" "reading" "weekend"] :squirrel true}
{:events ["potatoes" "brushed teeth" "running" "work"] :squirrel false}
{:events ["lasagna" "ice cream" "work" "touched tree"] :squirrel false}
{:events ["cauliflower" "peanuts" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["pizza" "brushed teeth" "running" "work"] :squirrel false}
{:events ["lettuce" "brushed teeth" "work"] :squirrel false}
{:events ["bread" "brushed teeth" "television" "weekend"] :squirrel false}
{:events ["cauliflower" "peanuts" "brushed teeth" "weekend"] :squirrel false}
])
(def events (fn [m] (reduce conj #{} (flatten (map :events m)))))
(def table-for
"find :n00 :n01 :n10 and :n11 (nXY X=squirrelness Y=event happened)"
(fn [journal event]
(loop [[entry & rem] journal t {:n00 0 :n01 0 :n10 0 :n11 0}]
(if (empty? entry) t
(if (:squirrel entry)
(if (some #{event} (:events entry))
(recur rem
{:n00 (:n00 t) :n01 (:n01 t) :n10 (:n10 t) :n11 (+ (:n11 t) 1)})
(recur rem
{:n00 (:n00 t) :n01 (:n01 t) :n10 (+ (:n10 t) 1) :n11 (:n11 t)}))
(if (some #{event} (:events entry))
(recur rem
{:n00 (:n00 t) :n01 (+ (:n01 t) 1) :n10 (:n10 t) :n11 (:n11 t)})
(recur rem
{:n00 (+ (:n00 t) 1) :n01 (:n01 t) :n10 (:n10 t) :n11 (:n11 t)})))))))
(def phi
(fn [journal event]
(let [t (table-for journal event)]
(/
(- (* (:n00 t) (:n11 t)) (* (:n10 t) (:n01 t)))
(java.lang.Math/sqrt (* (+ (:n10 t) (:n11 t)) (+ (:n00 t) (:n01 t))
(+ (:n01 t) (:n11 t)) (+ (:n00 t) (:n10 t))))))))
(def list-correlations
"find the correlation between his activities in his journal with turning into a squirrel"
(fn [journal]
(loop [rem (events journal) acc {}]
(let [x (first rem) xs (disj rem x)]
(if (nil? x) acc
(recur xs (conj acc {x (phi journal x)})))))))
(defn -main
"save Jacques"
[]
(list-correlations journal))
| 82701 | (ns weresquirrel.core
(:gen-class))
(def journal
[{:events ["carrot" "exercise" "weekend"] :squirrel false}
{:events ["bread" "pudding" "brushed teeth" "weekend" "touched tree"] :squirrel false}
{:events ["carrot" "nachos" "brushed teeth" "cycling" "weekend"] :squirrel false}
{:events ["brussel sprouts" "ice cream" "brushed teeth" "computer" "weekend"] :squirrel false}
{:events ["potatoes" "candy" "brushed teeth" "exercise" "weekend" "dentist"] :squirrel false}
{:events ["brussel sprouts" "pudding" "brushed teeth" "running" "weekend"] :squirrel false}
{:events ["pizza" "brushed teeth" "computer" "work" "touched tree"] :squirrel false}
{:events ["bread" "beer" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["cauliflower" "brushed teeth" "work"] :squirrel false}
{:events ["pizza" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["lasagna" "nachos" "brushed teeth" "work"] :squirrel false}
{:events ["brushed teeth" "weekend" "touched tree"] :squirrel false}
{:events ["lettuce" "brushed teeth" "television" "weekend"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "work"] :squirrel false}
{:events ["brushed teeth" "computer" "work"] :squirrel false}
{:events ["lettuce" "nachos" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "brushed teeth" "running" "work"] :squirrel false}
{:events ["brushed teeth" "work"] :squirrel false}
{:events ["cauliflower" "reading" "weekend"] :squirrel false}
{:events ["bread" "brushed teeth" "weekend"] :squirrel false}
{:events ["lasagna" "brushed teeth" "exercise" "work"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "reading" "work"] :squirrel false}
{:events ["carrot" "ice cream" "brushed teeth" "television" "work"] :squirrel false}
{:events ["spaghetti" "nachos" "work"] :squirrel false}
{:events ["cauliflower" "ice cream" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["spaghetti" "peanuts" "computer" "weekend"] :squirrel true}
{:events ["potatoes" "ice cream" "brushed teeth" "computer" "weekend"] :squirrel false}
{:events ["potatoes" "ice cream" "brushed teeth" "work"] :squirrel false}
{:events ["peanuts" "brushed teeth" "running" "work"] :squirrel false}
{:events ["potatoes" "exercise" "work"] :squirrel false}
{:events ["pizza" "ice cream" "computer" "work"] :squirrel false}
{:events ["lasagna" "ice cream" "work"] :squirrel false}
{:events ["cauliflower" "candy" "reading" "weekend"] :squirrel false}
{:events ["lasagna" "nachos" "brushed teeth" "running" "weekend"] :squirrel false}
{:events ["potatoes" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "work"] :squirrel false}
{:events ["pizza" "beer" "work" "dentist"] :squirrel false}
{:events ["lasagna" "pudding" "cycling" "work"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "reading" "work"] :squirrel false}
{:events ["spaghetti" "pudding" "television" "weekend"] :squirrel false}
{:events ["bread" "brushed teeth" "exercise" "weekend"] :squirrel false}
{:events ["lasagna" "peanuts" "work"] :squirrel true}
{:events ["pizza" "work"] :squirrel false}
{:events ["potatoes" "exercise" "work"] :squirrel false}
{:events ["brushed teeth" "exercise" "work"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "television" "work"] :squirrel false}
{:events ["pizza" "cycling" "weekend"] :squirrel false}
{:events ["carrot" "brushed teeth" "weekend"] :squirrel false}
{:events ["carrot" "beer" "brushed teeth" "work"] :squirrel false}
{:events ["pizza" "peanuts" "candy" "work"] :squirrel true}
{:events ["carrot" "peanuts" "brushed teeth" "reading" "work"] :squirrel false}
{:events ["potatoes" "peanuts" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "nachos" "brushed teeth" "exercise" "work"] :squirrel false}
{:events ["pizza" "peanuts" "brushed teeth" "television" "weekend"] :squirrel false}
{:events ["lasagna" "brushed teeth" "cycling" "weekend"] :squirrel false}
{:events ["cauliflower" "peanuts" "brushed teeth" "computer" "work" "touched tree"] :squirrel false}
{:events ["lettuce" "brushed teeth" "television" "work"] :squirrel false}
{:events ["potatoes" "brushed teeth" "computer" "work"] :squirrel false}
{:events ["bread" "candy" "work"] :squirrel false}
{:events ["potatoes" "nachos" "work"] :squirrel false}
{:events ["carrot" "pudding" "brushed teeth" "weekend"] :squirrel false}
{:events ["carrot" "brushed teeth" "exercise" "weekend" "touched tree"] :squirrel false}
{:events ["brussel sprouts" "running" "work"] :squirrel false}
{:events ["brushed teeth" "work"] :squirrel false}
{:events ["lettuce" "brushed teeth" "running" "work"] :squirrel false}
{:events ["candy" "brushed teeth" "work"] :squirrel false}
{:events ["brussel sprouts" "brushed teeth" "computer" "work"] :squirrel false}
{:events ["bread" "brushed teeth" "weekend"] :squirrel false}
{:events ["cauliflower" "brushed teeth" "weekend"] :squirrel false}
{:events ["spaghetti" "candy" "television" "work" "touched tree"] :squirrel false}
{:events ["carrot" "pudding" "brushed teeth" "work"] :squirrel false}
{:events ["lettuce" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "ice cream" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["pizza" "brushed teeth" "work"] :squirrel false}
{:events ["spaghetti" "peanuts" "exercise" "weekend"] :squirrel true}
{:events ["bread" "beer" "computer" "weekend" "touched tree"] :squirrel false}
{:events ["brushed teeth" "running" "work"] :squirrel false}
{:events ["lettuce" "peanuts" "brushed teeth" "work" "touched tree"] :squirrel false}
{:events ["lasagna" "brushed teeth" "television" "work"] :squirrel false}
{:events ["cauliflower" "brushed teeth" "running" "work"] :squirrel false}
{:events ["carrot" "brushed teeth" "running" "work"] :squirrel false}
{:events ["carrot" "reading" "weekend"] :squirrel false}
{:events ["carrot" "peanuts" "reading" "weekend"] :squirrel true}
{:events ["potatoes" "brushed teeth" "running" "work"] :squirrel false}
{:events ["lasagna" "ice cream" "work" "touched tree"] :squirrel false}
{:events ["cauliflower" "peanuts" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["pizza" "brushed teeth" "running" "work"] :squirrel false}
{:events ["lettuce" "brushed teeth" "work"] :squirrel false}
{:events ["bread" "brushed teeth" "television" "weekend"] :squirrel false}
{:events ["cauliflower" "peanuts" "brushed teeth" "weekend"] :squirrel false}
])
(def events (fn [m] (reduce conj #{} (flatten (map :events m)))))
(def table-for
"find :n00 :n01 :n10 and :n11 (nXY X=squirrelness Y=event happened)"
(fn [journal event]
(loop [[entry & rem] journal t {:n00 0 :n01 0 :n10 0 :n11 0}]
(if (empty? entry) t
(if (:squirrel entry)
(if (some #{event} (:events entry))
(recur rem
{:n00 (:n00 t) :n01 (:n01 t) :n10 (:n10 t) :n11 (+ (:n11 t) 1)})
(recur rem
{:n00 (:n00 t) :n01 (:n01 t) :n10 (+ (:n10 t) 1) :n11 (:n11 t)}))
(if (some #{event} (:events entry))
(recur rem
{:n00 (:n00 t) :n01 (+ (:n01 t) 1) :n10 (:n10 t) :n11 (:n11 t)})
(recur rem
{:n00 (+ (:n00 t) 1) :n01 (:n01 t) :n10 (:n10 t) :n11 (:n11 t)})))))))
(def phi
(fn [journal event]
(let [t (table-for journal event)]
(/
(- (* (:n00 t) (:n11 t)) (* (:n10 t) (:n01 t)))
(java.lang.Math/sqrt (* (+ (:n10 t) (:n11 t)) (+ (:n00 t) (:n01 t))
(+ (:n01 t) (:n11 t)) (+ (:n00 t) (:n10 t))))))))
(def list-correlations
"find the correlation between his activities in his journal with turning into a squirrel"
(fn [journal]
(loop [rem (events journal) acc {}]
(let [x (first rem) xs (disj rem x)]
(if (nil? x) acc
(recur xs (conj acc {x (phi journal x)})))))))
(defn -main
"save <NAME>"
[]
(list-correlations journal))
| true | (ns weresquirrel.core
(:gen-class))
(def journal
[{:events ["carrot" "exercise" "weekend"] :squirrel false}
{:events ["bread" "pudding" "brushed teeth" "weekend" "touched tree"] :squirrel false}
{:events ["carrot" "nachos" "brushed teeth" "cycling" "weekend"] :squirrel false}
{:events ["brussel sprouts" "ice cream" "brushed teeth" "computer" "weekend"] :squirrel false}
{:events ["potatoes" "candy" "brushed teeth" "exercise" "weekend" "dentist"] :squirrel false}
{:events ["brussel sprouts" "pudding" "brushed teeth" "running" "weekend"] :squirrel false}
{:events ["pizza" "brushed teeth" "computer" "work" "touched tree"] :squirrel false}
{:events ["bread" "beer" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["cauliflower" "brushed teeth" "work"] :squirrel false}
{:events ["pizza" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["lasagna" "nachos" "brushed teeth" "work"] :squirrel false}
{:events ["brushed teeth" "weekend" "touched tree"] :squirrel false}
{:events ["lettuce" "brushed teeth" "television" "weekend"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "work"] :squirrel false}
{:events ["brushed teeth" "computer" "work"] :squirrel false}
{:events ["lettuce" "nachos" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "brushed teeth" "running" "work"] :squirrel false}
{:events ["brushed teeth" "work"] :squirrel false}
{:events ["cauliflower" "reading" "weekend"] :squirrel false}
{:events ["bread" "brushed teeth" "weekend"] :squirrel false}
{:events ["lasagna" "brushed teeth" "exercise" "work"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "reading" "work"] :squirrel false}
{:events ["carrot" "ice cream" "brushed teeth" "television" "work"] :squirrel false}
{:events ["spaghetti" "nachos" "work"] :squirrel false}
{:events ["cauliflower" "ice cream" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["spaghetti" "peanuts" "computer" "weekend"] :squirrel true}
{:events ["potatoes" "ice cream" "brushed teeth" "computer" "weekend"] :squirrel false}
{:events ["potatoes" "ice cream" "brushed teeth" "work"] :squirrel false}
{:events ["peanuts" "brushed teeth" "running" "work"] :squirrel false}
{:events ["potatoes" "exercise" "work"] :squirrel false}
{:events ["pizza" "ice cream" "computer" "work"] :squirrel false}
{:events ["lasagna" "ice cream" "work"] :squirrel false}
{:events ["cauliflower" "candy" "reading" "weekend"] :squirrel false}
{:events ["lasagna" "nachos" "brushed teeth" "running" "weekend"] :squirrel false}
{:events ["potatoes" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "work"] :squirrel false}
{:events ["pizza" "beer" "work" "dentist"] :squirrel false}
{:events ["lasagna" "pudding" "cycling" "work"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "reading" "work"] :squirrel false}
{:events ["spaghetti" "pudding" "television" "weekend"] :squirrel false}
{:events ["bread" "brushed teeth" "exercise" "weekend"] :squirrel false}
{:events ["lasagna" "peanuts" "work"] :squirrel true}
{:events ["pizza" "work"] :squirrel false}
{:events ["potatoes" "exercise" "work"] :squirrel false}
{:events ["brushed teeth" "exercise" "work"] :squirrel false}
{:events ["spaghetti" "brushed teeth" "television" "work"] :squirrel false}
{:events ["pizza" "cycling" "weekend"] :squirrel false}
{:events ["carrot" "brushed teeth" "weekend"] :squirrel false}
{:events ["carrot" "beer" "brushed teeth" "work"] :squirrel false}
{:events ["pizza" "peanuts" "candy" "work"] :squirrel true}
{:events ["carrot" "peanuts" "brushed teeth" "reading" "work"] :squirrel false}
{:events ["potatoes" "peanuts" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "nachos" "brushed teeth" "exercise" "work"] :squirrel false}
{:events ["pizza" "peanuts" "brushed teeth" "television" "weekend"] :squirrel false}
{:events ["lasagna" "brushed teeth" "cycling" "weekend"] :squirrel false}
{:events ["cauliflower" "peanuts" "brushed teeth" "computer" "work" "touched tree"] :squirrel false}
{:events ["lettuce" "brushed teeth" "television" "work"] :squirrel false}
{:events ["potatoes" "brushed teeth" "computer" "work"] :squirrel false}
{:events ["bread" "candy" "work"] :squirrel false}
{:events ["potatoes" "nachos" "work"] :squirrel false}
{:events ["carrot" "pudding" "brushed teeth" "weekend"] :squirrel false}
{:events ["carrot" "brushed teeth" "exercise" "weekend" "touched tree"] :squirrel false}
{:events ["brussel sprouts" "running" "work"] :squirrel false}
{:events ["brushed teeth" "work"] :squirrel false}
{:events ["lettuce" "brushed teeth" "running" "work"] :squirrel false}
{:events ["candy" "brushed teeth" "work"] :squirrel false}
{:events ["brussel sprouts" "brushed teeth" "computer" "work"] :squirrel false}
{:events ["bread" "brushed teeth" "weekend"] :squirrel false}
{:events ["cauliflower" "brushed teeth" "weekend"] :squirrel false}
{:events ["spaghetti" "candy" "television" "work" "touched tree"] :squirrel false}
{:events ["carrot" "pudding" "brushed teeth" "work"] :squirrel false}
{:events ["lettuce" "brushed teeth" "work"] :squirrel false}
{:events ["carrot" "ice cream" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["pizza" "brushed teeth" "work"] :squirrel false}
{:events ["spaghetti" "peanuts" "exercise" "weekend"] :squirrel true}
{:events ["bread" "beer" "computer" "weekend" "touched tree"] :squirrel false}
{:events ["brushed teeth" "running" "work"] :squirrel false}
{:events ["lettuce" "peanuts" "brushed teeth" "work" "touched tree"] :squirrel false}
{:events ["lasagna" "brushed teeth" "television" "work"] :squirrel false}
{:events ["cauliflower" "brushed teeth" "running" "work"] :squirrel false}
{:events ["carrot" "brushed teeth" "running" "work"] :squirrel false}
{:events ["carrot" "reading" "weekend"] :squirrel false}
{:events ["carrot" "peanuts" "reading" "weekend"] :squirrel true}
{:events ["potatoes" "brushed teeth" "running" "work"] :squirrel false}
{:events ["lasagna" "ice cream" "work" "touched tree"] :squirrel false}
{:events ["cauliflower" "peanuts" "brushed teeth" "cycling" "work"] :squirrel false}
{:events ["pizza" "brushed teeth" "running" "work"] :squirrel false}
{:events ["lettuce" "brushed teeth" "work"] :squirrel false}
{:events ["bread" "brushed teeth" "television" "weekend"] :squirrel false}
{:events ["cauliflower" "peanuts" "brushed teeth" "weekend"] :squirrel false}
])
(def events (fn [m] (reduce conj #{} (flatten (map :events m)))))
(def table-for
"find :n00 :n01 :n10 and :n11 (nXY X=squirrelness Y=event happened)"
(fn [journal event]
(loop [[entry & rem] journal t {:n00 0 :n01 0 :n10 0 :n11 0}]
(if (empty? entry) t
(if (:squirrel entry)
(if (some #{event} (:events entry))
(recur rem
{:n00 (:n00 t) :n01 (:n01 t) :n10 (:n10 t) :n11 (+ (:n11 t) 1)})
(recur rem
{:n00 (:n00 t) :n01 (:n01 t) :n10 (+ (:n10 t) 1) :n11 (:n11 t)}))
(if (some #{event} (:events entry))
(recur rem
{:n00 (:n00 t) :n01 (+ (:n01 t) 1) :n10 (:n10 t) :n11 (:n11 t)})
(recur rem
{:n00 (+ (:n00 t) 1) :n01 (:n01 t) :n10 (:n10 t) :n11 (:n11 t)})))))))
(def phi
(fn [journal event]
(let [t (table-for journal event)]
(/
(- (* (:n00 t) (:n11 t)) (* (:n10 t) (:n01 t)))
(java.lang.Math/sqrt (* (+ (:n10 t) (:n11 t)) (+ (:n00 t) (:n01 t))
(+ (:n01 t) (:n11 t)) (+ (:n00 t) (:n10 t))))))))
(def list-correlations
"find the correlation between his activities in his journal with turning into a squirrel"
(fn [journal]
(loop [rem (events journal) acc {}]
(let [x (first rem) xs (disj rem x)]
(if (nil? x) acc
(recur xs (conj acc {x (phi journal x)})))))))
(defn -main
"save PI:NAME:<NAME>END_PI"
[]
(list-correlations journal))
|
[
{
"context": "key/certificate files\"\n :url \"https://github.com/into-docker/pem-reader\"\n :license {:name \"MIT\"\n :",
"end": 154,
"score": 0.9986875653266907,
"start": 143,
"tag": "USERNAME",
"value": "into-docker"
},
{
"context": "ses/mit\"\n :year 2015\n :key \"mit\"\n :comment \"MIT License\"}\n :dependenc",
"end": 294,
"score": 0.9516513347625732,
"start": 291,
"tag": "KEY",
"value": "mit"
}
] | project.clj | xsc/pem-reader | 4 | (defproject into-docker/pem-reader "1.0.3-SNAPSHOT"
:description "A lightweight reader for key/certificate files"
:url "https://github.com/into-docker/pem-reader"
:license {:name "MIT"
:url "https://choosealicense.com/licenses/mit"
:year 2015
:key "mit"
:comment "MIT License"}
:dependencies [[org.clojure/clojure "1.10.2" :scope "provided"]]
:profiles {:dev
{:global-vars {*warn-on-reflection* true}}
:kaocha
{:dependencies [[lambdaisland/kaocha "1.0.732"
:exclusions [org.clojure/spec.alpha]]
[lambdaisland/kaocha-cloverage "1.0.75"]]}
:ci
[:kaocha
{:global-vars {*warn-on-reflection* false}}]}
:aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"]
"ci" ["with-profile" "+ci" "run" "-m" "kaocha.runner"
"--reporter" "documentation"
"--plugin" "cloverage"
"--codecov"
"--no-cov-html"]}
:pedantic? :abort)
| 101762 | (defproject into-docker/pem-reader "1.0.3-SNAPSHOT"
:description "A lightweight reader for key/certificate files"
:url "https://github.com/into-docker/pem-reader"
:license {:name "MIT"
:url "https://choosealicense.com/licenses/mit"
:year 2015
:key "<KEY>"
:comment "MIT License"}
:dependencies [[org.clojure/clojure "1.10.2" :scope "provided"]]
:profiles {:dev
{:global-vars {*warn-on-reflection* true}}
:kaocha
{:dependencies [[lambdaisland/kaocha "1.0.732"
:exclusions [org.clojure/spec.alpha]]
[lambdaisland/kaocha-cloverage "1.0.75"]]}
:ci
[:kaocha
{:global-vars {*warn-on-reflection* false}}]}
:aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"]
"ci" ["with-profile" "+ci" "run" "-m" "kaocha.runner"
"--reporter" "documentation"
"--plugin" "cloverage"
"--codecov"
"--no-cov-html"]}
:pedantic? :abort)
| true | (defproject into-docker/pem-reader "1.0.3-SNAPSHOT"
:description "A lightweight reader for key/certificate files"
:url "https://github.com/into-docker/pem-reader"
:license {:name "MIT"
:url "https://choosealicense.com/licenses/mit"
:year 2015
:key "PI:KEY:<KEY>END_PI"
:comment "MIT License"}
:dependencies [[org.clojure/clojure "1.10.2" :scope "provided"]]
:profiles {:dev
{:global-vars {*warn-on-reflection* true}}
:kaocha
{:dependencies [[lambdaisland/kaocha "1.0.732"
:exclusions [org.clojure/spec.alpha]]
[lambdaisland/kaocha-cloverage "1.0.75"]]}
:ci
[:kaocha
{:global-vars {*warn-on-reflection* false}}]}
:aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"]
"ci" ["with-profile" "+ci" "run" "-m" "kaocha.runner"
"--reporter" "documentation"
"--plugin" "cloverage"
"--codecov"
"--no-cov-html"]}
:pedantic? :abort)
|
[
{
"context": "='login']\\\")\n\n (input-text \\\"#login_field\\\" \\\"your_username\\\")\n (-> \\\"#password\\\"\n (input-text \\\"yo",
"end": 4366,
"score": 0.9904303550720215,
"start": 4353,
"tag": "USERNAME",
"value": "your_username"
},
{
"context": " (input-text \\\"//input[@id='login_field']\\\" \\\"your_username\\\")\n (-> \\\"//input[@id='password']\\\"\n (i",
"end": 5009,
"score": 0.9908407330513,
"start": 4996,
"tag": "USERNAME",
"value": "your_username"
},
{
"context": ":\n =========\n\n (quick-fill {\\\"#first_name\\\" \\\"Rich\\\"}\n {\\\"a.foo\\\" click})\"\n [& query-",
"end": 43550,
"score": 0.9992861151695251,
"start": 43546,
"tag": "NAME",
"value": "Rich"
},
{
"context": ":\n =========\n\n (quick-fill {\\\"#first_name\\\" \\\"Rich\\\"}\n {\\\"a.foo\\\" click})\"\n [& query-",
"end": 44271,
"score": 0.9992292523384094,
"start": 44267,
"tag": "NAME",
"value": "Rich"
}
] | test/src/webdriver/clj_webdriver/taxi.clj | mbertheau/dirac | 802 | ;; The faster way to use clj-webdriver: take a taxi
(ns clj-webdriver.taxi
(:use [clj-webdriver.driver :only [driver?]]
[clj-webdriver.element :only [element-like?]])
(:require [clj-webdriver.core :as core]
[clj-webdriver.options :as options]
[clj-webdriver.util :as util]
[clj-webdriver.wait :as wait]
[clj-webdriver.window :as win])
(:import clj_webdriver.element.Element))
(declare css-finder)
(def ^:dynamic *driver*)
(def ^:dynamic *finder-fn* css-finder)
(def ^{:doc (str "Alias of clj-webdriver.core/new-driver:\n"
(:doc (meta #'clj-webdriver.core/new-driver)))
:arglists (:arglists (meta #'clj-webdriver.core/new-driver))}
new-driver clj-webdriver.core/new-driver)
(defn- set-driver*
"Given a `browser-spec`, instantiate a new Driver record and assign to `*driver*`."
[browser-spec]
(let [new-driver (if (driver? browser-spec)
browser-spec
(core/new-driver browser-spec))]
(alter-var-root (var *driver*)
(constantly new-driver)
(when (thread-bound? (var *driver*))
(set! *driver* new-driver)))))
(declare to)
(defn set-driver!
"Set a default `Driver` for this thread, optionally sending it to a starting `url`.
Available browsers are `:firefox`, `:chrome`, `:ie`, `:opera`, `:phantomjs` and `:htmlunit`.
Examples:
=========
;;
;; Simple example
;;
(set-driver! {:browser :firefox})
;;
;; Full example
;;
(set-driver! {:browser :firefox
:cache-spec {:strategy :basic,
:args [{}],
:include [ (fn [element] (= (attribute element :class) \"external\"))
{:css \"ol#pages\"}]}
;;
;; Use existing Driver record
;;
(set-driver! a-driver)"
([browser-spec] (set-driver* browser-spec))
([browser-spec url] (to (set-driver* browser-spec) url)))
(defn set-finder!
"Set a default finder function, which will be used with all `q` parameters in functions that require an Element.
Examples:
=========
;;
;; Simple example
;;
(set-finder! xpath-finder)
;;
;; Derivative finder function
;;
;; Takes the query string and always prepends \"div#container \", which would be
;; useful in situations where you know you're always inside that particular div.
;; (Note that this same functionality is provided by `find-element-under`, but
;; you get the idea.)
;;
(set-finder! (fn [q]
(if (element-like? q)
q
(css-finder (str \"div#container \" q)))))
;;
;; Custom finder function
;;
;; If you want to easily switch between using CSS and XPath (e.g., because
;; XPath has the text() function for which no CSS equivalent exists), then
;; you could write something like this, where `q` would become either the map
;; {:css \"query\"} or {:xpath \"query\"} instead of just a string.
;;
(set-finder! (fn [q]
(if (element-like? q)
q
(case (first (keys q))
:css (core/find-elements-by *driver* (by-css (first (values q))))
:xpath (core/find-elements-by *driver* (by-xpath (first (values q))))))))
;;
;; (Note: This last example is written to show how to use the lowest-level functions
;; `find-elements-by`, `by-css` and `by-xpath`. The maps `{:css \"query\"}` and
;; `{:xpath \"query\"}` are themselves acceptable arguments to the `find-elements`,
;; function, so that function could have been used instead without the `case` statement.)
;;"
[finder-fn]
(alter-var-root (var *finder-fn*)
(constantly finder-fn)
(when (thread-bound? (var *finder-fn*))
(set! *finder-fn* finder-fn))))
(declare quit)
(defmacro with-driver
"Given a `browser-spec` to start a browser, execute the forms in `body`, then call `quit` on the browser. Uses the default finder function.
Examples:
=========
;;
;; Log into Github
;;
(with-driver {:browser :firefox}
(to \"https://github.com\")
(click \"a[href*='login']\")
(input-text \"#login_field\" \"your_username\")
(-> \"#password\"
(input-text \"your_password\")
submit))"
[browser-spec & body]
`(binding [*driver* (core/new-driver ~browser-spec)]
(try
~@body
(finally
(quit)))))
(defmacro with-driver-fn
"Given a `browser-spec` to start a browser and a `finder-fn` to use as a finding function, execute the forms in `body`, then call `quit` on the browser.
Examples:
=========
;;
;; Log into Github
;;
(with-driver {:browser :firefox} xpath-finder
(to \"https://github.com\")
(click \"//a[text()='Login']\")
(input-text \"//input[@id='login_field']\" \"your_username\")
(-> \"//input[@id='password']\"
(input-text \"your_password\")
submit))"
[browser-spec finder-fn & body]
`(binding [*driver* (core/new-driver ~browser-spec)
*finder-fn* ~finder-fn]
(try
~@body
(finally
(quit)))))
(defn css-finder
"Given a CSS query `q`, return a lazy seq of the elements found by calling `find-elements` with `by-css`. If `q` is an `Element`, it is returned unchanged.
This function is used internally by the Taxi API as `*finder*`. See the documentation for `set-finder!` for examples of extending this function or creating your own custom finder function."
([q] (css-finder *driver* q))
([driver q]
(cond
(element-like? q) q
(map? q) (core/find-elements driver q)
:else (core/find-elements driver {:css q}))))
(set-finder! css-finder)
(defn xpath-finder
"Given a XPath query `q`, return a lazy seq of the elements found by calling `find-elements` with `by-xpath`. If `q` is an `Element`, it is returned unchanged.
This function is used internally by the Taxi API as `*finder*`. See the documentation for `set-finder!` for examples of extending this function or creating your own custom finder function."
([q] (xpath-finder *driver* q))
([driver q]
(cond
(element-like? q) q
(map? q) (core/find-elements driver q)
:else (core/find-elements driver {:xpath q}))))
;; Be able to get actual element/elements when needed
(defn element
"Given a query `q`, return the first element that the default finder function returns.
Examples:
=========
;;
;; Simple Example
;;
;; Create a var that points to an element for later use.
;;
(def login-link (element \"a[href*='login']\"))
;;
;; More useful example: composing actions on an element
;;
;; When threading actions together, it's more performant to thread an actual element,
;; than to thread simply the query string. Threading the query string makes clj-webdriver
;; locate the same element multiple times, while threading an actual element only
;; requires one lookup.
;;
(-> (element \"input#password\")
(input-text \"my-password\")
submit)"
([q] (element *driver* q))
([driver q]
(if (element-like? q)
q
(first (*finder-fn* driver q)))))
(defn elements
"Given a query `q`, return the elements that the default finder function returns.
Examples:
=========
;;
;; Simple Example
;;
;; Save a seq of anchor tags (links) for later.
;;
(def target-elements (elements \"a\"))"
([q] (elements *driver* q))
([driver q]
(if (element-like? q)
(lazy-seq (list q))
(*finder-fn* driver q))))
;; ## Driver functions ##
(defn to
"Navigate the browser to `url`.
Examples:
=========
;;
;; Simple Example
;;
(to \"https://github.com\")
;;
;; Custom function for building URL's from a base url
;;
(defn go
[path]
(let [base-url \"http://example.com/\"]
(to (str base-url path))))
;; (go \"test-page\") would navigate to \"http://example.com/test-page\""
([url]
(to *driver* url))
([driver url]
(core/to driver url)))
(defn back
"Navigate back in the browser history, optionally `n` times.
Examples:
=========
;;
;; Simple Example
;;
(back)
;;
;; Specify number of times to go back
;;
(back 2)"
([] (back *driver* 1))
([driver-or-n] (if (driver? driver-or-n)
(back driver-or-n 1)
(back *driver* driver-or-n)))
([driver n]
(dotimes [m n]
(core/back driver))
driver))
(defn close
"Close the browser. If multiple windows are open, this only closes the active window.
Examples:
=========
(close)"
([] (close *driver*))
([driver]
(core/close driver)))
(defn current-url
"Return the current url of the browser.
Examples:
=========
(current-url)"
([] (current-url *driver*))
([driver] (core/current-url driver)))
(defn forward
"Navigate forward in the browser history.
Examples:
=========
;;
;; Simple Example
;;
(forward)
;;
;; Specify number of times to go forward
;;
(forward 2)"
([] (forward *driver* 1))
([driver-or-n] (if (driver? driver-or-n)
(forward driver-or-n 1)
(forward *driver* driver-or-n)))
([driver n]
(dotimes [m n]
(core/forward driver))
driver))
(defn get-url
"Navigate the browser to `url`.
Examples:
=========
;;
;; Simple Example
;;
(get-url \"https://github.com\")
;;
;; Custom function for building URL's from a base url
;;
(defn go
[path]
(let [base-url \"http://example.com/\"]
(get-url (str base-url path))))
;; (go \"test-page\") would navigate to \"http://example.com/test-page\""
([url] (get-url *driver* url))
([driver url]
(core/get-url driver url)))
(defn take-screenshot
"Take a screenshot of the browser's current page, optionally specifying the format (`:file`, `:base64`, or `:bytes`) and the `destination` (something that `clojure.java.io/file` will accept).
Examples:
=========
;;
;; Simple Example
;;
;; Return screenshot as file object
;;
(take-screenshot :file)
;;
;; Specify a default destination for the file object
;;
(take-screenshot :file \"/path/to/save/screenshot.png\")"
([] (core/get-screenshot *driver* :file))
([format] (core/get-screenshot *driver* format))
([format destination] (core/get-screenshot *driver* format destination))
([driver format destination] (core/get-screenshot driver format destination)))
(defn page-source
"Return the source code of the current page in the browser.
Examples:
=========
;;
;; Simple Example
;;
(page-source)
;;
;; Do something with the HTML
;;
;; Selenium-WebDriver will instantiate a Java object for every element you query
;; or interact with, so if you have huge pages or need to do heavy-duty DOM
;; inspection or traversal, it could be more performant to do that \"offline\".
;;
(let [source (page-source)]
;; do hard-core parsing and manipulation here
)"
([] (page-source *driver*))
([driver]
(core/page-source driver)))
(defn quit
"Quit the browser completely, including all open windows.
Examples:
=========
(quit)"
([] (quit *driver*))
([driver]
(core/quit driver)))
(defn refresh
"Refresh the current page in the browser. Note that all references to elements will become \"stale\" and unusable after a page refresh.
Examples:
=========
(refresh)"
([] (refresh *driver*))
([driver]
(core/refresh driver)))
(defn title
"Return the title of the current page in the browser.
Examples:
=========
(title)"
([] (title *driver*))
([driver]
(core/title driver)))
(defn window
"Return a `Window` that contains information about the active window and can be used for switching or resizing.
Examples:
=========
(window)"
([] (window *driver*))
([driver]
(core/window driver)))
(defn windows
"Return `Window` records as a seq for all open windows.
Examples:
=========
(windows)"
([] (windows *driver*))
([driver]
(core/windows driver)))
(defn other-windows
"Return a `Window` for all open windows except the active one.
Examples:
=========
(other-windows)"
([] (other-windows *driver*))
([driver]
(core/other-windows driver)))
;; TODO: test coverage
(defn switch-to-frame
"Switch focus to the frame specified by `frame-q`, which is a standard Taxi element query or an integer for the order (zero-based index) of the frame on the page.
Examples:
=========
(switch-to-frame \"#target-frame\")
(switch-to-frame 1)"
([frame-q] (switch-to-frame *driver* frame-q))
([driver frame-q]
(let [frame (if (number? frame-q)
frame-q
(element frame-q))]
(core/switch-to-frame driver frame))))
;; TODO: accept a `Window` record or an attr-val that would get the window
(defn switch-to-window
"Switch focus to the window for the given one of the following:
* A string representing the target window name (as seen in the application titlebar)
* A number representing the index (order) of the target window
* A `Window` record
Examples:
=========
;;
;; By name
;;
(switch-to-window \"Name Of Window\")
;;
;; By index (order), open the 3rd window
;;
(switch-to-window 2)
;;
;; Passing a `Window` record directly (as returned by the `window` function)
;;
(switch-to-window a-window-record)"
([window] (switch-to-window *driver* window))
([driver window]
(core/switch-to-window driver window)))
(defn switch-to-other-window
"If two windows are open, switch focus to the other.
Examples:
=========
(switch-to-other-window)"
([] (switch-to-other-window *driver*))
([driver]
(core/switch-to-other-window driver)))
(defn switch-to-default
"Switch focus to the first first frame of the page, or the main document if the page contains iframes.
Examples:
=========
(switch-to-default)"
([] (switch-to-default *driver*))
([driver]
(core/switch-to-default driver)))
(defn switch-to-active
"Switch to the page element that currently has focus, or to the body if this cannot be detected.
Examples:
=========
(switch-to-active)"
([] (switch-to-active *driver*))
([driver]
(core/switch-to-active driver)))
(defn add-cookie
"Add a cookie to the browser session. The `cookie-spec` is a map which must contain `:name` and `:value` keys, and can also optionally include `:domain`, `:path`, `:expiry`, and `:secure?` (a boolean).
Examples:
=========
;;
;; Simple example
;;
(add-cookie {:name \"foo\", :value \"bar\"})
;;
;; Full example
;;
(add-cookie {:name \"foo\", :value \"bar\",
:domain \"example.com\", :path \"a-path\",
:expiry (java.util.Date.), :secure? false}) "
([cookie-spec] (add-cookie *driver* cookie-spec))
([driver cookie-spec]
(options/add-cookie driver cookie-spec)))
(defn delete-cookie
"Provided the name of a cookie or a Cookie record itself, delete it from the browser session.
Examples:
=========
;;
;; By name
;;
(delete-cookie \"foo\")
;;
;; With `Cookie` record as returned by `cookies` or `cookie` functions
;;
(delete-cookie a-cookie)"
([name-or-obj] (delete-cookie *driver* name-or-obj))
([driver name-or-obj]
(if (string? name-or-obj)
(options/delete-cookie-named driver name-or-obj)
(options/delete-cookie driver name-or-obj))))
(defn delete-all-cookies
"Delete all cookies from the browser session.
Examples:
=========
(delete-all-cookies)"
([] (delete-all-cookies *driver*))
([driver]
(options/delete-all-cookies driver)))
(defn cookies
"Return a seq of all cookies in the browser session. Items are `Cookie` records, which themselves contain a `:cookie` field with the original Java objects.
Examples:
=========
(cookies)"
([] (cookies *driver*))
([driver]
(options/cookies driver)))
(defn cookie
"Return the cookie with name `cookie-name`. Returns a `Cookie` record which contains a `:cookie` field with the original Java object.
Examples:
=========
(cookie \"foo\")"
([cookie-name] (cookie *driver* cookie-name))
([driver cookie-name]
(options/cookie-named driver cookie-name)))
(defn execute-script
"Execute the JavaScript code `js` with arguments `js-args` which must be passed in as a vector (for arity reasons).
Within the script, use document to refer to the current document. Note that local variables will not be available once the script has finished executing, though global variables will persist.
If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken:
* For an HTML element, this method returns a WebElement
* For a decimal, a Double is returned
* For a non-decimal number, a Long is returned
* For a boolean, a Boolean is returned
* For all other cases, a String is returned.
* For an array, return a List<Object> with each object following the rules above. We support nested lists.
* Unless the value is null or there is no return value, in which null is returned.
Arguments must be a number, a boolean, a String, WebElement, or a List of any combination of the above. An exception will be thrown if the arguments do not meet these criteria. The arguments will be made available to the JavaScript via the 'arguments' magic variable, as if the function were called via 'Function.apply'
See http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/remote/RemoteWebDriver.html#executeScript(java.lang.String, java.lang.Object...) for full details.
Examples:
=========
;;
;; Set a global variable
;;
(execute-script \"window.document.title = 'asdf'\")
;;
;; Return an element. Note that this currently returns a raw WebElement Java object.
;;
(execute-script \"var myElement = document.getElementById('elementId'); return myElement;\")"
([js] (execute-script *driver* js))
([driver-or-js js-or-args] (if (driver? driver-or-js)
(execute-script driver-or-js js-or-args [])
(execute-script *driver* driver-or-js js-or-args)))
([driver js js-args]
(apply (partial core/execute-script driver js) js-args)))
(defn wait-until
"Make the browser wait until the predicate `pred` returns true, providing an optional `timeout` in milliseconds and an optional `interval` in milliseconds on which to attempt the predicate. If the timeout is exceeded, an exception is thrown.
The predicate is a function that accepts the browser `Driver` record as its single parameter, and should return a truthy/falsey value.
Examples:
=========
;;
;; Simple example (taken from unit tests)
;;
;; Wait until the title of the page is 'asdf'
;;
(execute-script \"setTimeout(function () { window.document.title = 'asdf'}, 3000)\")
(wait-until #(= (title) \"asdf\"))
;;
;; Wait until an element exists
;;
(... code to load page ...)
(wait-until #(exists? \"#foo\"))
(click \"#foo a.bar\")"
([pred] (wait/wait-until *driver* (fn [_] pred)))
([pred timeout] (wait/wait-until *driver* (fn [_] pred) timeout))
([pred timeout interval] (wait/wait-until *driver* (fn [_] pred) timeout interval))
([driver pred timeout interval] (wait/wait-until driver pred timeout interval)))
(defn implicit-wait
"Set the global `timeout` that the browser should wait when attempting to find elements on the page, before timing out with an exception.
Examples:
=========
;;
;; Simple example (taken from unit tests)
;;
;; Set implicit timeout (global) to 3 seconds, then execute JavaScript with a
;; noticeable delay to prove that it works
;;
(implicit-wait 3000)
(execute-script \"setTimeout(function () { window.document.body.innerHTML = '<div id='test'>hi!</div>'}, 1000)\")"
([timeout] (implicit-wait *driver* timeout))
([driver timeout]
(wait/implicit-wait driver timeout)))
(defn find-windows
"Return all `Window` records that match the given `attr-val` map.
Attributes can be anything in a `Window` record (`:title` or `:url`) or you can pass an `:index` key and a number value to select a window by its open order.
Examples:
=========
;;
;; By name
;;
(find-windows {:title \"Window Title\"})
;;
;; By URL
;;
(find-windows {:url \"http://example.com/test-page\"})
;;
;; By index
;;
(find-windows {:index 2})"
([attr-val] (find-windows *driver* attr-val))
([driver attr-val]
(core/find-windows driver attr-val)))
(defn find-window
"Return the first `Window` record that matches the given `attr-val` map.
Attributes can be anything in a `Window` record (`:title` or `:url`) or you can pass an `:index` key and a number value to select a window by its open order.
Examples:
=========
;;
;; By name
;;
(find-window {:title \"Window Title\"})
;;
;; By URL
;;
(find-window {:url \"http://example.com/test-page\"})
;;
;; By index
;;
(find-window {:index 2})"
([attr-val] (find-window *driver* attr-val))
([driver attr-val] (core/find-window driver attr-val)))
(defn find-table-cell
"Within the table found with query `table-q`, return the table cell at coordinates `coords`. The top-left cell has coordinates `[0 0]`.
Examples:
=========
;;
;; Simple example, find 2nd cell on 2nd row from top
;;
(find-table-cell \"table#my-table\" [1 1])"
([table-q coords] (find-table-cell *driver* table-q coords))
([driver table-q coords]
(core/find-table-cell driver (element driver table-q) coords)))
(defn find-table-row
"Within the table found with query `table-q`, return a seq of all cells at row number `row`. The top-most row is row `0` (zero-based index).
Examples:
=========
;;
;; Simple example, return cells in second row
;;
(find-table-row \"table#my-table\" 1)"
([table-q row] (find-table-row *driver* table-q row))
([driver table-q row]
(core/find-table-row driver (element driver table-q) row)))
;; Need to explain difference between element and find-element fn's
(defn find-elements
"Return `Element` records that match the given `attr-val`. Prefer the default behavior of `elements` when possible.
Whereas the `elements` function uses a query `q` with the default finder function, this function requires an `attr-val` parameter which is either a map or a vector of maps with special semantics for finding elements on the page.
The `attr-val` map can consist of one or more of the following:
* The key `:css` or `:xpath` and a query value (e.g., `{:css \"a.external\"}`)
* The key `:tag` and an HTML tag (e.g., `{:tag :a}`)
* An HTML element attribute and its value (e.g., `{:class \"external\"}`)
* A 'meta' tag `:button*`, `:radio`, `:checkbox`, `:textfield`, `:password`, `:filefield` (e.g., `{:tag :button*}`)
* The key `:index` and the zero-based index (order) of the target element on the page (e.g., `{:index 2}` retrieves the third element that matches)
* A vector of attr-val maps like the above, representing a hierarchical query (auto-generates XPath)
Examples:
=========
;;
;; Medley of possibilities
;;
(find-elements {:css \"a.foo\"})
(find-elements {:xpath \"//a[@class='foo']\"})
(find-elements {:tag :a, :text \"Login\"})
(find-elements {:tag :a, :index 4}) ;; 5th anchor tag
(find-elements {:tag :button*, :class \"foo\"})
(find-elements {:tag :radio, :class \"choice\"})
(find-elements [{:tag :div, :id \"container\"},
{:tag :a, :class \"external\"}])
"
([attr-val] (find-elements *driver* attr-val))
([driver attr-val]
(core/find-elements driver attr-val)))
(defn find-element
"Return first `Element` record that matches the given `attr-val`. Prefer the default behavior of `element` when possible.
Whereas the `element` function uses a query `q` with the default finder function, this function requires an `attr-val` parameter which is either a map or a vector of maps with special semantics for finding elements on the page.
The `attr-val` map can consist of one or more of the following:
* The key `:css` or `:xpath` and a query value (e.g., `{:css \"a.external\"}`)
* The key `:tag` and an HTML tag (e.g., `{:tag :a}`)
* An HTML element attribute and its value (e.g., `{:class \"external\"}`)
* A 'meta' tag `:button*`, `:radio`, `:checkbox`, `:textfield`, `:password`, `:filefield` (e.g., `{:tag :button*}`)
* The key `:index` and the zero-based index (order) of the target element on the page (e.g., `{:index 2}` retrieves the third element that matches)
* A vector of attr-val maps like the above, representing a hierarchical query (auto-generates XPath)
Examples:
=========
;;
;; Medley of possibilities
;;
(find-element {:css \"a.foo\"})
(find-element {:xpath \"//a[@class='foo']\"})
(find-element {:tag :a, :text \"Login\"})
(find-element {:tag :a, :index 4}) ;; 5th anchor tag
(find-element {:tag :button*, :class \"foo\"})
(find-element {:tag :radio, :class \"choice\"})
(find-element [{:tag :div, :id \"container\"},
{:tag :a, :class \"external\"}])
"
([attr-val] (find-element *driver* attr-val))
([driver attr-val]
(core/find-element driver attr-val)))
;; Element versions of find-element-by and find-elements-by
(defn find-elements-under
"Find the elements that are children of the element found with query `q-parent`, using the given `attr-val`. If `q-parent` is an `Element`, it will be used as-is. The `attr-val` can either be a find-element-style map of attributes and values, or a by-clause (`by-tag`, `by-class`, etc.)
Examples:
=========
;;
;; Example using a map
;;
(find-elements-under \"div#container\" {:tag :a, :id \"foo\"})
;;
;; Example using by-clause, find an element with id \"foo\" within a div with id \"container\"
;;
(find-elements-under \"div#container\" (core/by-id \"foo\")"
([q-parent attr-val] (find-elements-under *driver* q-parent attr-val))
([driver q-parent attr-val]
(if (element-like? q-parent)
(core/find-elements q-parent attr-val)
(core/find-elements (element driver q-parent) attr-val))))
(defn find-element-under
"Find the first element that is a child of the element found with query `q-parent`, using the given `attr-val`. If `q-parent` is an `Element`, it will be used as-is. The `attr-val` can either be a find-element-style map of attributes and values, or a by-clause (`by-tag`, `by-class`, etc.)
Examples:
=========
;;
;; Example using map, which generates a (by-xpath ...) form
;;
(find-element-under \"div#container\" {:tag :a, :id \"foo\"})
;;
;; Example using by-clause, find an element with id \"foo\" within a div with id \"container\"
;;
(find-element-under \"div#container\" (core/by-id \"foo\")"
([q-parent attr-val] (find-element-under *driver* q-parent attr-val))
([driver q-parent attr-val]
(if (element-like? q-parent)
(core/find-element q-parent attr-val)
(core/find-element (element driver q-parent) attr-val))))
;; ## Element functions ##
;;
;; Unlike their counterparts in core, you don't need to do a `(find-element ...)`
;; with these; just pass in a CSS query followed by other necessary parameters
;; and the first element that matches the query will be used automatically.
;;
;; If a CSS query string is not passed in, it's assumed you're trying to use these
;; functions like their core counterparts, in which case each function will default
;; back to core functionality (expecting that you're passing in an Element record)
(defn attribute
"For the first element found with query `q`, return the value of the given `attribute`.
Examples:
=========
;;
;; Example medley for an anchor tag with id \"foo\", class \"bar\", and target \"_blank\"
;;
(attribute \"a#foo\" :id) ;=> \"foo\"
(attribute \"a#foo\" :class) ;=> \"bar\"
(attribute \"a#foo\" :target) ;=> \"_blank\""
([q attr] (attribute *driver* q attr))
([driver q attr]
(core/attribute (element driver q) attr)))
(defn click
"Click the first element found with query `q`.
Examples:
=========
(click \"a#foo\")"
([q] (click *driver* q))
([driver q]
(core/click (element driver q))))
(defn displayed?
"Return true if the first element found with query `q` is visible on the page.
Examples:
=========
(displayed? \"div#container\") ;=> true
(displayed? \"a.hidden\") ;=> false"
([q] (displayed? *driver* q))
([driver q]
(core/displayed? (element driver q))))
(defn drag-and-drop
"Drag the first element found with query `qa` onto the first element found with query `qb`.
Examples:
=========
;;
;; Drag div with id \"draggable\" onto div with id \"droppable\"
;;
(drag-and-drop \"#draggable\" \"#droppable\")"
([qa qb] (drag-and-drop *driver* qa qb))
([driver qa qb]
(core/drag-and-drop driver (element driver qa) (element driver qb))))
(defn drag-and-drop-by
"Drag the first element found with query `q` by `:x` pixels to the right and `:y` pixels down, passed in as a map like `{:x 10, :y 10}`. Values default to zero if excluded. Use negative numbers for `:x` and `:y` to move left or up respectively.
Examples:
=========
;;
;; Drag a div with id \"draggable\" 20 pixels to the right
;;
(drag-and-drop-by \"#draggable\" {:x 20})
;;
;; Drag a div with id \"draggable\" 10 pixels down
;;
(drag-and-drop-by \"#draggable\" {:y 10})
;;
;; Drag a div with id \"draggable\" 15 pixels to the left and 5 pixels up
;;
(drag-and-drop-by \"#draggable\" {:x -15, :y -5})"
([q x-y-map] (drag-and-drop-by *driver* q x-y-map))
([driver q x-y-map]
(core/drag-and-drop-by driver (element driver q) x-y-map)))
(defn exists?
"Return true if the first element found with query `q` exists on the current page in the browser.
Examples:
=========
(exists? \"a#foo\") ;=> true
(exists? \"footer\") ;=> false"
([q] (exists? *driver* q))
([driver q]
(core/exists? (element driver q))))
(defn flash
"Flash the background color of the first element found with query `q`.
Examples:
=========
(flash \"a.hard-to-see\")"
([q] (flash *driver* q))
([driver q]
(core/flash (element driver q))))
(defn focus
"Explicitly give the first element found with query `q` focus on the page.
Examples:
=========
(focus \"input.next-element\")"
([q] (focus *driver* q))
([driver q]
(core/focus (element driver q))))
(defn html
"Return the inner html of the first element found with query `q`.
Examples:
=========
(html \"div.with-interesting-html\")"
([q] (html *driver* q))
([driver q]
(core/html (element driver q))))
(defn location
"Return a map of `:x` and `:y` coordinates for the first element found with query `q`.
Examples:
=========
(location \"a#foo\") ;=> {:x 240, :y 300}"
([q] (location *driver* q))
([driver q]
(core/location (element driver q))))
(defn location-once-visible
"Return a map of `:x` and `:y` coordinates for the first element found with query `q` once the page has been scrolled enough to be visible in the viewport.
Examples:
=========
(location-once-visible \"a#foo\") ;=> {:x 240, :y 300}"
([q] (location-once-visible *driver* q))
([driver q]
(core/location-once-visible (element driver q))))
(defn present?
"Return true if the first element found with query `q` both exists and is visible on the page.
Examples:
=========
(present? \"div#container\") ;=> true
(present? \"a#skip-to-navigation\") ;=> false"
([q] (present? *driver* q))
([driver q]
(core/present? (element driver q))))
(defn element-size
"Return the size of the first element found with query `q` in pixels as a map of `:width` and `:height`.
Examples:
=========
(size \"div#container\") ;=> {:width 960, :height 2000} "
([q] (element-size *driver* q))
([driver q]
(core/size (element driver q))))
(defn intersects?
"Return true if the first element found with query `qa` intersects with the first element found with query `qb`.
Examples:
=========
(intersect? \"#login\" \"#login_field\") ;=> true
(intersect? \"#login_field\" \"#password\") ;=> false"
([qa qb] (intersects? *driver* qa qb))
([driver qa qb]
(core/intersects? (element driver qa) (element driver qb))))
(defn tag
"Return the HTML tag for the first element found with query `q`.
Examples:
=========
(tag \"#foo\") ;=> \"a\""
([q] (tag *driver* q))
([driver q]
(core/tag (element driver q))))
(defn text
"Return the text within the first element found with query `q`.
Examples:
=========
(text \"#message\") ;=> \"An error occurred.\""
([q] (text *driver* q))
([driver q]
(core/text (element driver q))))
(defn value
"Return the value of the HTML value attribute for the first element found with query `q`. The is identical to `(attribute q :value)`
Examples:
=========
(value \"#my-button\") ;=> \"submit\" "
([q] (value *driver* q))
([driver q]
(core/value (element driver q))))
(defn visible?
"Return true if the first element found with query `q` is visible on the current page in the browser.
Examples:
=========
(visible? \"div#container\") ;=> true
(visible? \"a.hidden\") ;=> false"
([q] (visible? *driver* q))
([driver q]
(core/visible? (element driver q))))
(defn xpath
"Return an absolute XPath path for the first element found with query `q`. NOTE: This function relies on executing JavaScript in the browser, and is therefore not as dependable as other functions.
Examples:
=========
(xpath \"#login_field\") ;=> \"/html/body/div[2]/div/div/form/div[2]/label/input\""
([q] (xpath *driver* q))
([driver q]
(core/xpath (element driver q))))
(defn deselect
"If the first form element found with query `q` is selected, click the element to deselect it. Otherwise, do nothing and just return the element found.
Examples:
=========
(deselect \"input.already-selected\") ;=> click
(deselect \"input.not-selected\") ;=> do nothing"
([q] (deselect *driver* q))
([driver q]
(core/deselect (element driver q))))
(defn enabled?
"Return true if the first form element found with query `q` is enabled (not disabled).
Examples:
=========
(enabled? \"input\") ;=> true
(enabled? \"input[disabled='disabled']\") ;=> false"
([q] (enabled? *driver* q))
([driver q] (core/enabled? (element driver q))))
(defn input-text
"Type the string `s` into the first form element found with query `q`.
Examples:
=========
(input-text \"input#login_field\" \"semperos\")"
([q s] (input-text *driver* q s))
([driver q s]
(core/input-text (element driver q) s)))
(defn submit
"Submit the form that the first form element found with query `q` belongs to (this is equivalent to pressing ENTER in a text field while filling out a form).
Examples:
=========
(submit \"input#password\")"
([q] (submit *driver* q))
([driver q]
(core/submit (element driver q))))
(defn clear
"Clear the contents (the HTML value attribute) of the first form element found with query `q`.
Examples:
=========
(clear \"input.with-default-text\")"
([q] (clear *driver* q))
([driver q]
(core/clear (element driver q))))
(defn select
"If the first form element found with query `q` is not selected, click the element to select it. Otherwise, do nothing and just return the element found.
Examples:
=========
(select \"input.already-selected\") ;=> do nothing
(select \"input.not-selected\") ;=> click"
([q] (select *driver* q))
([driver q]
(core/select (element driver q))))
(defn selected?
"Return true if the first element found with the query `q` is selected (works for radio buttons, checkboxes, and option tags within select lists).
Examples:
=========
(selected? \"input[type='radio'][value='foo']\") ;=> true
(selected? \"option[value='foo']\") ;=> false "
([q] (selected? *driver* q))
([driver q] (core/selected? (element driver q))))
(defn send-keys
"Type the string `s` into the first form element found with query `q`.
Examples:
=========
(input-text \"input#login_field\" \"semperos\")"
([q s] (send-keys *driver* q s))
([driver q s]
(core/send-keys (element driver q) s)))
(defn toggle
"Toggle is a synonym for click. Click the first element found with query `q`.
Examples:
=========
(toggle \"input[type='checkbox'][value='foo']\")"
([q] (toggle *driver* q))
([driver q]
(core/toggle (element driver q))))
(defn options
"Return all option elements within the first select list found with query `q`.
Examples:
=========
(options \"#my-select-list\")"
([q] (options *driver* q))
([driver q]
(core/all-options (element driver q))))
(defn selected-options
"Return all selected option elements within the first select list found with query `q`.
Examples:
=========
(selected-options \"#my-select-list\")"
([q] (selected-options *driver* q))
([driver q]
(core/all-selected-options (element driver q))))
(defn deselect-option
"Deselect the option element matching `attr-val` within the first select list found with query `q`.
The `attr-val` can contain `:index`, `:value`, or `:text` keys to find the target option element. Index is the zero-based order of the option element in the list, value is the value of the HTML value attribute, and text is the visible text of the option element on the page.
Examples:
=========
;;
;; By index, select 3rd option element
;;
(deselect-option \"#my-select-list\" {:index 2})
;;
;; By value of option element
;;
(deselect-option \"#my-select-list\" {:value \"foo\"})
;;
;; By visible text of option element
;;
(deselect-option \"#my-select-list\" {:value \"Foo\"})"
([q attr-val] (deselect-option *driver* q attr-val))
([driver q attr-val]
(core/deselect-option (element driver q) attr-val)))
(defn deselect-all
"Deselect all options within the first select list found with query `q`.
Examples:
=========
(deselect-all \"#my-select-list\")"
([q] (deselect-all *driver* q))
([driver q] (core/deselect-all (element driver q))))
(defn deselect-by-index
"Deselect the option element at index `idx` (zero-based) within the first select list found with query `q`.
Examples:
=========
;;
;; Deselect by index, deselect 2nd element
;;
(deselect-by-index \"#my-select-list\" 1)"
([q idx] (deselect-by-index *driver* q idx))
([driver q idx] (core/deselect-by-index (element driver q) idx)))
(defn deselect-by-text
"Deselect the option element with visible text `text` within the first select list found with query `q`.
Examples:
=========
(deselect-by-text \"#my-select-list\" \"Foo\")"
([q text] (deselect-by-text *driver* q text))
([driver q text]
(core/deselect-by-text (element driver q) text)))
(defn deselect-by-value
"Deselect the option element with `value` within the first select list found with query `q`.
Examples:
=========
(deselect-by-value \"#my-select-list\" \"foo\")"
([q value] (deselect-by-value *driver* q value))
([driver q value]
(core/deselect-by-value (element driver q) value)))
(defn multiple?
"Return true if the first select list found with query `q` allows multiple selections.
Examples:
=========
(multiple? \"select.multiple\") ;=> true
(multiple? \"select.not-multiple\") ;=> false "
([q] (multiple? *driver* q))
([driver q] (core/multiple? (element driver q))))
(defn select-option
"Select the option element matching `attr-val` within the first select list found with query `q`.
The `attr-val` can contain `:index`, `:value`, or `:text` keys to find the target option element. Index is the zero-based order of the option element in the list, value is the value of the HTML value attribute, and text is the visible text of the option element on the page.
Examples:
=========
;;
;; By index, select 3rd option element
;;
(select-option \"#my-select-list\" {:index 2})
;;
;; By value of option element
;;
(select-option \"#my-select-list\" {:value \"foo\"})
;;
;; By visible text of option element
;;
(select-option \"#my-select-list\" {:value \"Foo\"})"
([q attr-val] (select-option *driver* q attr-val))
([driver q attr-val]
(core/select-option (element driver q) attr-val)))
(defn select-all
"Select all options within the first select list found with query `q`.
Examples:
=========
(deselect-all \"#my-select-list\")"
([q] (select-all *driver* q))
([driver q]
(core/select-all (element driver q))))
(defn select-by-index
"Select the option element at index `idx` (zero-based) within the first select list found with query `q`.
Examples:
=========
;;
;; Select by index, select 2nd element
;;
(select-by-index \"#my-select-list\" 1)"
([q idx] (select-by-index *driver* q idx))
([driver q idx]
(core/select-by-index (element driver q) idx)))
(defn select-by-text
"Select the option element with visible text `text` within the first select list found with query `q`.
Examples:
=========
(select-by-text \"#my-select-list\" \"foo\")"
([q text] (select-by-text *driver* q text))
([driver q text]
(core/select-by-text (element driver q) text)))
(defn select-by-value
"Select the option element with `value` within the first select list found with query `q`.
Examples:
=========
(select-by-value \"#my-select-list\" \"foo\")"
([q value] (select-by-value *driver* q value))
([driver q value]
(core/select-by-value (element driver q) value)))
;; Helpers
(defn- quick-fill*
([k v] (quick-fill* k v false))
([k v submit?]
;; shortcuts:
;; v as string => text to input
(let [q k
action (if (string? v)
#(input-text % v)
v)
target-els (elements q)]
(if submit?
(doseq [el target-els]
(action el))
(map action target-els)))))
(defn quick-fill
"A utility for filling out multiple fields in a form in one go. Returns all the affected elements (if you want a list of unique elements, pass the results through the `distinct` function in clojure.core).
`query-action-maps` - a seq of maps of queries to actions (queries find HTML elements, actions are fn's that act on them)
Note that an \"action\" that is just a String will be interpreted as a call to `input-text` with that String for the target text field.
Examples:
=========
(quick-fill {\"#first_name\" \"Rich\"}
{\"a.foo\" click})"
[& query-action-maps]
(flatten (map (fn [a-map]
(let [[k v] (first a-map)] (quick-fill* k v)))
query-action-maps)))
(defn quick-fill-submit
"A utility for filling out multiple fields in a form in one go. Always returns nil instead of the affected elements, since on submit all of the elements will be void.
`query-action-maps` - a seq of maps of queries to actions (queries find HTML elements, actions are fn's that act on them)
Note that an \"action\" that is just a String will be interpreted as a call to `input-text` with that String for the target text field.
Examples:
=========
(quick-fill {\"#first_name\" \"Rich\"}
{\"a.foo\" click})"
[& query-action-maps]
(doseq [entry query-action-maps
[k v] entry]
(quick-fill* k v true)))
(defn accept
"Accept an alert popup dialog. Equivalent to pressing its 'Ok' button."
([] (accept *driver*))
([driver] (core/accept driver)))
(defn alert-obj
"Retrieve the underlying Java object used to identify an alert popup dialog. Exposed to allow you to use methods not yet exposed via clj-webdriver's API's."
([] (alert-obj *driver*))
([driver] (core/alert-obj driver)))
(defn alert-text
"Get the text of the alert popup dialog's message."
([] (alert-text *driver*))
([driver] (core/alert-text driver)))
(defn dismiss
"Dismiss the alert popup dialog. Equivalent to pressing its 'Cancel' button."
([] (dismiss *driver*))
([driver] (core/dismiss driver)))
(defn window-position
"Get the position of the top-left corner of the browser's window relative to the top-left corner of your primary display, returned as a map of `:x` and `:y` integers.
Examples:
=========
(window-position)"
([] (window-position *driver*))
([driver] (win/position driver)))
(defn window-reposition
"Move the top-left corner of the browser `:x` pixels to the right and `:y` pixels down from the top-left of your primary display. If you do not provide a coordinate, it's current value for the browser position will not be changed.
Examples:
=========
(window-reposition {:x 25, :y 50})
(window-reposition {:y 50})"
([coordinates-map] (window-reposition *driver* coordinates-map))
([driver {:keys [x y] :as coordinates-map}]
(win/reposition driver coordinates-map)))
(defn window-size
"Get the size of the browser's window in pixels, returned as a map of `:width` and `:height`.
Examples:
=========
(window-size)"
([] (window-size *driver*))
([driver] (win/size driver)))
(defn window-resize
"Resize the browser window to the given `:width` and `:height`. If a dimension is not specified, it's current value for the browser size will not be changed.
Examples:
=========
(window-resize {:width 300 :height 400})
(window-resize {:height 400})"
([dimensions-map] (window-resize *driver* dimensions-map))
([driver {:keys [width height] :as dimensions-map}]
(win/resize driver dimensions-map)))
(defn window-maximize
"Maximize the browser window.
Examples:
=========
(window-maximize)"
([] (window-maximize *driver*))
([driver] (win/maximize driver)))
| 22393 | ;; The faster way to use clj-webdriver: take a taxi
(ns clj-webdriver.taxi
(:use [clj-webdriver.driver :only [driver?]]
[clj-webdriver.element :only [element-like?]])
(:require [clj-webdriver.core :as core]
[clj-webdriver.options :as options]
[clj-webdriver.util :as util]
[clj-webdriver.wait :as wait]
[clj-webdriver.window :as win])
(:import clj_webdriver.element.Element))
(declare css-finder)
(def ^:dynamic *driver*)
(def ^:dynamic *finder-fn* css-finder)
(def ^{:doc (str "Alias of clj-webdriver.core/new-driver:\n"
(:doc (meta #'clj-webdriver.core/new-driver)))
:arglists (:arglists (meta #'clj-webdriver.core/new-driver))}
new-driver clj-webdriver.core/new-driver)
(defn- set-driver*
"Given a `browser-spec`, instantiate a new Driver record and assign to `*driver*`."
[browser-spec]
(let [new-driver (if (driver? browser-spec)
browser-spec
(core/new-driver browser-spec))]
(alter-var-root (var *driver*)
(constantly new-driver)
(when (thread-bound? (var *driver*))
(set! *driver* new-driver)))))
(declare to)
(defn set-driver!
"Set a default `Driver` for this thread, optionally sending it to a starting `url`.
Available browsers are `:firefox`, `:chrome`, `:ie`, `:opera`, `:phantomjs` and `:htmlunit`.
Examples:
=========
;;
;; Simple example
;;
(set-driver! {:browser :firefox})
;;
;; Full example
;;
(set-driver! {:browser :firefox
:cache-spec {:strategy :basic,
:args [{}],
:include [ (fn [element] (= (attribute element :class) \"external\"))
{:css \"ol#pages\"}]}
;;
;; Use existing Driver record
;;
(set-driver! a-driver)"
([browser-spec] (set-driver* browser-spec))
([browser-spec url] (to (set-driver* browser-spec) url)))
(defn set-finder!
"Set a default finder function, which will be used with all `q` parameters in functions that require an Element.
Examples:
=========
;;
;; Simple example
;;
(set-finder! xpath-finder)
;;
;; Derivative finder function
;;
;; Takes the query string and always prepends \"div#container \", which would be
;; useful in situations where you know you're always inside that particular div.
;; (Note that this same functionality is provided by `find-element-under`, but
;; you get the idea.)
;;
(set-finder! (fn [q]
(if (element-like? q)
q
(css-finder (str \"div#container \" q)))))
;;
;; Custom finder function
;;
;; If you want to easily switch between using CSS and XPath (e.g., because
;; XPath has the text() function for which no CSS equivalent exists), then
;; you could write something like this, where `q` would become either the map
;; {:css \"query\"} or {:xpath \"query\"} instead of just a string.
;;
(set-finder! (fn [q]
(if (element-like? q)
q
(case (first (keys q))
:css (core/find-elements-by *driver* (by-css (first (values q))))
:xpath (core/find-elements-by *driver* (by-xpath (first (values q))))))))
;;
;; (Note: This last example is written to show how to use the lowest-level functions
;; `find-elements-by`, `by-css` and `by-xpath`. The maps `{:css \"query\"}` and
;; `{:xpath \"query\"}` are themselves acceptable arguments to the `find-elements`,
;; function, so that function could have been used instead without the `case` statement.)
;;"
[finder-fn]
(alter-var-root (var *finder-fn*)
(constantly finder-fn)
(when (thread-bound? (var *finder-fn*))
(set! *finder-fn* finder-fn))))
(declare quit)
(defmacro with-driver
"Given a `browser-spec` to start a browser, execute the forms in `body`, then call `quit` on the browser. Uses the default finder function.
Examples:
=========
;;
;; Log into Github
;;
(with-driver {:browser :firefox}
(to \"https://github.com\")
(click \"a[href*='login']\")
(input-text \"#login_field\" \"your_username\")
(-> \"#password\"
(input-text \"your_password\")
submit))"
[browser-spec & body]
`(binding [*driver* (core/new-driver ~browser-spec)]
(try
~@body
(finally
(quit)))))
(defmacro with-driver-fn
"Given a `browser-spec` to start a browser and a `finder-fn` to use as a finding function, execute the forms in `body`, then call `quit` on the browser.
Examples:
=========
;;
;; Log into Github
;;
(with-driver {:browser :firefox} xpath-finder
(to \"https://github.com\")
(click \"//a[text()='Login']\")
(input-text \"//input[@id='login_field']\" \"your_username\")
(-> \"//input[@id='password']\"
(input-text \"your_password\")
submit))"
[browser-spec finder-fn & body]
`(binding [*driver* (core/new-driver ~browser-spec)
*finder-fn* ~finder-fn]
(try
~@body
(finally
(quit)))))
(defn css-finder
"Given a CSS query `q`, return a lazy seq of the elements found by calling `find-elements` with `by-css`. If `q` is an `Element`, it is returned unchanged.
This function is used internally by the Taxi API as `*finder*`. See the documentation for `set-finder!` for examples of extending this function or creating your own custom finder function."
([q] (css-finder *driver* q))
([driver q]
(cond
(element-like? q) q
(map? q) (core/find-elements driver q)
:else (core/find-elements driver {:css q}))))
(set-finder! css-finder)
(defn xpath-finder
"Given a XPath query `q`, return a lazy seq of the elements found by calling `find-elements` with `by-xpath`. If `q` is an `Element`, it is returned unchanged.
This function is used internally by the Taxi API as `*finder*`. See the documentation for `set-finder!` for examples of extending this function or creating your own custom finder function."
([q] (xpath-finder *driver* q))
([driver q]
(cond
(element-like? q) q
(map? q) (core/find-elements driver q)
:else (core/find-elements driver {:xpath q}))))
;; Be able to get actual element/elements when needed
(defn element
"Given a query `q`, return the first element that the default finder function returns.
Examples:
=========
;;
;; Simple Example
;;
;; Create a var that points to an element for later use.
;;
(def login-link (element \"a[href*='login']\"))
;;
;; More useful example: composing actions on an element
;;
;; When threading actions together, it's more performant to thread an actual element,
;; than to thread simply the query string. Threading the query string makes clj-webdriver
;; locate the same element multiple times, while threading an actual element only
;; requires one lookup.
;;
(-> (element \"input#password\")
(input-text \"my-password\")
submit)"
([q] (element *driver* q))
([driver q]
(if (element-like? q)
q
(first (*finder-fn* driver q)))))
(defn elements
"Given a query `q`, return the elements that the default finder function returns.
Examples:
=========
;;
;; Simple Example
;;
;; Save a seq of anchor tags (links) for later.
;;
(def target-elements (elements \"a\"))"
([q] (elements *driver* q))
([driver q]
(if (element-like? q)
(lazy-seq (list q))
(*finder-fn* driver q))))
;; ## Driver functions ##
(defn to
"Navigate the browser to `url`.
Examples:
=========
;;
;; Simple Example
;;
(to \"https://github.com\")
;;
;; Custom function for building URL's from a base url
;;
(defn go
[path]
(let [base-url \"http://example.com/\"]
(to (str base-url path))))
;; (go \"test-page\") would navigate to \"http://example.com/test-page\""
([url]
(to *driver* url))
([driver url]
(core/to driver url)))
(defn back
"Navigate back in the browser history, optionally `n` times.
Examples:
=========
;;
;; Simple Example
;;
(back)
;;
;; Specify number of times to go back
;;
(back 2)"
([] (back *driver* 1))
([driver-or-n] (if (driver? driver-or-n)
(back driver-or-n 1)
(back *driver* driver-or-n)))
([driver n]
(dotimes [m n]
(core/back driver))
driver))
(defn close
"Close the browser. If multiple windows are open, this only closes the active window.
Examples:
=========
(close)"
([] (close *driver*))
([driver]
(core/close driver)))
(defn current-url
"Return the current url of the browser.
Examples:
=========
(current-url)"
([] (current-url *driver*))
([driver] (core/current-url driver)))
(defn forward
"Navigate forward in the browser history.
Examples:
=========
;;
;; Simple Example
;;
(forward)
;;
;; Specify number of times to go forward
;;
(forward 2)"
([] (forward *driver* 1))
([driver-or-n] (if (driver? driver-or-n)
(forward driver-or-n 1)
(forward *driver* driver-or-n)))
([driver n]
(dotimes [m n]
(core/forward driver))
driver))
(defn get-url
"Navigate the browser to `url`.
Examples:
=========
;;
;; Simple Example
;;
(get-url \"https://github.com\")
;;
;; Custom function for building URL's from a base url
;;
(defn go
[path]
(let [base-url \"http://example.com/\"]
(get-url (str base-url path))))
;; (go \"test-page\") would navigate to \"http://example.com/test-page\""
([url] (get-url *driver* url))
([driver url]
(core/get-url driver url)))
(defn take-screenshot
"Take a screenshot of the browser's current page, optionally specifying the format (`:file`, `:base64`, or `:bytes`) and the `destination` (something that `clojure.java.io/file` will accept).
Examples:
=========
;;
;; Simple Example
;;
;; Return screenshot as file object
;;
(take-screenshot :file)
;;
;; Specify a default destination for the file object
;;
(take-screenshot :file \"/path/to/save/screenshot.png\")"
([] (core/get-screenshot *driver* :file))
([format] (core/get-screenshot *driver* format))
([format destination] (core/get-screenshot *driver* format destination))
([driver format destination] (core/get-screenshot driver format destination)))
(defn page-source
"Return the source code of the current page in the browser.
Examples:
=========
;;
;; Simple Example
;;
(page-source)
;;
;; Do something with the HTML
;;
;; Selenium-WebDriver will instantiate a Java object for every element you query
;; or interact with, so if you have huge pages or need to do heavy-duty DOM
;; inspection or traversal, it could be more performant to do that \"offline\".
;;
(let [source (page-source)]
;; do hard-core parsing and manipulation here
)"
([] (page-source *driver*))
([driver]
(core/page-source driver)))
(defn quit
"Quit the browser completely, including all open windows.
Examples:
=========
(quit)"
([] (quit *driver*))
([driver]
(core/quit driver)))
(defn refresh
"Refresh the current page in the browser. Note that all references to elements will become \"stale\" and unusable after a page refresh.
Examples:
=========
(refresh)"
([] (refresh *driver*))
([driver]
(core/refresh driver)))
(defn title
"Return the title of the current page in the browser.
Examples:
=========
(title)"
([] (title *driver*))
([driver]
(core/title driver)))
(defn window
"Return a `Window` that contains information about the active window and can be used for switching or resizing.
Examples:
=========
(window)"
([] (window *driver*))
([driver]
(core/window driver)))
(defn windows
"Return `Window` records as a seq for all open windows.
Examples:
=========
(windows)"
([] (windows *driver*))
([driver]
(core/windows driver)))
(defn other-windows
"Return a `Window` for all open windows except the active one.
Examples:
=========
(other-windows)"
([] (other-windows *driver*))
([driver]
(core/other-windows driver)))
;; TODO: test coverage
(defn switch-to-frame
"Switch focus to the frame specified by `frame-q`, which is a standard Taxi element query or an integer for the order (zero-based index) of the frame on the page.
Examples:
=========
(switch-to-frame \"#target-frame\")
(switch-to-frame 1)"
([frame-q] (switch-to-frame *driver* frame-q))
([driver frame-q]
(let [frame (if (number? frame-q)
frame-q
(element frame-q))]
(core/switch-to-frame driver frame))))
;; TODO: accept a `Window` record or an attr-val that would get the window
(defn switch-to-window
"Switch focus to the window for the given one of the following:
* A string representing the target window name (as seen in the application titlebar)
* A number representing the index (order) of the target window
* A `Window` record
Examples:
=========
;;
;; By name
;;
(switch-to-window \"Name Of Window\")
;;
;; By index (order), open the 3rd window
;;
(switch-to-window 2)
;;
;; Passing a `Window` record directly (as returned by the `window` function)
;;
(switch-to-window a-window-record)"
([window] (switch-to-window *driver* window))
([driver window]
(core/switch-to-window driver window)))
(defn switch-to-other-window
"If two windows are open, switch focus to the other.
Examples:
=========
(switch-to-other-window)"
([] (switch-to-other-window *driver*))
([driver]
(core/switch-to-other-window driver)))
(defn switch-to-default
"Switch focus to the first first frame of the page, or the main document if the page contains iframes.
Examples:
=========
(switch-to-default)"
([] (switch-to-default *driver*))
([driver]
(core/switch-to-default driver)))
(defn switch-to-active
"Switch to the page element that currently has focus, or to the body if this cannot be detected.
Examples:
=========
(switch-to-active)"
([] (switch-to-active *driver*))
([driver]
(core/switch-to-active driver)))
(defn add-cookie
"Add a cookie to the browser session. The `cookie-spec` is a map which must contain `:name` and `:value` keys, and can also optionally include `:domain`, `:path`, `:expiry`, and `:secure?` (a boolean).
Examples:
=========
;;
;; Simple example
;;
(add-cookie {:name \"foo\", :value \"bar\"})
;;
;; Full example
;;
(add-cookie {:name \"foo\", :value \"bar\",
:domain \"example.com\", :path \"a-path\",
:expiry (java.util.Date.), :secure? false}) "
([cookie-spec] (add-cookie *driver* cookie-spec))
([driver cookie-spec]
(options/add-cookie driver cookie-spec)))
(defn delete-cookie
"Provided the name of a cookie or a Cookie record itself, delete it from the browser session.
Examples:
=========
;;
;; By name
;;
(delete-cookie \"foo\")
;;
;; With `Cookie` record as returned by `cookies` or `cookie` functions
;;
(delete-cookie a-cookie)"
([name-or-obj] (delete-cookie *driver* name-or-obj))
([driver name-or-obj]
(if (string? name-or-obj)
(options/delete-cookie-named driver name-or-obj)
(options/delete-cookie driver name-or-obj))))
(defn delete-all-cookies
"Delete all cookies from the browser session.
Examples:
=========
(delete-all-cookies)"
([] (delete-all-cookies *driver*))
([driver]
(options/delete-all-cookies driver)))
(defn cookies
"Return a seq of all cookies in the browser session. Items are `Cookie` records, which themselves contain a `:cookie` field with the original Java objects.
Examples:
=========
(cookies)"
([] (cookies *driver*))
([driver]
(options/cookies driver)))
(defn cookie
"Return the cookie with name `cookie-name`. Returns a `Cookie` record which contains a `:cookie` field with the original Java object.
Examples:
=========
(cookie \"foo\")"
([cookie-name] (cookie *driver* cookie-name))
([driver cookie-name]
(options/cookie-named driver cookie-name)))
(defn execute-script
"Execute the JavaScript code `js` with arguments `js-args` which must be passed in as a vector (for arity reasons).
Within the script, use document to refer to the current document. Note that local variables will not be available once the script has finished executing, though global variables will persist.
If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken:
* For an HTML element, this method returns a WebElement
* For a decimal, a Double is returned
* For a non-decimal number, a Long is returned
* For a boolean, a Boolean is returned
* For all other cases, a String is returned.
* For an array, return a List<Object> with each object following the rules above. We support nested lists.
* Unless the value is null or there is no return value, in which null is returned.
Arguments must be a number, a boolean, a String, WebElement, or a List of any combination of the above. An exception will be thrown if the arguments do not meet these criteria. The arguments will be made available to the JavaScript via the 'arguments' magic variable, as if the function were called via 'Function.apply'
See http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/remote/RemoteWebDriver.html#executeScript(java.lang.String, java.lang.Object...) for full details.
Examples:
=========
;;
;; Set a global variable
;;
(execute-script \"window.document.title = 'asdf'\")
;;
;; Return an element. Note that this currently returns a raw WebElement Java object.
;;
(execute-script \"var myElement = document.getElementById('elementId'); return myElement;\")"
([js] (execute-script *driver* js))
([driver-or-js js-or-args] (if (driver? driver-or-js)
(execute-script driver-or-js js-or-args [])
(execute-script *driver* driver-or-js js-or-args)))
([driver js js-args]
(apply (partial core/execute-script driver js) js-args)))
(defn wait-until
"Make the browser wait until the predicate `pred` returns true, providing an optional `timeout` in milliseconds and an optional `interval` in milliseconds on which to attempt the predicate. If the timeout is exceeded, an exception is thrown.
The predicate is a function that accepts the browser `Driver` record as its single parameter, and should return a truthy/falsey value.
Examples:
=========
;;
;; Simple example (taken from unit tests)
;;
;; Wait until the title of the page is 'asdf'
;;
(execute-script \"setTimeout(function () { window.document.title = 'asdf'}, 3000)\")
(wait-until #(= (title) \"asdf\"))
;;
;; Wait until an element exists
;;
(... code to load page ...)
(wait-until #(exists? \"#foo\"))
(click \"#foo a.bar\")"
([pred] (wait/wait-until *driver* (fn [_] pred)))
([pred timeout] (wait/wait-until *driver* (fn [_] pred) timeout))
([pred timeout interval] (wait/wait-until *driver* (fn [_] pred) timeout interval))
([driver pred timeout interval] (wait/wait-until driver pred timeout interval)))
(defn implicit-wait
"Set the global `timeout` that the browser should wait when attempting to find elements on the page, before timing out with an exception.
Examples:
=========
;;
;; Simple example (taken from unit tests)
;;
;; Set implicit timeout (global) to 3 seconds, then execute JavaScript with a
;; noticeable delay to prove that it works
;;
(implicit-wait 3000)
(execute-script \"setTimeout(function () { window.document.body.innerHTML = '<div id='test'>hi!</div>'}, 1000)\")"
([timeout] (implicit-wait *driver* timeout))
([driver timeout]
(wait/implicit-wait driver timeout)))
(defn find-windows
"Return all `Window` records that match the given `attr-val` map.
Attributes can be anything in a `Window` record (`:title` or `:url`) or you can pass an `:index` key and a number value to select a window by its open order.
Examples:
=========
;;
;; By name
;;
(find-windows {:title \"Window Title\"})
;;
;; By URL
;;
(find-windows {:url \"http://example.com/test-page\"})
;;
;; By index
;;
(find-windows {:index 2})"
([attr-val] (find-windows *driver* attr-val))
([driver attr-val]
(core/find-windows driver attr-val)))
(defn find-window
"Return the first `Window` record that matches the given `attr-val` map.
Attributes can be anything in a `Window` record (`:title` or `:url`) or you can pass an `:index` key and a number value to select a window by its open order.
Examples:
=========
;;
;; By name
;;
(find-window {:title \"Window Title\"})
;;
;; By URL
;;
(find-window {:url \"http://example.com/test-page\"})
;;
;; By index
;;
(find-window {:index 2})"
([attr-val] (find-window *driver* attr-val))
([driver attr-val] (core/find-window driver attr-val)))
(defn find-table-cell
"Within the table found with query `table-q`, return the table cell at coordinates `coords`. The top-left cell has coordinates `[0 0]`.
Examples:
=========
;;
;; Simple example, find 2nd cell on 2nd row from top
;;
(find-table-cell \"table#my-table\" [1 1])"
([table-q coords] (find-table-cell *driver* table-q coords))
([driver table-q coords]
(core/find-table-cell driver (element driver table-q) coords)))
(defn find-table-row
"Within the table found with query `table-q`, return a seq of all cells at row number `row`. The top-most row is row `0` (zero-based index).
Examples:
=========
;;
;; Simple example, return cells in second row
;;
(find-table-row \"table#my-table\" 1)"
([table-q row] (find-table-row *driver* table-q row))
([driver table-q row]
(core/find-table-row driver (element driver table-q) row)))
;; Need to explain difference between element and find-element fn's
(defn find-elements
"Return `Element` records that match the given `attr-val`. Prefer the default behavior of `elements` when possible.
Whereas the `elements` function uses a query `q` with the default finder function, this function requires an `attr-val` parameter which is either a map or a vector of maps with special semantics for finding elements on the page.
The `attr-val` map can consist of one or more of the following:
* The key `:css` or `:xpath` and a query value (e.g., `{:css \"a.external\"}`)
* The key `:tag` and an HTML tag (e.g., `{:tag :a}`)
* An HTML element attribute and its value (e.g., `{:class \"external\"}`)
* A 'meta' tag `:button*`, `:radio`, `:checkbox`, `:textfield`, `:password`, `:filefield` (e.g., `{:tag :button*}`)
* The key `:index` and the zero-based index (order) of the target element on the page (e.g., `{:index 2}` retrieves the third element that matches)
* A vector of attr-val maps like the above, representing a hierarchical query (auto-generates XPath)
Examples:
=========
;;
;; Medley of possibilities
;;
(find-elements {:css \"a.foo\"})
(find-elements {:xpath \"//a[@class='foo']\"})
(find-elements {:tag :a, :text \"Login\"})
(find-elements {:tag :a, :index 4}) ;; 5th anchor tag
(find-elements {:tag :button*, :class \"foo\"})
(find-elements {:tag :radio, :class \"choice\"})
(find-elements [{:tag :div, :id \"container\"},
{:tag :a, :class \"external\"}])
"
([attr-val] (find-elements *driver* attr-val))
([driver attr-val]
(core/find-elements driver attr-val)))
(defn find-element
"Return first `Element` record that matches the given `attr-val`. Prefer the default behavior of `element` when possible.
Whereas the `element` function uses a query `q` with the default finder function, this function requires an `attr-val` parameter which is either a map or a vector of maps with special semantics for finding elements on the page.
The `attr-val` map can consist of one or more of the following:
* The key `:css` or `:xpath` and a query value (e.g., `{:css \"a.external\"}`)
* The key `:tag` and an HTML tag (e.g., `{:tag :a}`)
* An HTML element attribute and its value (e.g., `{:class \"external\"}`)
* A 'meta' tag `:button*`, `:radio`, `:checkbox`, `:textfield`, `:password`, `:filefield` (e.g., `{:tag :button*}`)
* The key `:index` and the zero-based index (order) of the target element on the page (e.g., `{:index 2}` retrieves the third element that matches)
* A vector of attr-val maps like the above, representing a hierarchical query (auto-generates XPath)
Examples:
=========
;;
;; Medley of possibilities
;;
(find-element {:css \"a.foo\"})
(find-element {:xpath \"//a[@class='foo']\"})
(find-element {:tag :a, :text \"Login\"})
(find-element {:tag :a, :index 4}) ;; 5th anchor tag
(find-element {:tag :button*, :class \"foo\"})
(find-element {:tag :radio, :class \"choice\"})
(find-element [{:tag :div, :id \"container\"},
{:tag :a, :class \"external\"}])
"
([attr-val] (find-element *driver* attr-val))
([driver attr-val]
(core/find-element driver attr-val)))
;; Element versions of find-element-by and find-elements-by
(defn find-elements-under
"Find the elements that are children of the element found with query `q-parent`, using the given `attr-val`. If `q-parent` is an `Element`, it will be used as-is. The `attr-val` can either be a find-element-style map of attributes and values, or a by-clause (`by-tag`, `by-class`, etc.)
Examples:
=========
;;
;; Example using a map
;;
(find-elements-under \"div#container\" {:tag :a, :id \"foo\"})
;;
;; Example using by-clause, find an element with id \"foo\" within a div with id \"container\"
;;
(find-elements-under \"div#container\" (core/by-id \"foo\")"
([q-parent attr-val] (find-elements-under *driver* q-parent attr-val))
([driver q-parent attr-val]
(if (element-like? q-parent)
(core/find-elements q-parent attr-val)
(core/find-elements (element driver q-parent) attr-val))))
(defn find-element-under
"Find the first element that is a child of the element found with query `q-parent`, using the given `attr-val`. If `q-parent` is an `Element`, it will be used as-is. The `attr-val` can either be a find-element-style map of attributes and values, or a by-clause (`by-tag`, `by-class`, etc.)
Examples:
=========
;;
;; Example using map, which generates a (by-xpath ...) form
;;
(find-element-under \"div#container\" {:tag :a, :id \"foo\"})
;;
;; Example using by-clause, find an element with id \"foo\" within a div with id \"container\"
;;
(find-element-under \"div#container\" (core/by-id \"foo\")"
([q-parent attr-val] (find-element-under *driver* q-parent attr-val))
([driver q-parent attr-val]
(if (element-like? q-parent)
(core/find-element q-parent attr-val)
(core/find-element (element driver q-parent) attr-val))))
;; ## Element functions ##
;;
;; Unlike their counterparts in core, you don't need to do a `(find-element ...)`
;; with these; just pass in a CSS query followed by other necessary parameters
;; and the first element that matches the query will be used automatically.
;;
;; If a CSS query string is not passed in, it's assumed you're trying to use these
;; functions like their core counterparts, in which case each function will default
;; back to core functionality (expecting that you're passing in an Element record)
(defn attribute
"For the first element found with query `q`, return the value of the given `attribute`.
Examples:
=========
;;
;; Example medley for an anchor tag with id \"foo\", class \"bar\", and target \"_blank\"
;;
(attribute \"a#foo\" :id) ;=> \"foo\"
(attribute \"a#foo\" :class) ;=> \"bar\"
(attribute \"a#foo\" :target) ;=> \"_blank\""
([q attr] (attribute *driver* q attr))
([driver q attr]
(core/attribute (element driver q) attr)))
(defn click
"Click the first element found with query `q`.
Examples:
=========
(click \"a#foo\")"
([q] (click *driver* q))
([driver q]
(core/click (element driver q))))
(defn displayed?
"Return true if the first element found with query `q` is visible on the page.
Examples:
=========
(displayed? \"div#container\") ;=> true
(displayed? \"a.hidden\") ;=> false"
([q] (displayed? *driver* q))
([driver q]
(core/displayed? (element driver q))))
(defn drag-and-drop
"Drag the first element found with query `qa` onto the first element found with query `qb`.
Examples:
=========
;;
;; Drag div with id \"draggable\" onto div with id \"droppable\"
;;
(drag-and-drop \"#draggable\" \"#droppable\")"
([qa qb] (drag-and-drop *driver* qa qb))
([driver qa qb]
(core/drag-and-drop driver (element driver qa) (element driver qb))))
(defn drag-and-drop-by
"Drag the first element found with query `q` by `:x` pixels to the right and `:y` pixels down, passed in as a map like `{:x 10, :y 10}`. Values default to zero if excluded. Use negative numbers for `:x` and `:y` to move left or up respectively.
Examples:
=========
;;
;; Drag a div with id \"draggable\" 20 pixels to the right
;;
(drag-and-drop-by \"#draggable\" {:x 20})
;;
;; Drag a div with id \"draggable\" 10 pixels down
;;
(drag-and-drop-by \"#draggable\" {:y 10})
;;
;; Drag a div with id \"draggable\" 15 pixels to the left and 5 pixels up
;;
(drag-and-drop-by \"#draggable\" {:x -15, :y -5})"
([q x-y-map] (drag-and-drop-by *driver* q x-y-map))
([driver q x-y-map]
(core/drag-and-drop-by driver (element driver q) x-y-map)))
(defn exists?
"Return true if the first element found with query `q` exists on the current page in the browser.
Examples:
=========
(exists? \"a#foo\") ;=> true
(exists? \"footer\") ;=> false"
([q] (exists? *driver* q))
([driver q]
(core/exists? (element driver q))))
(defn flash
"Flash the background color of the first element found with query `q`.
Examples:
=========
(flash \"a.hard-to-see\")"
([q] (flash *driver* q))
([driver q]
(core/flash (element driver q))))
(defn focus
"Explicitly give the first element found with query `q` focus on the page.
Examples:
=========
(focus \"input.next-element\")"
([q] (focus *driver* q))
([driver q]
(core/focus (element driver q))))
(defn html
"Return the inner html of the first element found with query `q`.
Examples:
=========
(html \"div.with-interesting-html\")"
([q] (html *driver* q))
([driver q]
(core/html (element driver q))))
(defn location
"Return a map of `:x` and `:y` coordinates for the first element found with query `q`.
Examples:
=========
(location \"a#foo\") ;=> {:x 240, :y 300}"
([q] (location *driver* q))
([driver q]
(core/location (element driver q))))
(defn location-once-visible
"Return a map of `:x` and `:y` coordinates for the first element found with query `q` once the page has been scrolled enough to be visible in the viewport.
Examples:
=========
(location-once-visible \"a#foo\") ;=> {:x 240, :y 300}"
([q] (location-once-visible *driver* q))
([driver q]
(core/location-once-visible (element driver q))))
(defn present?
"Return true if the first element found with query `q` both exists and is visible on the page.
Examples:
=========
(present? \"div#container\") ;=> true
(present? \"a#skip-to-navigation\") ;=> false"
([q] (present? *driver* q))
([driver q]
(core/present? (element driver q))))
(defn element-size
"Return the size of the first element found with query `q` in pixels as a map of `:width` and `:height`.
Examples:
=========
(size \"div#container\") ;=> {:width 960, :height 2000} "
([q] (element-size *driver* q))
([driver q]
(core/size (element driver q))))
(defn intersects?
"Return true if the first element found with query `qa` intersects with the first element found with query `qb`.
Examples:
=========
(intersect? \"#login\" \"#login_field\") ;=> true
(intersect? \"#login_field\" \"#password\") ;=> false"
([qa qb] (intersects? *driver* qa qb))
([driver qa qb]
(core/intersects? (element driver qa) (element driver qb))))
(defn tag
"Return the HTML tag for the first element found with query `q`.
Examples:
=========
(tag \"#foo\") ;=> \"a\""
([q] (tag *driver* q))
([driver q]
(core/tag (element driver q))))
(defn text
"Return the text within the first element found with query `q`.
Examples:
=========
(text \"#message\") ;=> \"An error occurred.\""
([q] (text *driver* q))
([driver q]
(core/text (element driver q))))
(defn value
"Return the value of the HTML value attribute for the first element found with query `q`. The is identical to `(attribute q :value)`
Examples:
=========
(value \"#my-button\") ;=> \"submit\" "
([q] (value *driver* q))
([driver q]
(core/value (element driver q))))
(defn visible?
"Return true if the first element found with query `q` is visible on the current page in the browser.
Examples:
=========
(visible? \"div#container\") ;=> true
(visible? \"a.hidden\") ;=> false"
([q] (visible? *driver* q))
([driver q]
(core/visible? (element driver q))))
(defn xpath
"Return an absolute XPath path for the first element found with query `q`. NOTE: This function relies on executing JavaScript in the browser, and is therefore not as dependable as other functions.
Examples:
=========
(xpath \"#login_field\") ;=> \"/html/body/div[2]/div/div/form/div[2]/label/input\""
([q] (xpath *driver* q))
([driver q]
(core/xpath (element driver q))))
(defn deselect
"If the first form element found with query `q` is selected, click the element to deselect it. Otherwise, do nothing and just return the element found.
Examples:
=========
(deselect \"input.already-selected\") ;=> click
(deselect \"input.not-selected\") ;=> do nothing"
([q] (deselect *driver* q))
([driver q]
(core/deselect (element driver q))))
(defn enabled?
"Return true if the first form element found with query `q` is enabled (not disabled).
Examples:
=========
(enabled? \"input\") ;=> true
(enabled? \"input[disabled='disabled']\") ;=> false"
([q] (enabled? *driver* q))
([driver q] (core/enabled? (element driver q))))
(defn input-text
"Type the string `s` into the first form element found with query `q`.
Examples:
=========
(input-text \"input#login_field\" \"semperos\")"
([q s] (input-text *driver* q s))
([driver q s]
(core/input-text (element driver q) s)))
(defn submit
"Submit the form that the first form element found with query `q` belongs to (this is equivalent to pressing ENTER in a text field while filling out a form).
Examples:
=========
(submit \"input#password\")"
([q] (submit *driver* q))
([driver q]
(core/submit (element driver q))))
(defn clear
"Clear the contents (the HTML value attribute) of the first form element found with query `q`.
Examples:
=========
(clear \"input.with-default-text\")"
([q] (clear *driver* q))
([driver q]
(core/clear (element driver q))))
(defn select
"If the first form element found with query `q` is not selected, click the element to select it. Otherwise, do nothing and just return the element found.
Examples:
=========
(select \"input.already-selected\") ;=> do nothing
(select \"input.not-selected\") ;=> click"
([q] (select *driver* q))
([driver q]
(core/select (element driver q))))
(defn selected?
"Return true if the first element found with the query `q` is selected (works for radio buttons, checkboxes, and option tags within select lists).
Examples:
=========
(selected? \"input[type='radio'][value='foo']\") ;=> true
(selected? \"option[value='foo']\") ;=> false "
([q] (selected? *driver* q))
([driver q] (core/selected? (element driver q))))
(defn send-keys
"Type the string `s` into the first form element found with query `q`.
Examples:
=========
(input-text \"input#login_field\" \"semperos\")"
([q s] (send-keys *driver* q s))
([driver q s]
(core/send-keys (element driver q) s)))
(defn toggle
"Toggle is a synonym for click. Click the first element found with query `q`.
Examples:
=========
(toggle \"input[type='checkbox'][value='foo']\")"
([q] (toggle *driver* q))
([driver q]
(core/toggle (element driver q))))
(defn options
"Return all option elements within the first select list found with query `q`.
Examples:
=========
(options \"#my-select-list\")"
([q] (options *driver* q))
([driver q]
(core/all-options (element driver q))))
(defn selected-options
"Return all selected option elements within the first select list found with query `q`.
Examples:
=========
(selected-options \"#my-select-list\")"
([q] (selected-options *driver* q))
([driver q]
(core/all-selected-options (element driver q))))
(defn deselect-option
"Deselect the option element matching `attr-val` within the first select list found with query `q`.
The `attr-val` can contain `:index`, `:value`, or `:text` keys to find the target option element. Index is the zero-based order of the option element in the list, value is the value of the HTML value attribute, and text is the visible text of the option element on the page.
Examples:
=========
;;
;; By index, select 3rd option element
;;
(deselect-option \"#my-select-list\" {:index 2})
;;
;; By value of option element
;;
(deselect-option \"#my-select-list\" {:value \"foo\"})
;;
;; By visible text of option element
;;
(deselect-option \"#my-select-list\" {:value \"Foo\"})"
([q attr-val] (deselect-option *driver* q attr-val))
([driver q attr-val]
(core/deselect-option (element driver q) attr-val)))
(defn deselect-all
"Deselect all options within the first select list found with query `q`.
Examples:
=========
(deselect-all \"#my-select-list\")"
([q] (deselect-all *driver* q))
([driver q] (core/deselect-all (element driver q))))
(defn deselect-by-index
"Deselect the option element at index `idx` (zero-based) within the first select list found with query `q`.
Examples:
=========
;;
;; Deselect by index, deselect 2nd element
;;
(deselect-by-index \"#my-select-list\" 1)"
([q idx] (deselect-by-index *driver* q idx))
([driver q idx] (core/deselect-by-index (element driver q) idx)))
(defn deselect-by-text
"Deselect the option element with visible text `text` within the first select list found with query `q`.
Examples:
=========
(deselect-by-text \"#my-select-list\" \"Foo\")"
([q text] (deselect-by-text *driver* q text))
([driver q text]
(core/deselect-by-text (element driver q) text)))
(defn deselect-by-value
"Deselect the option element with `value` within the first select list found with query `q`.
Examples:
=========
(deselect-by-value \"#my-select-list\" \"foo\")"
([q value] (deselect-by-value *driver* q value))
([driver q value]
(core/deselect-by-value (element driver q) value)))
(defn multiple?
"Return true if the first select list found with query `q` allows multiple selections.
Examples:
=========
(multiple? \"select.multiple\") ;=> true
(multiple? \"select.not-multiple\") ;=> false "
([q] (multiple? *driver* q))
([driver q] (core/multiple? (element driver q))))
(defn select-option
"Select the option element matching `attr-val` within the first select list found with query `q`.
The `attr-val` can contain `:index`, `:value`, or `:text` keys to find the target option element. Index is the zero-based order of the option element in the list, value is the value of the HTML value attribute, and text is the visible text of the option element on the page.
Examples:
=========
;;
;; By index, select 3rd option element
;;
(select-option \"#my-select-list\" {:index 2})
;;
;; By value of option element
;;
(select-option \"#my-select-list\" {:value \"foo\"})
;;
;; By visible text of option element
;;
(select-option \"#my-select-list\" {:value \"Foo\"})"
([q attr-val] (select-option *driver* q attr-val))
([driver q attr-val]
(core/select-option (element driver q) attr-val)))
(defn select-all
"Select all options within the first select list found with query `q`.
Examples:
=========
(deselect-all \"#my-select-list\")"
([q] (select-all *driver* q))
([driver q]
(core/select-all (element driver q))))
(defn select-by-index
"Select the option element at index `idx` (zero-based) within the first select list found with query `q`.
Examples:
=========
;;
;; Select by index, select 2nd element
;;
(select-by-index \"#my-select-list\" 1)"
([q idx] (select-by-index *driver* q idx))
([driver q idx]
(core/select-by-index (element driver q) idx)))
(defn select-by-text
"Select the option element with visible text `text` within the first select list found with query `q`.
Examples:
=========
(select-by-text \"#my-select-list\" \"foo\")"
([q text] (select-by-text *driver* q text))
([driver q text]
(core/select-by-text (element driver q) text)))
(defn select-by-value
"Select the option element with `value` within the first select list found with query `q`.
Examples:
=========
(select-by-value \"#my-select-list\" \"foo\")"
([q value] (select-by-value *driver* q value))
([driver q value]
(core/select-by-value (element driver q) value)))
;; Helpers
(defn- quick-fill*
([k v] (quick-fill* k v false))
([k v submit?]
;; shortcuts:
;; v as string => text to input
(let [q k
action (if (string? v)
#(input-text % v)
v)
target-els (elements q)]
(if submit?
(doseq [el target-els]
(action el))
(map action target-els)))))
(defn quick-fill
"A utility for filling out multiple fields in a form in one go. Returns all the affected elements (if you want a list of unique elements, pass the results through the `distinct` function in clojure.core).
`query-action-maps` - a seq of maps of queries to actions (queries find HTML elements, actions are fn's that act on them)
Note that an \"action\" that is just a String will be interpreted as a call to `input-text` with that String for the target text field.
Examples:
=========
(quick-fill {\"#first_name\" \"<NAME>\"}
{\"a.foo\" click})"
[& query-action-maps]
(flatten (map (fn [a-map]
(let [[k v] (first a-map)] (quick-fill* k v)))
query-action-maps)))
(defn quick-fill-submit
"A utility for filling out multiple fields in a form in one go. Always returns nil instead of the affected elements, since on submit all of the elements will be void.
`query-action-maps` - a seq of maps of queries to actions (queries find HTML elements, actions are fn's that act on them)
Note that an \"action\" that is just a String will be interpreted as a call to `input-text` with that String for the target text field.
Examples:
=========
(quick-fill {\"#first_name\" \"<NAME>\"}
{\"a.foo\" click})"
[& query-action-maps]
(doseq [entry query-action-maps
[k v] entry]
(quick-fill* k v true)))
(defn accept
"Accept an alert popup dialog. Equivalent to pressing its 'Ok' button."
([] (accept *driver*))
([driver] (core/accept driver)))
(defn alert-obj
"Retrieve the underlying Java object used to identify an alert popup dialog. Exposed to allow you to use methods not yet exposed via clj-webdriver's API's."
([] (alert-obj *driver*))
([driver] (core/alert-obj driver)))
(defn alert-text
"Get the text of the alert popup dialog's message."
([] (alert-text *driver*))
([driver] (core/alert-text driver)))
(defn dismiss
"Dismiss the alert popup dialog. Equivalent to pressing its 'Cancel' button."
([] (dismiss *driver*))
([driver] (core/dismiss driver)))
(defn window-position
"Get the position of the top-left corner of the browser's window relative to the top-left corner of your primary display, returned as a map of `:x` and `:y` integers.
Examples:
=========
(window-position)"
([] (window-position *driver*))
([driver] (win/position driver)))
(defn window-reposition
"Move the top-left corner of the browser `:x` pixels to the right and `:y` pixels down from the top-left of your primary display. If you do not provide a coordinate, it's current value for the browser position will not be changed.
Examples:
=========
(window-reposition {:x 25, :y 50})
(window-reposition {:y 50})"
([coordinates-map] (window-reposition *driver* coordinates-map))
([driver {:keys [x y] :as coordinates-map}]
(win/reposition driver coordinates-map)))
(defn window-size
"Get the size of the browser's window in pixels, returned as a map of `:width` and `:height`.
Examples:
=========
(window-size)"
([] (window-size *driver*))
([driver] (win/size driver)))
(defn window-resize
"Resize the browser window to the given `:width` and `:height`. If a dimension is not specified, it's current value for the browser size will not be changed.
Examples:
=========
(window-resize {:width 300 :height 400})
(window-resize {:height 400})"
([dimensions-map] (window-resize *driver* dimensions-map))
([driver {:keys [width height] :as dimensions-map}]
(win/resize driver dimensions-map)))
(defn window-maximize
"Maximize the browser window.
Examples:
=========
(window-maximize)"
([] (window-maximize *driver*))
([driver] (win/maximize driver)))
| true | ;; The faster way to use clj-webdriver: take a taxi
(ns clj-webdriver.taxi
(:use [clj-webdriver.driver :only [driver?]]
[clj-webdriver.element :only [element-like?]])
(:require [clj-webdriver.core :as core]
[clj-webdriver.options :as options]
[clj-webdriver.util :as util]
[clj-webdriver.wait :as wait]
[clj-webdriver.window :as win])
(:import clj_webdriver.element.Element))
(declare css-finder)
(def ^:dynamic *driver*)
(def ^:dynamic *finder-fn* css-finder)
(def ^{:doc (str "Alias of clj-webdriver.core/new-driver:\n"
(:doc (meta #'clj-webdriver.core/new-driver)))
:arglists (:arglists (meta #'clj-webdriver.core/new-driver))}
new-driver clj-webdriver.core/new-driver)
(defn- set-driver*
"Given a `browser-spec`, instantiate a new Driver record and assign to `*driver*`."
[browser-spec]
(let [new-driver (if (driver? browser-spec)
browser-spec
(core/new-driver browser-spec))]
(alter-var-root (var *driver*)
(constantly new-driver)
(when (thread-bound? (var *driver*))
(set! *driver* new-driver)))))
(declare to)
(defn set-driver!
"Set a default `Driver` for this thread, optionally sending it to a starting `url`.
Available browsers are `:firefox`, `:chrome`, `:ie`, `:opera`, `:phantomjs` and `:htmlunit`.
Examples:
=========
;;
;; Simple example
;;
(set-driver! {:browser :firefox})
;;
;; Full example
;;
(set-driver! {:browser :firefox
:cache-spec {:strategy :basic,
:args [{}],
:include [ (fn [element] (= (attribute element :class) \"external\"))
{:css \"ol#pages\"}]}
;;
;; Use existing Driver record
;;
(set-driver! a-driver)"
([browser-spec] (set-driver* browser-spec))
([browser-spec url] (to (set-driver* browser-spec) url)))
(defn set-finder!
"Set a default finder function, which will be used with all `q` parameters in functions that require an Element.
Examples:
=========
;;
;; Simple example
;;
(set-finder! xpath-finder)
;;
;; Derivative finder function
;;
;; Takes the query string and always prepends \"div#container \", which would be
;; useful in situations where you know you're always inside that particular div.
;; (Note that this same functionality is provided by `find-element-under`, but
;; you get the idea.)
;;
(set-finder! (fn [q]
(if (element-like? q)
q
(css-finder (str \"div#container \" q)))))
;;
;; Custom finder function
;;
;; If you want to easily switch between using CSS and XPath (e.g., because
;; XPath has the text() function for which no CSS equivalent exists), then
;; you could write something like this, where `q` would become either the map
;; {:css \"query\"} or {:xpath \"query\"} instead of just a string.
;;
(set-finder! (fn [q]
(if (element-like? q)
q
(case (first (keys q))
:css (core/find-elements-by *driver* (by-css (first (values q))))
:xpath (core/find-elements-by *driver* (by-xpath (first (values q))))))))
;;
;; (Note: This last example is written to show how to use the lowest-level functions
;; `find-elements-by`, `by-css` and `by-xpath`. The maps `{:css \"query\"}` and
;; `{:xpath \"query\"}` are themselves acceptable arguments to the `find-elements`,
;; function, so that function could have been used instead without the `case` statement.)
;;"
[finder-fn]
(alter-var-root (var *finder-fn*)
(constantly finder-fn)
(when (thread-bound? (var *finder-fn*))
(set! *finder-fn* finder-fn))))
(declare quit)
(defmacro with-driver
"Given a `browser-spec` to start a browser, execute the forms in `body`, then call `quit` on the browser. Uses the default finder function.
Examples:
=========
;;
;; Log into Github
;;
(with-driver {:browser :firefox}
(to \"https://github.com\")
(click \"a[href*='login']\")
(input-text \"#login_field\" \"your_username\")
(-> \"#password\"
(input-text \"your_password\")
submit))"
[browser-spec & body]
`(binding [*driver* (core/new-driver ~browser-spec)]
(try
~@body
(finally
(quit)))))
(defmacro with-driver-fn
"Given a `browser-spec` to start a browser and a `finder-fn` to use as a finding function, execute the forms in `body`, then call `quit` on the browser.
Examples:
=========
;;
;; Log into Github
;;
(with-driver {:browser :firefox} xpath-finder
(to \"https://github.com\")
(click \"//a[text()='Login']\")
(input-text \"//input[@id='login_field']\" \"your_username\")
(-> \"//input[@id='password']\"
(input-text \"your_password\")
submit))"
[browser-spec finder-fn & body]
`(binding [*driver* (core/new-driver ~browser-spec)
*finder-fn* ~finder-fn]
(try
~@body
(finally
(quit)))))
(defn css-finder
"Given a CSS query `q`, return a lazy seq of the elements found by calling `find-elements` with `by-css`. If `q` is an `Element`, it is returned unchanged.
This function is used internally by the Taxi API as `*finder*`. See the documentation for `set-finder!` for examples of extending this function or creating your own custom finder function."
([q] (css-finder *driver* q))
([driver q]
(cond
(element-like? q) q
(map? q) (core/find-elements driver q)
:else (core/find-elements driver {:css q}))))
(set-finder! css-finder)
(defn xpath-finder
"Given a XPath query `q`, return a lazy seq of the elements found by calling `find-elements` with `by-xpath`. If `q` is an `Element`, it is returned unchanged.
This function is used internally by the Taxi API as `*finder*`. See the documentation for `set-finder!` for examples of extending this function or creating your own custom finder function."
([q] (xpath-finder *driver* q))
([driver q]
(cond
(element-like? q) q
(map? q) (core/find-elements driver q)
:else (core/find-elements driver {:xpath q}))))
;; Be able to get actual element/elements when needed
(defn element
"Given a query `q`, return the first element that the default finder function returns.
Examples:
=========
;;
;; Simple Example
;;
;; Create a var that points to an element for later use.
;;
(def login-link (element \"a[href*='login']\"))
;;
;; More useful example: composing actions on an element
;;
;; When threading actions together, it's more performant to thread an actual element,
;; than to thread simply the query string. Threading the query string makes clj-webdriver
;; locate the same element multiple times, while threading an actual element only
;; requires one lookup.
;;
(-> (element \"input#password\")
(input-text \"my-password\")
submit)"
([q] (element *driver* q))
([driver q]
(if (element-like? q)
q
(first (*finder-fn* driver q)))))
(defn elements
"Given a query `q`, return the elements that the default finder function returns.
Examples:
=========
;;
;; Simple Example
;;
;; Save a seq of anchor tags (links) for later.
;;
(def target-elements (elements \"a\"))"
([q] (elements *driver* q))
([driver q]
(if (element-like? q)
(lazy-seq (list q))
(*finder-fn* driver q))))
;; ## Driver functions ##
(defn to
"Navigate the browser to `url`.
Examples:
=========
;;
;; Simple Example
;;
(to \"https://github.com\")
;;
;; Custom function for building URL's from a base url
;;
(defn go
[path]
(let [base-url \"http://example.com/\"]
(to (str base-url path))))
;; (go \"test-page\") would navigate to \"http://example.com/test-page\""
([url]
(to *driver* url))
([driver url]
(core/to driver url)))
(defn back
"Navigate back in the browser history, optionally `n` times.
Examples:
=========
;;
;; Simple Example
;;
(back)
;;
;; Specify number of times to go back
;;
(back 2)"
([] (back *driver* 1))
([driver-or-n] (if (driver? driver-or-n)
(back driver-or-n 1)
(back *driver* driver-or-n)))
([driver n]
(dotimes [m n]
(core/back driver))
driver))
(defn close
"Close the browser. If multiple windows are open, this only closes the active window.
Examples:
=========
(close)"
([] (close *driver*))
([driver]
(core/close driver)))
(defn current-url
"Return the current url of the browser.
Examples:
=========
(current-url)"
([] (current-url *driver*))
([driver] (core/current-url driver)))
(defn forward
"Navigate forward in the browser history.
Examples:
=========
;;
;; Simple Example
;;
(forward)
;;
;; Specify number of times to go forward
;;
(forward 2)"
([] (forward *driver* 1))
([driver-or-n] (if (driver? driver-or-n)
(forward driver-or-n 1)
(forward *driver* driver-or-n)))
([driver n]
(dotimes [m n]
(core/forward driver))
driver))
(defn get-url
"Navigate the browser to `url`.
Examples:
=========
;;
;; Simple Example
;;
(get-url \"https://github.com\")
;;
;; Custom function for building URL's from a base url
;;
(defn go
[path]
(let [base-url \"http://example.com/\"]
(get-url (str base-url path))))
;; (go \"test-page\") would navigate to \"http://example.com/test-page\""
([url] (get-url *driver* url))
([driver url]
(core/get-url driver url)))
(defn take-screenshot
"Take a screenshot of the browser's current page, optionally specifying the format (`:file`, `:base64`, or `:bytes`) and the `destination` (something that `clojure.java.io/file` will accept).
Examples:
=========
;;
;; Simple Example
;;
;; Return screenshot as file object
;;
(take-screenshot :file)
;;
;; Specify a default destination for the file object
;;
(take-screenshot :file \"/path/to/save/screenshot.png\")"
([] (core/get-screenshot *driver* :file))
([format] (core/get-screenshot *driver* format))
([format destination] (core/get-screenshot *driver* format destination))
([driver format destination] (core/get-screenshot driver format destination)))
(defn page-source
"Return the source code of the current page in the browser.
Examples:
=========
;;
;; Simple Example
;;
(page-source)
;;
;; Do something with the HTML
;;
;; Selenium-WebDriver will instantiate a Java object for every element you query
;; or interact with, so if you have huge pages or need to do heavy-duty DOM
;; inspection or traversal, it could be more performant to do that \"offline\".
;;
(let [source (page-source)]
;; do hard-core parsing and manipulation here
)"
([] (page-source *driver*))
([driver]
(core/page-source driver)))
(defn quit
"Quit the browser completely, including all open windows.
Examples:
=========
(quit)"
([] (quit *driver*))
([driver]
(core/quit driver)))
(defn refresh
"Refresh the current page in the browser. Note that all references to elements will become \"stale\" and unusable after a page refresh.
Examples:
=========
(refresh)"
([] (refresh *driver*))
([driver]
(core/refresh driver)))
(defn title
"Return the title of the current page in the browser.
Examples:
=========
(title)"
([] (title *driver*))
([driver]
(core/title driver)))
(defn window
"Return a `Window` that contains information about the active window and can be used for switching or resizing.
Examples:
=========
(window)"
([] (window *driver*))
([driver]
(core/window driver)))
(defn windows
"Return `Window` records as a seq for all open windows.
Examples:
=========
(windows)"
([] (windows *driver*))
([driver]
(core/windows driver)))
(defn other-windows
"Return a `Window` for all open windows except the active one.
Examples:
=========
(other-windows)"
([] (other-windows *driver*))
([driver]
(core/other-windows driver)))
;; TODO: test coverage
(defn switch-to-frame
"Switch focus to the frame specified by `frame-q`, which is a standard Taxi element query or an integer for the order (zero-based index) of the frame on the page.
Examples:
=========
(switch-to-frame \"#target-frame\")
(switch-to-frame 1)"
([frame-q] (switch-to-frame *driver* frame-q))
([driver frame-q]
(let [frame (if (number? frame-q)
frame-q
(element frame-q))]
(core/switch-to-frame driver frame))))
;; TODO: accept a `Window` record or an attr-val that would get the window
(defn switch-to-window
"Switch focus to the window for the given one of the following:
* A string representing the target window name (as seen in the application titlebar)
* A number representing the index (order) of the target window
* A `Window` record
Examples:
=========
;;
;; By name
;;
(switch-to-window \"Name Of Window\")
;;
;; By index (order), open the 3rd window
;;
(switch-to-window 2)
;;
;; Passing a `Window` record directly (as returned by the `window` function)
;;
(switch-to-window a-window-record)"
([window] (switch-to-window *driver* window))
([driver window]
(core/switch-to-window driver window)))
(defn switch-to-other-window
"If two windows are open, switch focus to the other.
Examples:
=========
(switch-to-other-window)"
([] (switch-to-other-window *driver*))
([driver]
(core/switch-to-other-window driver)))
(defn switch-to-default
"Switch focus to the first first frame of the page, or the main document if the page contains iframes.
Examples:
=========
(switch-to-default)"
([] (switch-to-default *driver*))
([driver]
(core/switch-to-default driver)))
(defn switch-to-active
"Switch to the page element that currently has focus, or to the body if this cannot be detected.
Examples:
=========
(switch-to-active)"
([] (switch-to-active *driver*))
([driver]
(core/switch-to-active driver)))
(defn add-cookie
"Add a cookie to the browser session. The `cookie-spec` is a map which must contain `:name` and `:value` keys, and can also optionally include `:domain`, `:path`, `:expiry`, and `:secure?` (a boolean).
Examples:
=========
;;
;; Simple example
;;
(add-cookie {:name \"foo\", :value \"bar\"})
;;
;; Full example
;;
(add-cookie {:name \"foo\", :value \"bar\",
:domain \"example.com\", :path \"a-path\",
:expiry (java.util.Date.), :secure? false}) "
([cookie-spec] (add-cookie *driver* cookie-spec))
([driver cookie-spec]
(options/add-cookie driver cookie-spec)))
(defn delete-cookie
"Provided the name of a cookie or a Cookie record itself, delete it from the browser session.
Examples:
=========
;;
;; By name
;;
(delete-cookie \"foo\")
;;
;; With `Cookie` record as returned by `cookies` or `cookie` functions
;;
(delete-cookie a-cookie)"
([name-or-obj] (delete-cookie *driver* name-or-obj))
([driver name-or-obj]
(if (string? name-or-obj)
(options/delete-cookie-named driver name-or-obj)
(options/delete-cookie driver name-or-obj))))
(defn delete-all-cookies
"Delete all cookies from the browser session.
Examples:
=========
(delete-all-cookies)"
([] (delete-all-cookies *driver*))
([driver]
(options/delete-all-cookies driver)))
(defn cookies
"Return a seq of all cookies in the browser session. Items are `Cookie` records, which themselves contain a `:cookie` field with the original Java objects.
Examples:
=========
(cookies)"
([] (cookies *driver*))
([driver]
(options/cookies driver)))
(defn cookie
"Return the cookie with name `cookie-name`. Returns a `Cookie` record which contains a `:cookie` field with the original Java object.
Examples:
=========
(cookie \"foo\")"
([cookie-name] (cookie *driver* cookie-name))
([driver cookie-name]
(options/cookie-named driver cookie-name)))
(defn execute-script
"Execute the JavaScript code `js` with arguments `js-args` which must be passed in as a vector (for arity reasons).
Within the script, use document to refer to the current document. Note that local variables will not be available once the script has finished executing, though global variables will persist.
If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken:
* For an HTML element, this method returns a WebElement
* For a decimal, a Double is returned
* For a non-decimal number, a Long is returned
* For a boolean, a Boolean is returned
* For all other cases, a String is returned.
* For an array, return a List<Object> with each object following the rules above. We support nested lists.
* Unless the value is null or there is no return value, in which null is returned.
Arguments must be a number, a boolean, a String, WebElement, or a List of any combination of the above. An exception will be thrown if the arguments do not meet these criteria. The arguments will be made available to the JavaScript via the 'arguments' magic variable, as if the function were called via 'Function.apply'
See http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/remote/RemoteWebDriver.html#executeScript(java.lang.String, java.lang.Object...) for full details.
Examples:
=========
;;
;; Set a global variable
;;
(execute-script \"window.document.title = 'asdf'\")
;;
;; Return an element. Note that this currently returns a raw WebElement Java object.
;;
(execute-script \"var myElement = document.getElementById('elementId'); return myElement;\")"
([js] (execute-script *driver* js))
([driver-or-js js-or-args] (if (driver? driver-or-js)
(execute-script driver-or-js js-or-args [])
(execute-script *driver* driver-or-js js-or-args)))
([driver js js-args]
(apply (partial core/execute-script driver js) js-args)))
(defn wait-until
"Make the browser wait until the predicate `pred` returns true, providing an optional `timeout` in milliseconds and an optional `interval` in milliseconds on which to attempt the predicate. If the timeout is exceeded, an exception is thrown.
The predicate is a function that accepts the browser `Driver` record as its single parameter, and should return a truthy/falsey value.
Examples:
=========
;;
;; Simple example (taken from unit tests)
;;
;; Wait until the title of the page is 'asdf'
;;
(execute-script \"setTimeout(function () { window.document.title = 'asdf'}, 3000)\")
(wait-until #(= (title) \"asdf\"))
;;
;; Wait until an element exists
;;
(... code to load page ...)
(wait-until #(exists? \"#foo\"))
(click \"#foo a.bar\")"
([pred] (wait/wait-until *driver* (fn [_] pred)))
([pred timeout] (wait/wait-until *driver* (fn [_] pred) timeout))
([pred timeout interval] (wait/wait-until *driver* (fn [_] pred) timeout interval))
([driver pred timeout interval] (wait/wait-until driver pred timeout interval)))
(defn implicit-wait
"Set the global `timeout` that the browser should wait when attempting to find elements on the page, before timing out with an exception.
Examples:
=========
;;
;; Simple example (taken from unit tests)
;;
;; Set implicit timeout (global) to 3 seconds, then execute JavaScript with a
;; noticeable delay to prove that it works
;;
(implicit-wait 3000)
(execute-script \"setTimeout(function () { window.document.body.innerHTML = '<div id='test'>hi!</div>'}, 1000)\")"
([timeout] (implicit-wait *driver* timeout))
([driver timeout]
(wait/implicit-wait driver timeout)))
(defn find-windows
"Return all `Window` records that match the given `attr-val` map.
Attributes can be anything in a `Window` record (`:title` or `:url`) or you can pass an `:index` key and a number value to select a window by its open order.
Examples:
=========
;;
;; By name
;;
(find-windows {:title \"Window Title\"})
;;
;; By URL
;;
(find-windows {:url \"http://example.com/test-page\"})
;;
;; By index
;;
(find-windows {:index 2})"
([attr-val] (find-windows *driver* attr-val))
([driver attr-val]
(core/find-windows driver attr-val)))
(defn find-window
"Return the first `Window` record that matches the given `attr-val` map.
Attributes can be anything in a `Window` record (`:title` or `:url`) or you can pass an `:index` key and a number value to select a window by its open order.
Examples:
=========
;;
;; By name
;;
(find-window {:title \"Window Title\"})
;;
;; By URL
;;
(find-window {:url \"http://example.com/test-page\"})
;;
;; By index
;;
(find-window {:index 2})"
([attr-val] (find-window *driver* attr-val))
([driver attr-val] (core/find-window driver attr-val)))
(defn find-table-cell
"Within the table found with query `table-q`, return the table cell at coordinates `coords`. The top-left cell has coordinates `[0 0]`.
Examples:
=========
;;
;; Simple example, find 2nd cell on 2nd row from top
;;
(find-table-cell \"table#my-table\" [1 1])"
([table-q coords] (find-table-cell *driver* table-q coords))
([driver table-q coords]
(core/find-table-cell driver (element driver table-q) coords)))
(defn find-table-row
"Within the table found with query `table-q`, return a seq of all cells at row number `row`. The top-most row is row `0` (zero-based index).
Examples:
=========
;;
;; Simple example, return cells in second row
;;
(find-table-row \"table#my-table\" 1)"
([table-q row] (find-table-row *driver* table-q row))
([driver table-q row]
(core/find-table-row driver (element driver table-q) row)))
;; Need to explain difference between element and find-element fn's
(defn find-elements
"Return `Element` records that match the given `attr-val`. Prefer the default behavior of `elements` when possible.
Whereas the `elements` function uses a query `q` with the default finder function, this function requires an `attr-val` parameter which is either a map or a vector of maps with special semantics for finding elements on the page.
The `attr-val` map can consist of one or more of the following:
* The key `:css` or `:xpath` and a query value (e.g., `{:css \"a.external\"}`)
* The key `:tag` and an HTML tag (e.g., `{:tag :a}`)
* An HTML element attribute and its value (e.g., `{:class \"external\"}`)
* A 'meta' tag `:button*`, `:radio`, `:checkbox`, `:textfield`, `:password`, `:filefield` (e.g., `{:tag :button*}`)
* The key `:index` and the zero-based index (order) of the target element on the page (e.g., `{:index 2}` retrieves the third element that matches)
* A vector of attr-val maps like the above, representing a hierarchical query (auto-generates XPath)
Examples:
=========
;;
;; Medley of possibilities
;;
(find-elements {:css \"a.foo\"})
(find-elements {:xpath \"//a[@class='foo']\"})
(find-elements {:tag :a, :text \"Login\"})
(find-elements {:tag :a, :index 4}) ;; 5th anchor tag
(find-elements {:tag :button*, :class \"foo\"})
(find-elements {:tag :radio, :class \"choice\"})
(find-elements [{:tag :div, :id \"container\"},
{:tag :a, :class \"external\"}])
"
([attr-val] (find-elements *driver* attr-val))
([driver attr-val]
(core/find-elements driver attr-val)))
(defn find-element
"Return first `Element` record that matches the given `attr-val`. Prefer the default behavior of `element` when possible.
Whereas the `element` function uses a query `q` with the default finder function, this function requires an `attr-val` parameter which is either a map or a vector of maps with special semantics for finding elements on the page.
The `attr-val` map can consist of one or more of the following:
* The key `:css` or `:xpath` and a query value (e.g., `{:css \"a.external\"}`)
* The key `:tag` and an HTML tag (e.g., `{:tag :a}`)
* An HTML element attribute and its value (e.g., `{:class \"external\"}`)
* A 'meta' tag `:button*`, `:radio`, `:checkbox`, `:textfield`, `:password`, `:filefield` (e.g., `{:tag :button*}`)
* The key `:index` and the zero-based index (order) of the target element on the page (e.g., `{:index 2}` retrieves the third element that matches)
* A vector of attr-val maps like the above, representing a hierarchical query (auto-generates XPath)
Examples:
=========
;;
;; Medley of possibilities
;;
(find-element {:css \"a.foo\"})
(find-element {:xpath \"//a[@class='foo']\"})
(find-element {:tag :a, :text \"Login\"})
(find-element {:tag :a, :index 4}) ;; 5th anchor tag
(find-element {:tag :button*, :class \"foo\"})
(find-element {:tag :radio, :class \"choice\"})
(find-element [{:tag :div, :id \"container\"},
{:tag :a, :class \"external\"}])
"
([attr-val] (find-element *driver* attr-val))
([driver attr-val]
(core/find-element driver attr-val)))
;; Element versions of find-element-by and find-elements-by
(defn find-elements-under
"Find the elements that are children of the element found with query `q-parent`, using the given `attr-val`. If `q-parent` is an `Element`, it will be used as-is. The `attr-val` can either be a find-element-style map of attributes and values, or a by-clause (`by-tag`, `by-class`, etc.)
Examples:
=========
;;
;; Example using a map
;;
(find-elements-under \"div#container\" {:tag :a, :id \"foo\"})
;;
;; Example using by-clause, find an element with id \"foo\" within a div with id \"container\"
;;
(find-elements-under \"div#container\" (core/by-id \"foo\")"
([q-parent attr-val] (find-elements-under *driver* q-parent attr-val))
([driver q-parent attr-val]
(if (element-like? q-parent)
(core/find-elements q-parent attr-val)
(core/find-elements (element driver q-parent) attr-val))))
(defn find-element-under
"Find the first element that is a child of the element found with query `q-parent`, using the given `attr-val`. If `q-parent` is an `Element`, it will be used as-is. The `attr-val` can either be a find-element-style map of attributes and values, or a by-clause (`by-tag`, `by-class`, etc.)
Examples:
=========
;;
;; Example using map, which generates a (by-xpath ...) form
;;
(find-element-under \"div#container\" {:tag :a, :id \"foo\"})
;;
;; Example using by-clause, find an element with id \"foo\" within a div with id \"container\"
;;
(find-element-under \"div#container\" (core/by-id \"foo\")"
([q-parent attr-val] (find-element-under *driver* q-parent attr-val))
([driver q-parent attr-val]
(if (element-like? q-parent)
(core/find-element q-parent attr-val)
(core/find-element (element driver q-parent) attr-val))))
;; ## Element functions ##
;;
;; Unlike their counterparts in core, you don't need to do a `(find-element ...)`
;; with these; just pass in a CSS query followed by other necessary parameters
;; and the first element that matches the query will be used automatically.
;;
;; If a CSS query string is not passed in, it's assumed you're trying to use these
;; functions like their core counterparts, in which case each function will default
;; back to core functionality (expecting that you're passing in an Element record)
(defn attribute
"For the first element found with query `q`, return the value of the given `attribute`.
Examples:
=========
;;
;; Example medley for an anchor tag with id \"foo\", class \"bar\", and target \"_blank\"
;;
(attribute \"a#foo\" :id) ;=> \"foo\"
(attribute \"a#foo\" :class) ;=> \"bar\"
(attribute \"a#foo\" :target) ;=> \"_blank\""
([q attr] (attribute *driver* q attr))
([driver q attr]
(core/attribute (element driver q) attr)))
(defn click
"Click the first element found with query `q`.
Examples:
=========
(click \"a#foo\")"
([q] (click *driver* q))
([driver q]
(core/click (element driver q))))
(defn displayed?
"Return true if the first element found with query `q` is visible on the page.
Examples:
=========
(displayed? \"div#container\") ;=> true
(displayed? \"a.hidden\") ;=> false"
([q] (displayed? *driver* q))
([driver q]
(core/displayed? (element driver q))))
(defn drag-and-drop
"Drag the first element found with query `qa` onto the first element found with query `qb`.
Examples:
=========
;;
;; Drag div with id \"draggable\" onto div with id \"droppable\"
;;
(drag-and-drop \"#draggable\" \"#droppable\")"
([qa qb] (drag-and-drop *driver* qa qb))
([driver qa qb]
(core/drag-and-drop driver (element driver qa) (element driver qb))))
(defn drag-and-drop-by
"Drag the first element found with query `q` by `:x` pixels to the right and `:y` pixels down, passed in as a map like `{:x 10, :y 10}`. Values default to zero if excluded. Use negative numbers for `:x` and `:y` to move left or up respectively.
Examples:
=========
;;
;; Drag a div with id \"draggable\" 20 pixels to the right
;;
(drag-and-drop-by \"#draggable\" {:x 20})
;;
;; Drag a div with id \"draggable\" 10 pixels down
;;
(drag-and-drop-by \"#draggable\" {:y 10})
;;
;; Drag a div with id \"draggable\" 15 pixels to the left and 5 pixels up
;;
(drag-and-drop-by \"#draggable\" {:x -15, :y -5})"
([q x-y-map] (drag-and-drop-by *driver* q x-y-map))
([driver q x-y-map]
(core/drag-and-drop-by driver (element driver q) x-y-map)))
(defn exists?
"Return true if the first element found with query `q` exists on the current page in the browser.
Examples:
=========
(exists? \"a#foo\") ;=> true
(exists? \"footer\") ;=> false"
([q] (exists? *driver* q))
([driver q]
(core/exists? (element driver q))))
(defn flash
"Flash the background color of the first element found with query `q`.
Examples:
=========
(flash \"a.hard-to-see\")"
([q] (flash *driver* q))
([driver q]
(core/flash (element driver q))))
(defn focus
"Explicitly give the first element found with query `q` focus on the page.
Examples:
=========
(focus \"input.next-element\")"
([q] (focus *driver* q))
([driver q]
(core/focus (element driver q))))
(defn html
"Return the inner html of the first element found with query `q`.
Examples:
=========
(html \"div.with-interesting-html\")"
([q] (html *driver* q))
([driver q]
(core/html (element driver q))))
(defn location
"Return a map of `:x` and `:y` coordinates for the first element found with query `q`.
Examples:
=========
(location \"a#foo\") ;=> {:x 240, :y 300}"
([q] (location *driver* q))
([driver q]
(core/location (element driver q))))
(defn location-once-visible
"Return a map of `:x` and `:y` coordinates for the first element found with query `q` once the page has been scrolled enough to be visible in the viewport.
Examples:
=========
(location-once-visible \"a#foo\") ;=> {:x 240, :y 300}"
([q] (location-once-visible *driver* q))
([driver q]
(core/location-once-visible (element driver q))))
(defn present?
"Return true if the first element found with query `q` both exists and is visible on the page.
Examples:
=========
(present? \"div#container\") ;=> true
(present? \"a#skip-to-navigation\") ;=> false"
([q] (present? *driver* q))
([driver q]
(core/present? (element driver q))))
(defn element-size
"Return the size of the first element found with query `q` in pixels as a map of `:width` and `:height`.
Examples:
=========
(size \"div#container\") ;=> {:width 960, :height 2000} "
([q] (element-size *driver* q))
([driver q]
(core/size (element driver q))))
(defn intersects?
"Return true if the first element found with query `qa` intersects with the first element found with query `qb`.
Examples:
=========
(intersect? \"#login\" \"#login_field\") ;=> true
(intersect? \"#login_field\" \"#password\") ;=> false"
([qa qb] (intersects? *driver* qa qb))
([driver qa qb]
(core/intersects? (element driver qa) (element driver qb))))
(defn tag
"Return the HTML tag for the first element found with query `q`.
Examples:
=========
(tag \"#foo\") ;=> \"a\""
([q] (tag *driver* q))
([driver q]
(core/tag (element driver q))))
(defn text
"Return the text within the first element found with query `q`.
Examples:
=========
(text \"#message\") ;=> \"An error occurred.\""
([q] (text *driver* q))
([driver q]
(core/text (element driver q))))
(defn value
"Return the value of the HTML value attribute for the first element found with query `q`. The is identical to `(attribute q :value)`
Examples:
=========
(value \"#my-button\") ;=> \"submit\" "
([q] (value *driver* q))
([driver q]
(core/value (element driver q))))
(defn visible?
"Return true if the first element found with query `q` is visible on the current page in the browser.
Examples:
=========
(visible? \"div#container\") ;=> true
(visible? \"a.hidden\") ;=> false"
([q] (visible? *driver* q))
([driver q]
(core/visible? (element driver q))))
(defn xpath
"Return an absolute XPath path for the first element found with query `q`. NOTE: This function relies on executing JavaScript in the browser, and is therefore not as dependable as other functions.
Examples:
=========
(xpath \"#login_field\") ;=> \"/html/body/div[2]/div/div/form/div[2]/label/input\""
([q] (xpath *driver* q))
([driver q]
(core/xpath (element driver q))))
(defn deselect
"If the first form element found with query `q` is selected, click the element to deselect it. Otherwise, do nothing and just return the element found.
Examples:
=========
(deselect \"input.already-selected\") ;=> click
(deselect \"input.not-selected\") ;=> do nothing"
([q] (deselect *driver* q))
([driver q]
(core/deselect (element driver q))))
(defn enabled?
"Return true if the first form element found with query `q` is enabled (not disabled).
Examples:
=========
(enabled? \"input\") ;=> true
(enabled? \"input[disabled='disabled']\") ;=> false"
([q] (enabled? *driver* q))
([driver q] (core/enabled? (element driver q))))
(defn input-text
"Type the string `s` into the first form element found with query `q`.
Examples:
=========
(input-text \"input#login_field\" \"semperos\")"
([q s] (input-text *driver* q s))
([driver q s]
(core/input-text (element driver q) s)))
(defn submit
"Submit the form that the first form element found with query `q` belongs to (this is equivalent to pressing ENTER in a text field while filling out a form).
Examples:
=========
(submit \"input#password\")"
([q] (submit *driver* q))
([driver q]
(core/submit (element driver q))))
(defn clear
"Clear the contents (the HTML value attribute) of the first form element found with query `q`.
Examples:
=========
(clear \"input.with-default-text\")"
([q] (clear *driver* q))
([driver q]
(core/clear (element driver q))))
(defn select
"If the first form element found with query `q` is not selected, click the element to select it. Otherwise, do nothing and just return the element found.
Examples:
=========
(select \"input.already-selected\") ;=> do nothing
(select \"input.not-selected\") ;=> click"
([q] (select *driver* q))
([driver q]
(core/select (element driver q))))
(defn selected?
"Return true if the first element found with the query `q` is selected (works for radio buttons, checkboxes, and option tags within select lists).
Examples:
=========
(selected? \"input[type='radio'][value='foo']\") ;=> true
(selected? \"option[value='foo']\") ;=> false "
([q] (selected? *driver* q))
([driver q] (core/selected? (element driver q))))
(defn send-keys
"Type the string `s` into the first form element found with query `q`.
Examples:
=========
(input-text \"input#login_field\" \"semperos\")"
([q s] (send-keys *driver* q s))
([driver q s]
(core/send-keys (element driver q) s)))
(defn toggle
"Toggle is a synonym for click. Click the first element found with query `q`.
Examples:
=========
(toggle \"input[type='checkbox'][value='foo']\")"
([q] (toggle *driver* q))
([driver q]
(core/toggle (element driver q))))
(defn options
"Return all option elements within the first select list found with query `q`.
Examples:
=========
(options \"#my-select-list\")"
([q] (options *driver* q))
([driver q]
(core/all-options (element driver q))))
(defn selected-options
"Return all selected option elements within the first select list found with query `q`.
Examples:
=========
(selected-options \"#my-select-list\")"
([q] (selected-options *driver* q))
([driver q]
(core/all-selected-options (element driver q))))
(defn deselect-option
"Deselect the option element matching `attr-val` within the first select list found with query `q`.
The `attr-val` can contain `:index`, `:value`, or `:text` keys to find the target option element. Index is the zero-based order of the option element in the list, value is the value of the HTML value attribute, and text is the visible text of the option element on the page.
Examples:
=========
;;
;; By index, select 3rd option element
;;
(deselect-option \"#my-select-list\" {:index 2})
;;
;; By value of option element
;;
(deselect-option \"#my-select-list\" {:value \"foo\"})
;;
;; By visible text of option element
;;
(deselect-option \"#my-select-list\" {:value \"Foo\"})"
([q attr-val] (deselect-option *driver* q attr-val))
([driver q attr-val]
(core/deselect-option (element driver q) attr-val)))
(defn deselect-all
"Deselect all options within the first select list found with query `q`.
Examples:
=========
(deselect-all \"#my-select-list\")"
([q] (deselect-all *driver* q))
([driver q] (core/deselect-all (element driver q))))
(defn deselect-by-index
"Deselect the option element at index `idx` (zero-based) within the first select list found with query `q`.
Examples:
=========
;;
;; Deselect by index, deselect 2nd element
;;
(deselect-by-index \"#my-select-list\" 1)"
([q idx] (deselect-by-index *driver* q idx))
([driver q idx] (core/deselect-by-index (element driver q) idx)))
(defn deselect-by-text
"Deselect the option element with visible text `text` within the first select list found with query `q`.
Examples:
=========
(deselect-by-text \"#my-select-list\" \"Foo\")"
([q text] (deselect-by-text *driver* q text))
([driver q text]
(core/deselect-by-text (element driver q) text)))
(defn deselect-by-value
"Deselect the option element with `value` within the first select list found with query `q`.
Examples:
=========
(deselect-by-value \"#my-select-list\" \"foo\")"
([q value] (deselect-by-value *driver* q value))
([driver q value]
(core/deselect-by-value (element driver q) value)))
(defn multiple?
"Return true if the first select list found with query `q` allows multiple selections.
Examples:
=========
(multiple? \"select.multiple\") ;=> true
(multiple? \"select.not-multiple\") ;=> false "
([q] (multiple? *driver* q))
([driver q] (core/multiple? (element driver q))))
(defn select-option
"Select the option element matching `attr-val` within the first select list found with query `q`.
The `attr-val` can contain `:index`, `:value`, or `:text` keys to find the target option element. Index is the zero-based order of the option element in the list, value is the value of the HTML value attribute, and text is the visible text of the option element on the page.
Examples:
=========
;;
;; By index, select 3rd option element
;;
(select-option \"#my-select-list\" {:index 2})
;;
;; By value of option element
;;
(select-option \"#my-select-list\" {:value \"foo\"})
;;
;; By visible text of option element
;;
(select-option \"#my-select-list\" {:value \"Foo\"})"
([q attr-val] (select-option *driver* q attr-val))
([driver q attr-val]
(core/select-option (element driver q) attr-val)))
(defn select-all
"Select all options within the first select list found with query `q`.
Examples:
=========
(deselect-all \"#my-select-list\")"
([q] (select-all *driver* q))
([driver q]
(core/select-all (element driver q))))
(defn select-by-index
"Select the option element at index `idx` (zero-based) within the first select list found with query `q`.
Examples:
=========
;;
;; Select by index, select 2nd element
;;
(select-by-index \"#my-select-list\" 1)"
([q idx] (select-by-index *driver* q idx))
([driver q idx]
(core/select-by-index (element driver q) idx)))
(defn select-by-text
"Select the option element with visible text `text` within the first select list found with query `q`.
Examples:
=========
(select-by-text \"#my-select-list\" \"foo\")"
([q text] (select-by-text *driver* q text))
([driver q text]
(core/select-by-text (element driver q) text)))
(defn select-by-value
"Select the option element with `value` within the first select list found with query `q`.
Examples:
=========
(select-by-value \"#my-select-list\" \"foo\")"
([q value] (select-by-value *driver* q value))
([driver q value]
(core/select-by-value (element driver q) value)))
;; Helpers
(defn- quick-fill*
([k v] (quick-fill* k v false))
([k v submit?]
;; shortcuts:
;; v as string => text to input
(let [q k
action (if (string? v)
#(input-text % v)
v)
target-els (elements q)]
(if submit?
(doseq [el target-els]
(action el))
(map action target-els)))))
(defn quick-fill
"A utility for filling out multiple fields in a form in one go. Returns all the affected elements (if you want a list of unique elements, pass the results through the `distinct` function in clojure.core).
`query-action-maps` - a seq of maps of queries to actions (queries find HTML elements, actions are fn's that act on them)
Note that an \"action\" that is just a String will be interpreted as a call to `input-text` with that String for the target text field.
Examples:
=========
(quick-fill {\"#first_name\" \"PI:NAME:<NAME>END_PI\"}
{\"a.foo\" click})"
[& query-action-maps]
(flatten (map (fn [a-map]
(let [[k v] (first a-map)] (quick-fill* k v)))
query-action-maps)))
(defn quick-fill-submit
"A utility for filling out multiple fields in a form in one go. Always returns nil instead of the affected elements, since on submit all of the elements will be void.
`query-action-maps` - a seq of maps of queries to actions (queries find HTML elements, actions are fn's that act on them)
Note that an \"action\" that is just a String will be interpreted as a call to `input-text` with that String for the target text field.
Examples:
=========
(quick-fill {\"#first_name\" \"PI:NAME:<NAME>END_PI\"}
{\"a.foo\" click})"
[& query-action-maps]
(doseq [entry query-action-maps
[k v] entry]
(quick-fill* k v true)))
(defn accept
"Accept an alert popup dialog. Equivalent to pressing its 'Ok' button."
([] (accept *driver*))
([driver] (core/accept driver)))
(defn alert-obj
"Retrieve the underlying Java object used to identify an alert popup dialog. Exposed to allow you to use methods not yet exposed via clj-webdriver's API's."
([] (alert-obj *driver*))
([driver] (core/alert-obj driver)))
(defn alert-text
"Get the text of the alert popup dialog's message."
([] (alert-text *driver*))
([driver] (core/alert-text driver)))
(defn dismiss
"Dismiss the alert popup dialog. Equivalent to pressing its 'Cancel' button."
([] (dismiss *driver*))
([driver] (core/dismiss driver)))
(defn window-position
"Get the position of the top-left corner of the browser's window relative to the top-left corner of your primary display, returned as a map of `:x` and `:y` integers.
Examples:
=========
(window-position)"
([] (window-position *driver*))
([driver] (win/position driver)))
(defn window-reposition
"Move the top-left corner of the browser `:x` pixels to the right and `:y` pixels down from the top-left of your primary display. If you do not provide a coordinate, it's current value for the browser position will not be changed.
Examples:
=========
(window-reposition {:x 25, :y 50})
(window-reposition {:y 50})"
([coordinates-map] (window-reposition *driver* coordinates-map))
([driver {:keys [x y] :as coordinates-map}]
(win/reposition driver coordinates-map)))
(defn window-size
"Get the size of the browser's window in pixels, returned as a map of `:width` and `:height`.
Examples:
=========
(window-size)"
([] (window-size *driver*))
([driver] (win/size driver)))
(defn window-resize
"Resize the browser window to the given `:width` and `:height`. If a dimension is not specified, it's current value for the browser size will not be changed.
Examples:
=========
(window-resize {:width 300 :height 400})
(window-resize {:height 400})"
([dimensions-map] (window-resize *driver* dimensions-map))
([driver {:keys [width height] :as dimensions-map}]
(win/resize driver dimensions-map)))
(defn window-maximize
"Maximize the browser window.
Examples:
=========
(window-maximize)"
([] (window-maximize *driver*))
([driver] (win/maximize driver)))
|
[
{
"context": ";; Copyright (c) 2014, Andrey Antukh\n;; Copyright (c) 2014, Alejandro Gómez\n;; All rig",
"end": 36,
"score": 0.9998753666877747,
"start": 23,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": "ght (c) 2014, Andrey Antukh\n;; Copyright (c) 2014, Alejandro Gómez\n;; All rights reserved.\n;;\n;; Redistribution and ",
"end": 75,
"score": 0.9998589158058167,
"start": 60,
"tag": "NAME",
"value": "Alejandro Gómez"
}
] | src/cljx/cats/monad/state.cljx | pbaille/cats | 0 | ;; Copyright (c) 2014, Andrey Antukh
;; Copyright (c) 2014, Alejandro Gómez
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. 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 AUTHOR ``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 AUTHOR 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 cats.monad.state
"The State Monad."
#+clj
(:require [cats.core :refer [with-monad]])
#+cljs
(:require-macros [cats.core :refer (with-monad)])
(:require [cats.protocols :as proto]
[cats.data :as d]
[cats.core :as m]))
(declare state-monad)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Type constructors and functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftype State [mfn]
proto/Context
(get-context [_] state-monad)
(get-value [_] mfn)
#+clj clojure.lang.IFn
#+cljs cljs.core/IFn
(#+clj invoke #+cljs -invoke [self seed]
(mfn seed)))
(defn state-t
"Transform a simple state-monad function
to State class instance.
State class instance work as simple wrapper
for standard clojure function, just for avoid
extend plain function type of clojure."
[f]
(State. f))
(defn state?
"Check if value s is instance of
State type."
[s]
(instance? State s))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Monad definition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def state-monad
(reify
proto/Functor
(fmap [_ f fv]
(state-t (fn [s]
(let [[v ns] (fv s)]
(d/pair (f v) ns)))))
proto/Monad
(mreturn [_ v]
(state-t (fn [s]
(d/pair v s))))
(mbind [_ self f]
(-> (fn [s]
(let [p (self s)
value (.-fst p)
newstate (.-snd p)]
((f value) newstate)))
(state-t)))
proto/MonadState
(get-state [_]
(state-t (fn [s]
(d/pair s s))))
(put-state [_ newstate]
(state-t (fn [s]
(d/pair s newstate))))
(swap-state [_ f]
(-> (fn [s]
(d/pair s (f s)))
(state-t)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Monad transformer definition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn state-transformer [inner-monad]
(reify
proto/Functor
(fmap [_ f fv]
(state-t (fn [s]
(let [wr (fv s)]
(proto/fmap inner-monad
(fn [[v ns]]
(d/pair (f v) ns))
wr)))))
proto/Monad
(mreturn [_ v]
(state-t (fn [s]
(proto/mreturn inner-monad
(d/pair v s)))))
(mbind [_ self f]
(-> (fn [s]
(let [mp (self s)]
(proto/mbind inner-monad
mp
(fn [[v ns]]
((f v) ns)))))
(state-t)))
; FIXME: Conditionally if `inner-monad` is MonadZero
proto/MonadZero
(mzero [_]
(-> (fn [s]
(proto/mzero inner-monad))
(state-t)))
; FIXME: Conditionally if `inner-monad` is MonadPlus
proto/MonadPlus
(mplus [_ mv mv']
(-> (fn [s]
(proto/mplus inner-monad (mv s) (mv' s)))
(state-t)))
proto/MonadState
(get-state [_]
(state-t (fn [s]
(proto/mreturn inner-monad
(d/pair s s)))))
(put-state [_ newstate]
(state-t (fn [s]
(proto/mreturn inner-monad
(d/pair s newstate)))))
(swap-state [_ f]
(-> (fn [s]
(proto/mreturn inner-monad
(d/pair s (f s))))
(state-t)))
proto/MonadTrans
(base [_]
state-monad)
(inner [_]
inner-monad)
(lift [_ mv]
(state-t (fn [s]
(proto/mbind inner-monad
mv
(fn [v]
(proto/mreturn inner-monad
(d/pair v s)))))))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; State monad functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-state
"Return a State instance with computation that returns
the current state."
[]
(proto/get-state (m/get-current-context-or state-monad)))
(defn put-state
"Return a State instance with computation that replaces
the current state with specified new state."
[newstate]
(proto/put-state (m/get-current-context-or state-monad) newstate))
(defn swap-state
"Return a State instance with computation that applies the
specified function to state and returns the old state."
[f]
(proto/swap-state (m/get-current-context-or state-monad) f))
(defn run-state
"Given a State instance, execute the
wrapped computation and returns a cats.data.Pair
instance with result and new state.
(def computation (mlet [x (get-state)
y (put-state (inc x))]
(return y)))
(def initial-state 1)
(run-state computation initial-state)
This should be return something to: #<Pair [1 2]>"
[state seed]
(with-monad (m/get-current-context-or state-monad)
(state seed)))
(defn eval-state
"Given a State instance, execute the
wrapped computation and return the resultant
value, ignoring the state.
Equivalent to taking the first value of the pair instance
returned by `run-state` function."
[state seed]
(first (run-state state seed)))
(defn exec-state
"Given a State instance, execute the
wrapped computation and return the resultant
state.
Equivalent to taking the second value of the pair instance
returned by `run-state` function."
[state seed]
(second (run-state state seed)))
| 51820 | ;; Copyright (c) 2014, <NAME>
;; Copyright (c) 2014, <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:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. 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 AUTHOR ``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 AUTHOR 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 cats.monad.state
"The State Monad."
#+clj
(:require [cats.core :refer [with-monad]])
#+cljs
(:require-macros [cats.core :refer (with-monad)])
(:require [cats.protocols :as proto]
[cats.data :as d]
[cats.core :as m]))
(declare state-monad)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Type constructors and functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftype State [mfn]
proto/Context
(get-context [_] state-monad)
(get-value [_] mfn)
#+clj clojure.lang.IFn
#+cljs cljs.core/IFn
(#+clj invoke #+cljs -invoke [self seed]
(mfn seed)))
(defn state-t
"Transform a simple state-monad function
to State class instance.
State class instance work as simple wrapper
for standard clojure function, just for avoid
extend plain function type of clojure."
[f]
(State. f))
(defn state?
"Check if value s is instance of
State type."
[s]
(instance? State s))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Monad definition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def state-monad
(reify
proto/Functor
(fmap [_ f fv]
(state-t (fn [s]
(let [[v ns] (fv s)]
(d/pair (f v) ns)))))
proto/Monad
(mreturn [_ v]
(state-t (fn [s]
(d/pair v s))))
(mbind [_ self f]
(-> (fn [s]
(let [p (self s)
value (.-fst p)
newstate (.-snd p)]
((f value) newstate)))
(state-t)))
proto/MonadState
(get-state [_]
(state-t (fn [s]
(d/pair s s))))
(put-state [_ newstate]
(state-t (fn [s]
(d/pair s newstate))))
(swap-state [_ f]
(-> (fn [s]
(d/pair s (f s)))
(state-t)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Monad transformer definition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn state-transformer [inner-monad]
(reify
proto/Functor
(fmap [_ f fv]
(state-t (fn [s]
(let [wr (fv s)]
(proto/fmap inner-monad
(fn [[v ns]]
(d/pair (f v) ns))
wr)))))
proto/Monad
(mreturn [_ v]
(state-t (fn [s]
(proto/mreturn inner-monad
(d/pair v s)))))
(mbind [_ self f]
(-> (fn [s]
(let [mp (self s)]
(proto/mbind inner-monad
mp
(fn [[v ns]]
((f v) ns)))))
(state-t)))
; FIXME: Conditionally if `inner-monad` is MonadZero
proto/MonadZero
(mzero [_]
(-> (fn [s]
(proto/mzero inner-monad))
(state-t)))
; FIXME: Conditionally if `inner-monad` is MonadPlus
proto/MonadPlus
(mplus [_ mv mv']
(-> (fn [s]
(proto/mplus inner-monad (mv s) (mv' s)))
(state-t)))
proto/MonadState
(get-state [_]
(state-t (fn [s]
(proto/mreturn inner-monad
(d/pair s s)))))
(put-state [_ newstate]
(state-t (fn [s]
(proto/mreturn inner-monad
(d/pair s newstate)))))
(swap-state [_ f]
(-> (fn [s]
(proto/mreturn inner-monad
(d/pair s (f s))))
(state-t)))
proto/MonadTrans
(base [_]
state-monad)
(inner [_]
inner-monad)
(lift [_ mv]
(state-t (fn [s]
(proto/mbind inner-monad
mv
(fn [v]
(proto/mreturn inner-monad
(d/pair v s)))))))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; State monad functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-state
"Return a State instance with computation that returns
the current state."
[]
(proto/get-state (m/get-current-context-or state-monad)))
(defn put-state
"Return a State instance with computation that replaces
the current state with specified new state."
[newstate]
(proto/put-state (m/get-current-context-or state-monad) newstate))
(defn swap-state
"Return a State instance with computation that applies the
specified function to state and returns the old state."
[f]
(proto/swap-state (m/get-current-context-or state-monad) f))
(defn run-state
"Given a State instance, execute the
wrapped computation and returns a cats.data.Pair
instance with result and new state.
(def computation (mlet [x (get-state)
y (put-state (inc x))]
(return y)))
(def initial-state 1)
(run-state computation initial-state)
This should be return something to: #<Pair [1 2]>"
[state seed]
(with-monad (m/get-current-context-or state-monad)
(state seed)))
(defn eval-state
"Given a State instance, execute the
wrapped computation and return the resultant
value, ignoring the state.
Equivalent to taking the first value of the pair instance
returned by `run-state` function."
[state seed]
(first (run-state state seed)))
(defn exec-state
"Given a State instance, execute the
wrapped computation and return the resultant
state.
Equivalent to taking the second value of the pair instance
returned by `run-state` function."
[state seed]
(second (run-state state seed)))
| true | ;; Copyright (c) 2014, PI:NAME:<NAME>END_PI
;; Copyright (c) 2014, 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:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. 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 AUTHOR ``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 AUTHOR 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 cats.monad.state
"The State Monad."
#+clj
(:require [cats.core :refer [with-monad]])
#+cljs
(:require-macros [cats.core :refer (with-monad)])
(:require [cats.protocols :as proto]
[cats.data :as d]
[cats.core :as m]))
(declare state-monad)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Type constructors and functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftype State [mfn]
proto/Context
(get-context [_] state-monad)
(get-value [_] mfn)
#+clj clojure.lang.IFn
#+cljs cljs.core/IFn
(#+clj invoke #+cljs -invoke [self seed]
(mfn seed)))
(defn state-t
"Transform a simple state-monad function
to State class instance.
State class instance work as simple wrapper
for standard clojure function, just for avoid
extend plain function type of clojure."
[f]
(State. f))
(defn state?
"Check if value s is instance of
State type."
[s]
(instance? State s))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Monad definition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def state-monad
(reify
proto/Functor
(fmap [_ f fv]
(state-t (fn [s]
(let [[v ns] (fv s)]
(d/pair (f v) ns)))))
proto/Monad
(mreturn [_ v]
(state-t (fn [s]
(d/pair v s))))
(mbind [_ self f]
(-> (fn [s]
(let [p (self s)
value (.-fst p)
newstate (.-snd p)]
((f value) newstate)))
(state-t)))
proto/MonadState
(get-state [_]
(state-t (fn [s]
(d/pair s s))))
(put-state [_ newstate]
(state-t (fn [s]
(d/pair s newstate))))
(swap-state [_ f]
(-> (fn [s]
(d/pair s (f s)))
(state-t)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Monad transformer definition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn state-transformer [inner-monad]
(reify
proto/Functor
(fmap [_ f fv]
(state-t (fn [s]
(let [wr (fv s)]
(proto/fmap inner-monad
(fn [[v ns]]
(d/pair (f v) ns))
wr)))))
proto/Monad
(mreturn [_ v]
(state-t (fn [s]
(proto/mreturn inner-monad
(d/pair v s)))))
(mbind [_ self f]
(-> (fn [s]
(let [mp (self s)]
(proto/mbind inner-monad
mp
(fn [[v ns]]
((f v) ns)))))
(state-t)))
; FIXME: Conditionally if `inner-monad` is MonadZero
proto/MonadZero
(mzero [_]
(-> (fn [s]
(proto/mzero inner-monad))
(state-t)))
; FIXME: Conditionally if `inner-monad` is MonadPlus
proto/MonadPlus
(mplus [_ mv mv']
(-> (fn [s]
(proto/mplus inner-monad (mv s) (mv' s)))
(state-t)))
proto/MonadState
(get-state [_]
(state-t (fn [s]
(proto/mreturn inner-monad
(d/pair s s)))))
(put-state [_ newstate]
(state-t (fn [s]
(proto/mreturn inner-monad
(d/pair s newstate)))))
(swap-state [_ f]
(-> (fn [s]
(proto/mreturn inner-monad
(d/pair s (f s))))
(state-t)))
proto/MonadTrans
(base [_]
state-monad)
(inner [_]
inner-monad)
(lift [_ mv]
(state-t (fn [s]
(proto/mbind inner-monad
mv
(fn [v]
(proto/mreturn inner-monad
(d/pair v s)))))))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; State monad functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-state
"Return a State instance with computation that returns
the current state."
[]
(proto/get-state (m/get-current-context-or state-monad)))
(defn put-state
"Return a State instance with computation that replaces
the current state with specified new state."
[newstate]
(proto/put-state (m/get-current-context-or state-monad) newstate))
(defn swap-state
"Return a State instance with computation that applies the
specified function to state and returns the old state."
[f]
(proto/swap-state (m/get-current-context-or state-monad) f))
(defn run-state
"Given a State instance, execute the
wrapped computation and returns a cats.data.Pair
instance with result and new state.
(def computation (mlet [x (get-state)
y (put-state (inc x))]
(return y)))
(def initial-state 1)
(run-state computation initial-state)
This should be return something to: #<Pair [1 2]>"
[state seed]
(with-monad (m/get-current-context-or state-monad)
(state seed)))
(defn eval-state
"Given a State instance, execute the
wrapped computation and return the resultant
value, ignoring the state.
Equivalent to taking the first value of the pair instance
returned by `run-state` function."
[state seed]
(first (run-state state seed)))
(defn exec-state
"Given a State instance, execute the
wrapped computation and return the resultant
state.
Equivalent to taking the second value of the pair instance
returned by `run-state` function."
[state seed]
(second (run-state state seed)))
|
[
{
"context": "by name\"\n (is (ffirst (q/person-by-email db \"jenkins@mailinator.com\")))\n (is (= (q/pull-by-email db \"mcnugget@ma",
"end": 386,
"score": 0.9999276995658875,
"start": 364,
"tag": "EMAIL",
"value": "jenkins@mailinator.com"
},
{
"context": "linator.com\")))\n (is (= (q/pull-by-email db \"mcnugget@mailinator.com\")\n #:person {:email \"mcnugget@ma",
"end": 448,
"score": 0.9999269843101501,
"start": 425,
"tag": "EMAIL",
"value": "mcnugget@mailinator.com"
},
{
"context": "linator.com\")\n #:person {:email \"mcnugget@mailinator.com\"\n :first-name \"JSON\"\n ",
"end": 510,
"score": 0.9999312162399292,
"start": 487,
"tag": "EMAIL",
"value": "mcnugget@mailinator.com"
},
{
"context": "ilinator.com\"\n :first-name \"JSON\"\n :last-name \"McNugget\"}))",
"end": 552,
"score": 0.9990079998970032,
"start": 548,
"tag": "NAME",
"value": "JSON"
},
{
"context": "t-name \"JSON\"\n :last-name \"McNugget\"})))))",
"end": 598,
"score": 0.99981689453125,
"start": 590,
"tag": "NAME",
"value": "McNugget"
}
] | test/examples/query_test.clj | zilvinasu/datomic-presentation | 1 | (ns examples.query-test
(:require
[clojure.test :refer :all]
[examples.query :refer [pull-by-uuid]]
[examples.db :as db]
[examples.query :as q]
[examples.fixtures :refer [with-db]]))
(use-fixtures :each with-db)
(deftest query-api-test
(let [db (db/current-db)]
(testing "find person by name"
(is (ffirst (q/person-by-email db "jenkins@mailinator.com")))
(is (= (q/pull-by-email db "mcnugget@mailinator.com")
#:person {:email "mcnugget@mailinator.com"
:first-name "JSON"
:last-name "McNugget"}))))) | 11666 | (ns examples.query-test
(:require
[clojure.test :refer :all]
[examples.query :refer [pull-by-uuid]]
[examples.db :as db]
[examples.query :as q]
[examples.fixtures :refer [with-db]]))
(use-fixtures :each with-db)
(deftest query-api-test
(let [db (db/current-db)]
(testing "find person by name"
(is (ffirst (q/person-by-email db "<EMAIL>")))
(is (= (q/pull-by-email db "<EMAIL>")
#:person {:email "<EMAIL>"
:first-name "<NAME>"
:last-name "<NAME>"}))))) | true | (ns examples.query-test
(:require
[clojure.test :refer :all]
[examples.query :refer [pull-by-uuid]]
[examples.db :as db]
[examples.query :as q]
[examples.fixtures :refer [with-db]]))
(use-fixtures :each with-db)
(deftest query-api-test
(let [db (db/current-db)]
(testing "find person by name"
(is (ffirst (q/person-by-email db "PI:EMAIL:<EMAIL>END_PI")))
(is (= (q/pull-by-email db "PI:EMAIL:<EMAIL>END_PI")
#:person {:email "PI:EMAIL:<EMAIL>END_PI"
:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}))))) |
[
{
"context": "s\n {:atom atom-or-opts})\n\n key (java.util.UUID/randomUUID)\n listeners (atom #{})\n update! (",
"end": 1171,
"score": 0.9923585057258606,
"start": 1146,
"tag": "KEY",
"value": "java.util.UUID/randomUUID"
}
] | src/ripley/live/atom.clj | jcpsantiago/ripley | 188 | (ns ripley.live.atom
"Live component that tracks an atom's value"
(:require [ripley.live.protocols :as p]
[clojure.core.async :as async :refer [go >!! >!]]
[taoensso.timbre :as log]))
(defrecord AtomSource [input-atom process-value key listeners]
p/Source
(current-value [_] (process-value @input-atom))
(listen! [_ listener]
(swap! listeners conj listener)
#(swap! listeners disj listener))
(close! [_]
(reset! listeners #{})
(remove-watch input-atom key))
p/Writable
(write! [_ new-value]
(reset! input-atom new-value))
Object
(toString [_]
(str "#<atom-source val: " @input-atom
", " (count @listeners) " listeners>")))
(defn atom-source
"Create a source that tracks changes made to the given atom.
The source will return the same channel on each call to to-channel
so the same source can't be used for multiple live components."
([atom-or-opts]
(let [{input-atom :atom
:keys [process-value label]
:or {process-value identity}}
(if (map? atom-or-opts)
atom-or-opts
{:atom atom-or-opts})
key (java.util.UUID/randomUUID)
listeners (atom #{})
update! (fn [old-value new-value]
(let [old (process-value old-value)
new (process-value new-value)]
(when (not= old new)
(doseq [listener @listeners]
(listener new)))))]
(add-watch input-atom key
(fn [_ _ old-value new-value]
(when (not= old-value new-value)
(when label
(log/debug label "atom-source changed, v:" new-value))
(update! old-value new-value))))
(->AtomSource input-atom process-value key listeners)))
([atom process-value]
(atom-source {:atom atom
:process-value process-value})))
| 36095 | (ns ripley.live.atom
"Live component that tracks an atom's value"
(:require [ripley.live.protocols :as p]
[clojure.core.async :as async :refer [go >!! >!]]
[taoensso.timbre :as log]))
(defrecord AtomSource [input-atom process-value key listeners]
p/Source
(current-value [_] (process-value @input-atom))
(listen! [_ listener]
(swap! listeners conj listener)
#(swap! listeners disj listener))
(close! [_]
(reset! listeners #{})
(remove-watch input-atom key))
p/Writable
(write! [_ new-value]
(reset! input-atom new-value))
Object
(toString [_]
(str "#<atom-source val: " @input-atom
", " (count @listeners) " listeners>")))
(defn atom-source
"Create a source that tracks changes made to the given atom.
The source will return the same channel on each call to to-channel
so the same source can't be used for multiple live components."
([atom-or-opts]
(let [{input-atom :atom
:keys [process-value label]
:or {process-value identity}}
(if (map? atom-or-opts)
atom-or-opts
{:atom atom-or-opts})
key (<KEY>)
listeners (atom #{})
update! (fn [old-value new-value]
(let [old (process-value old-value)
new (process-value new-value)]
(when (not= old new)
(doseq [listener @listeners]
(listener new)))))]
(add-watch input-atom key
(fn [_ _ old-value new-value]
(when (not= old-value new-value)
(when label
(log/debug label "atom-source changed, v:" new-value))
(update! old-value new-value))))
(->AtomSource input-atom process-value key listeners)))
([atom process-value]
(atom-source {:atom atom
:process-value process-value})))
| true | (ns ripley.live.atom
"Live component that tracks an atom's value"
(:require [ripley.live.protocols :as p]
[clojure.core.async :as async :refer [go >!! >!]]
[taoensso.timbre :as log]))
(defrecord AtomSource [input-atom process-value key listeners]
p/Source
(current-value [_] (process-value @input-atom))
(listen! [_ listener]
(swap! listeners conj listener)
#(swap! listeners disj listener))
(close! [_]
(reset! listeners #{})
(remove-watch input-atom key))
p/Writable
(write! [_ new-value]
(reset! input-atom new-value))
Object
(toString [_]
(str "#<atom-source val: " @input-atom
", " (count @listeners) " listeners>")))
(defn atom-source
"Create a source that tracks changes made to the given atom.
The source will return the same channel on each call to to-channel
so the same source can't be used for multiple live components."
([atom-or-opts]
(let [{input-atom :atom
:keys [process-value label]
:or {process-value identity}}
(if (map? atom-or-opts)
atom-or-opts
{:atom atom-or-opts})
key (PI:KEY:<KEY>END_PI)
listeners (atom #{})
update! (fn [old-value new-value]
(let [old (process-value old-value)
new (process-value new-value)]
(when (not= old new)
(doseq [listener @listeners]
(listener new)))))]
(add-watch input-atom key
(fn [_ _ old-value new-value]
(when (not= old-value new-value)
(when label
(log/debug label "atom-source changed, v:" new-value))
(update! old-value new-value))))
(->AtomSource input-atom process-value key listeners)))
([atom process-value]
(atom-source {:atom atom
:process-value process-value})))
|
[
{
"context": ";; Copyright © 2015-2022 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.9998852610588074,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
},
{
"context": "pe command)))\n\n(def ^:private data-keys\n [:region/name\n :region/location])\n\n(defmethod command-handler",
"end": 1629,
"score": 0.8131369352340698,
"start": 1625,
"tag": "KEY",
"value": "name"
},
{
"context": "def ^:private data-keys\n [:region/name\n :region/location])\n\n(defmethod command-handler :region.com",
"end": 1640,
"score": 0.6710801124572754,
"start": 1640,
"tag": "KEY",
"value": ""
}
] | src/territory_bro/domain/region.clj | 3breadt/territory-bro | 0 | ;; Copyright © 2015-2022 Esko Luontola
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.domain.region
(:require [medley.core :refer [dissoc-in]]
[territory-bro.gis.gis-change :as gis-change])
(:import (territory_bro ValidationException)))
;;;; Read model
(defmulti projection (fn [_state event]
(:event/type event)))
(defmethod projection :default [state _event]
state)
(defmethod projection :region.event/region-defined
[state event]
(update-in state [::regions (:congregation/id event) (:region/id event)]
(fn [region]
(-> region
(assoc :region/id (:region/id event))
(assoc :region/name (:region/name event))
(assoc :region/location (:region/location event))))))
(defmethod projection :region.event/region-deleted
[state event]
(dissoc-in state [::regions (:congregation/id event) (:region/id event)]))
;;;; Queries
(defn check-region-exists [state cong-id region-id]
(when (nil? (get-in state [::regions cong-id region-id]))
(throw (ValidationException. [[:no-such-region cong-id region-id]]))))
;;;; Write model
(defn- write-model [command events]
(let [state (reduce projection nil events)]
(get-in state [::regions (:congregation/id command) (:region/id command)])))
;;;; Command handlers
(defmulti ^:private command-handler (fn [command _region _injections]
(:command/type command)))
(def ^:private data-keys
[:region/name
:region/location])
(defmethod command-handler :region.command/define-region
[command region {:keys [check-permit]}]
(let [cong-id (:congregation/id command)
region-id (:region/id command)]
(check-permit [:create-region cong-id])
(when (nil? region)
[(merge {:event/type :region.event/region-defined
:congregation/id cong-id
:region/id region-id}
(gis-change/event-metadata command)
(select-keys command data-keys))])))
(defmethod command-handler :region.command/update-region
[command region {:keys [check-permit]}]
(let [cong-id (:congregation/id command)
region-id (:region/id command)
old-data (select-keys region data-keys)
new-data (select-keys command data-keys)]
(check-permit [:update-region cong-id region-id])
(when (not= old-data new-data)
[(merge {:event/type :region.event/region-defined
:congregation/id cong-id
:region/id region-id}
(gis-change/event-metadata command)
new-data)])))
(defmethod command-handler :region.command/delete-region
[command region {:keys [check-permit]}]
(let [cong-id (:congregation/id command)
region-id (:region/id command)]
(check-permit [:delete-region cong-id region-id])
(when (some? region)
[(merge {:event/type :region.event/region-deleted
:congregation/id cong-id
:region/id region-id}
(gis-change/event-metadata command))])))
(defn handle-command [command events injections]
(command-handler command (write-model command events) injections))
| 94387 | ;; Copyright © 2015-2022 <NAME>
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.domain.region
(:require [medley.core :refer [dissoc-in]]
[territory-bro.gis.gis-change :as gis-change])
(:import (territory_bro ValidationException)))
;;;; Read model
(defmulti projection (fn [_state event]
(:event/type event)))
(defmethod projection :default [state _event]
state)
(defmethod projection :region.event/region-defined
[state event]
(update-in state [::regions (:congregation/id event) (:region/id event)]
(fn [region]
(-> region
(assoc :region/id (:region/id event))
(assoc :region/name (:region/name event))
(assoc :region/location (:region/location event))))))
(defmethod projection :region.event/region-deleted
[state event]
(dissoc-in state [::regions (:congregation/id event) (:region/id event)]))
;;;; Queries
(defn check-region-exists [state cong-id region-id]
(when (nil? (get-in state [::regions cong-id region-id]))
(throw (ValidationException. [[:no-such-region cong-id region-id]]))))
;;;; Write model
(defn- write-model [command events]
(let [state (reduce projection nil events)]
(get-in state [::regions (:congregation/id command) (:region/id command)])))
;;;; Command handlers
(defmulti ^:private command-handler (fn [command _region _injections]
(:command/type command)))
(def ^:private data-keys
[:region/<KEY>
:region<KEY>/location])
(defmethod command-handler :region.command/define-region
[command region {:keys [check-permit]}]
(let [cong-id (:congregation/id command)
region-id (:region/id command)]
(check-permit [:create-region cong-id])
(when (nil? region)
[(merge {:event/type :region.event/region-defined
:congregation/id cong-id
:region/id region-id}
(gis-change/event-metadata command)
(select-keys command data-keys))])))
(defmethod command-handler :region.command/update-region
[command region {:keys [check-permit]}]
(let [cong-id (:congregation/id command)
region-id (:region/id command)
old-data (select-keys region data-keys)
new-data (select-keys command data-keys)]
(check-permit [:update-region cong-id region-id])
(when (not= old-data new-data)
[(merge {:event/type :region.event/region-defined
:congregation/id cong-id
:region/id region-id}
(gis-change/event-metadata command)
new-data)])))
(defmethod command-handler :region.command/delete-region
[command region {:keys [check-permit]}]
(let [cong-id (:congregation/id command)
region-id (:region/id command)]
(check-permit [:delete-region cong-id region-id])
(when (some? region)
[(merge {:event/type :region.event/region-deleted
:congregation/id cong-id
:region/id region-id}
(gis-change/event-metadata command))])))
(defn handle-command [command events injections]
(command-handler command (write-model command events) injections))
| true | ;; Copyright © 2015-2022 PI:NAME:<NAME>END_PI
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.domain.region
(:require [medley.core :refer [dissoc-in]]
[territory-bro.gis.gis-change :as gis-change])
(:import (territory_bro ValidationException)))
;;;; Read model
(defmulti projection (fn [_state event]
(:event/type event)))
(defmethod projection :default [state _event]
state)
(defmethod projection :region.event/region-defined
[state event]
(update-in state [::regions (:congregation/id event) (:region/id event)]
(fn [region]
(-> region
(assoc :region/id (:region/id event))
(assoc :region/name (:region/name event))
(assoc :region/location (:region/location event))))))
(defmethod projection :region.event/region-deleted
[state event]
(dissoc-in state [::regions (:congregation/id event) (:region/id event)]))
;;;; Queries
(defn check-region-exists [state cong-id region-id]
(when (nil? (get-in state [::regions cong-id region-id]))
(throw (ValidationException. [[:no-such-region cong-id region-id]]))))
;;;; Write model
(defn- write-model [command events]
(let [state (reduce projection nil events)]
(get-in state [::regions (:congregation/id command) (:region/id command)])))
;;;; Command handlers
(defmulti ^:private command-handler (fn [command _region _injections]
(:command/type command)))
(def ^:private data-keys
[:region/PI:KEY:<KEY>END_PI
:regionPI:KEY:<KEY>END_PI/location])
(defmethod command-handler :region.command/define-region
[command region {:keys [check-permit]}]
(let [cong-id (:congregation/id command)
region-id (:region/id command)]
(check-permit [:create-region cong-id])
(when (nil? region)
[(merge {:event/type :region.event/region-defined
:congregation/id cong-id
:region/id region-id}
(gis-change/event-metadata command)
(select-keys command data-keys))])))
(defmethod command-handler :region.command/update-region
[command region {:keys [check-permit]}]
(let [cong-id (:congregation/id command)
region-id (:region/id command)
old-data (select-keys region data-keys)
new-data (select-keys command data-keys)]
(check-permit [:update-region cong-id region-id])
(when (not= old-data new-data)
[(merge {:event/type :region.event/region-defined
:congregation/id cong-id
:region/id region-id}
(gis-change/event-metadata command)
new-data)])))
(defmethod command-handler :region.command/delete-region
[command region {:keys [check-permit]}]
(let [cong-id (:congregation/id command)
region-id (:region/id command)]
(check-permit [:delete-region cong-id region-id])
(when (some? region)
[(merge {:event/type :region.event/region-deleted
:congregation/id cong-id
:region/id region-id}
(gis-change/event-metadata command))])))
(defn handle-command [command events injections]
(command-handler command (write-model command events) injections))
|
[
{
"context": "TRUST_STORE_PASSWORD\")\n \"changeit\"))\n (System/setProperty \"javax.net.ssl.keyStore\"",
"end": 4160,
"score": 0.9982309341430664,
"start": 4152,
"tag": "PASSWORD",
"value": "changeit"
},
{
"context": " \"KEY_STORE_PASSWORD\")\n \"somepass\"))\n (component/start-system\n (make-spacon-serv",
"end": 4617,
"score": 0.9990116357803345,
"start": 4609,
"tag": "PASSWORD",
"value": "somepass"
}
] | server/src/spacon/server.clj | martinwilkerson-scisys/spatialconnect-server | 1 | ;; Copyright 2016-2017 Boundless, http://boundlessgeo.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 spacon.server
(:gen-class) ; for -main method in uberjar
(:require [io.pedestal.http :as server]
[spacon.components.http.core :as http]
[com.stuartsierra.component :as component]
[spacon.components.ping.core :as ping]
[spacon.components.user.core :as user]
[spacon.components.team.core :as team]
[spacon.components.device.core :as device]
[spacon.components.config.core :as config]
[spacon.components.store.core :as store]
[spacon.components.location.core :as location]
[spacon.components.mqtt.core :as mqtt]
[spacon.components.notification.core :as notification]
[spacon.components.form.core :as form]
[spacon.components.kafka.core :as kafka]
[clojure.tools.logging :as log]))
(defrecord SpaconServer [http-service]
component/Lifecycle
(start [component]
(log/info "Starting SpaconServer Component")
(let [server (server/create-server (:service-def http-service))]
(server/start server)
(assoc component :http-server server)))
(stop [component]
(log/info "Stopping SpaconServer Component")
(update-in component [:http-server] server/stop)))
(defn new-spacon-server []
(map->SpaconServer {}))
(defn make-spacon-server
"Returns a new instance of the system"
[config-options]
(log/debug "Making server config with these options" config-options)
(let [{:keys [http-config mqtt-config kafka-producer-config kafka-consumer-config]} config-options]
(component/system-map
:user (user/make-user-component)
:team (team/make-team-component)
:mqtt (mqtt/make-mqtt-component mqtt-config)
:kafka (kafka/make-kafka-component kafka-producer-config kafka-consumer-config)
:ping (component/using (ping/make-ping-component) [:mqtt :kafka])
:device (component/using (device/make-device-component) [:mqtt])
:config (component/using (config/make-config-component) [:mqtt])
:notify (component/using (notification/make-notification-component) [:mqtt])
:store (component/using (store/make-store-component) [:mqtt])
:location (component/using (location/make-location-component) [:mqtt])
:form (component/using (form/make-form-component) [:mqtt])
:http-service (component/using
(http/make-http-service-component http-config)
[:ping :user :team :device :location
:store :config :form :mqtt :notify])
:server (component/using (new-spacon-server) [:http-service]))))
(defn -main
"The entry-point for 'lein run'"
[& _]
(log/info "Configuring the server...")
(if (= "true" (System/getenv "AUTO_MIGRATE"))
(spacon.db.conn/migrate))
;; create global uncaught exception handler so threads don't silently die
(Thread/setDefaultUncaughtExceptionHandler
(reify Thread$UncaughtExceptionHandler
(uncaughtException [_ thread ex]
(log/error ex "Uncaught exception on thread" (.getName thread)))))
(System/setProperty "javax.net.ssl.trustStore"
(or (System/getenv "TRUST_STORE")
"tls/test-cacerts.jks"))
(System/setProperty "javax.net.ssl.trustStoreType"
(or (System/getenv "TRUST_STORE_TYPE")
"JKS"))
(System/setProperty "javax.net.ssl.trustStorePassword"
(or (System/getenv "TRUST_STORE_PASSWORD")
"changeit"))
(System/setProperty "javax.net.ssl.keyStore"
(or (System/getenv "KEY_STORE")
"tls/test-keystore.p12"))
(System/setProperty "javax.net.ssl.keyStoreType"
(or (System/getenv "KEY_STORE_TYPE")
"pkcs12"))
(System/setProperty "javax.net.ssl.keyStorePassword"
(or (System/getenv "KEY_STORE_PASSWORD")
"somepass"))
(component/start-system
(make-spacon-server {:http-config {::server/allowed-origins {:allowed-origins [(System/getenv "ALLOWED_ORIGINS")]}}
:mqtt-config {:broker-url (System/getenv "MQTT_BROKER_URL")}
:kafka-producer-config {:servers (System/getenv "BOOTSTRAP_SERVERS")
:timeout-ms 2000}
:kafka-consumer-config {:servers (System/getenv "BOOTSTRAP_SERVERS")
:group-id (System/getenv "GROUP_ID")}})))
| 113309 | ;; Copyright 2016-2017 Boundless, http://boundlessgeo.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 spacon.server
(:gen-class) ; for -main method in uberjar
(:require [io.pedestal.http :as server]
[spacon.components.http.core :as http]
[com.stuartsierra.component :as component]
[spacon.components.ping.core :as ping]
[spacon.components.user.core :as user]
[spacon.components.team.core :as team]
[spacon.components.device.core :as device]
[spacon.components.config.core :as config]
[spacon.components.store.core :as store]
[spacon.components.location.core :as location]
[spacon.components.mqtt.core :as mqtt]
[spacon.components.notification.core :as notification]
[spacon.components.form.core :as form]
[spacon.components.kafka.core :as kafka]
[clojure.tools.logging :as log]))
(defrecord SpaconServer [http-service]
component/Lifecycle
(start [component]
(log/info "Starting SpaconServer Component")
(let [server (server/create-server (:service-def http-service))]
(server/start server)
(assoc component :http-server server)))
(stop [component]
(log/info "Stopping SpaconServer Component")
(update-in component [:http-server] server/stop)))
(defn new-spacon-server []
(map->SpaconServer {}))
(defn make-spacon-server
"Returns a new instance of the system"
[config-options]
(log/debug "Making server config with these options" config-options)
(let [{:keys [http-config mqtt-config kafka-producer-config kafka-consumer-config]} config-options]
(component/system-map
:user (user/make-user-component)
:team (team/make-team-component)
:mqtt (mqtt/make-mqtt-component mqtt-config)
:kafka (kafka/make-kafka-component kafka-producer-config kafka-consumer-config)
:ping (component/using (ping/make-ping-component) [:mqtt :kafka])
:device (component/using (device/make-device-component) [:mqtt])
:config (component/using (config/make-config-component) [:mqtt])
:notify (component/using (notification/make-notification-component) [:mqtt])
:store (component/using (store/make-store-component) [:mqtt])
:location (component/using (location/make-location-component) [:mqtt])
:form (component/using (form/make-form-component) [:mqtt])
:http-service (component/using
(http/make-http-service-component http-config)
[:ping :user :team :device :location
:store :config :form :mqtt :notify])
:server (component/using (new-spacon-server) [:http-service]))))
(defn -main
"The entry-point for 'lein run'"
[& _]
(log/info "Configuring the server...")
(if (= "true" (System/getenv "AUTO_MIGRATE"))
(spacon.db.conn/migrate))
;; create global uncaught exception handler so threads don't silently die
(Thread/setDefaultUncaughtExceptionHandler
(reify Thread$UncaughtExceptionHandler
(uncaughtException [_ thread ex]
(log/error ex "Uncaught exception on thread" (.getName thread)))))
(System/setProperty "javax.net.ssl.trustStore"
(or (System/getenv "TRUST_STORE")
"tls/test-cacerts.jks"))
(System/setProperty "javax.net.ssl.trustStoreType"
(or (System/getenv "TRUST_STORE_TYPE")
"JKS"))
(System/setProperty "javax.net.ssl.trustStorePassword"
(or (System/getenv "TRUST_STORE_PASSWORD")
"<PASSWORD>"))
(System/setProperty "javax.net.ssl.keyStore"
(or (System/getenv "KEY_STORE")
"tls/test-keystore.p12"))
(System/setProperty "javax.net.ssl.keyStoreType"
(or (System/getenv "KEY_STORE_TYPE")
"pkcs12"))
(System/setProperty "javax.net.ssl.keyStorePassword"
(or (System/getenv "KEY_STORE_PASSWORD")
"<PASSWORD>"))
(component/start-system
(make-spacon-server {:http-config {::server/allowed-origins {:allowed-origins [(System/getenv "ALLOWED_ORIGINS")]}}
:mqtt-config {:broker-url (System/getenv "MQTT_BROKER_URL")}
:kafka-producer-config {:servers (System/getenv "BOOTSTRAP_SERVERS")
:timeout-ms 2000}
:kafka-consumer-config {:servers (System/getenv "BOOTSTRAP_SERVERS")
:group-id (System/getenv "GROUP_ID")}})))
| true | ;; Copyright 2016-2017 Boundless, http://boundlessgeo.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 spacon.server
(:gen-class) ; for -main method in uberjar
(:require [io.pedestal.http :as server]
[spacon.components.http.core :as http]
[com.stuartsierra.component :as component]
[spacon.components.ping.core :as ping]
[spacon.components.user.core :as user]
[spacon.components.team.core :as team]
[spacon.components.device.core :as device]
[spacon.components.config.core :as config]
[spacon.components.store.core :as store]
[spacon.components.location.core :as location]
[spacon.components.mqtt.core :as mqtt]
[spacon.components.notification.core :as notification]
[spacon.components.form.core :as form]
[spacon.components.kafka.core :as kafka]
[clojure.tools.logging :as log]))
(defrecord SpaconServer [http-service]
component/Lifecycle
(start [component]
(log/info "Starting SpaconServer Component")
(let [server (server/create-server (:service-def http-service))]
(server/start server)
(assoc component :http-server server)))
(stop [component]
(log/info "Stopping SpaconServer Component")
(update-in component [:http-server] server/stop)))
(defn new-spacon-server []
(map->SpaconServer {}))
(defn make-spacon-server
"Returns a new instance of the system"
[config-options]
(log/debug "Making server config with these options" config-options)
(let [{:keys [http-config mqtt-config kafka-producer-config kafka-consumer-config]} config-options]
(component/system-map
:user (user/make-user-component)
:team (team/make-team-component)
:mqtt (mqtt/make-mqtt-component mqtt-config)
:kafka (kafka/make-kafka-component kafka-producer-config kafka-consumer-config)
:ping (component/using (ping/make-ping-component) [:mqtt :kafka])
:device (component/using (device/make-device-component) [:mqtt])
:config (component/using (config/make-config-component) [:mqtt])
:notify (component/using (notification/make-notification-component) [:mqtt])
:store (component/using (store/make-store-component) [:mqtt])
:location (component/using (location/make-location-component) [:mqtt])
:form (component/using (form/make-form-component) [:mqtt])
:http-service (component/using
(http/make-http-service-component http-config)
[:ping :user :team :device :location
:store :config :form :mqtt :notify])
:server (component/using (new-spacon-server) [:http-service]))))
(defn -main
"The entry-point for 'lein run'"
[& _]
(log/info "Configuring the server...")
(if (= "true" (System/getenv "AUTO_MIGRATE"))
(spacon.db.conn/migrate))
;; create global uncaught exception handler so threads don't silently die
(Thread/setDefaultUncaughtExceptionHandler
(reify Thread$UncaughtExceptionHandler
(uncaughtException [_ thread ex]
(log/error ex "Uncaught exception on thread" (.getName thread)))))
(System/setProperty "javax.net.ssl.trustStore"
(or (System/getenv "TRUST_STORE")
"tls/test-cacerts.jks"))
(System/setProperty "javax.net.ssl.trustStoreType"
(or (System/getenv "TRUST_STORE_TYPE")
"JKS"))
(System/setProperty "javax.net.ssl.trustStorePassword"
(or (System/getenv "TRUST_STORE_PASSWORD")
"PI:PASSWORD:<PASSWORD>END_PI"))
(System/setProperty "javax.net.ssl.keyStore"
(or (System/getenv "KEY_STORE")
"tls/test-keystore.p12"))
(System/setProperty "javax.net.ssl.keyStoreType"
(or (System/getenv "KEY_STORE_TYPE")
"pkcs12"))
(System/setProperty "javax.net.ssl.keyStorePassword"
(or (System/getenv "KEY_STORE_PASSWORD")
"PI:PASSWORD:<PASSWORD>END_PI"))
(component/start-system
(make-spacon-server {:http-config {::server/allowed-origins {:allowed-origins [(System/getenv "ALLOWED_ORIGINS")]}}
:mqtt-config {:broker-url (System/getenv "MQTT_BROKER_URL")}
:kafka-producer-config {:servers (System/getenv "BOOTSTRAP_SERVERS")
:timeout-ms 2000}
:kafka-consumer-config {:servers (System/getenv "BOOTSTRAP_SERVERS")
:group-id (System/getenv "GROUP_ID")}})))
|
[
{
"context": "[omchaya.utils :as utils]))\n\n(def user-emails\n [\"sean@bushi.do\" \"nb@bushi.do\" \"sacha@bushi.do\"])\n\n(defn random-m",
"end": 97,
"score": 0.999927818775177,
"start": 84,
"tag": "EMAIL",
"value": "sean@bushi.do"
},
{
"context": "as utils]))\n\n(def user-emails\n [\"sean@bushi.do\" \"nb@bushi.do\" \"sacha@bushi.do\"])\n\n(defn random-message [channe",
"end": 111,
"score": 0.999928891658783,
"start": 100,
"tag": "EMAIL",
"value": "nb@bushi.do"
},
{
"context": "def user-emails\n [\"sean@bushi.do\" \"nb@bushi.do\" \"sacha@bushi.do\"])\n\n(defn random-message [channel-id & [at-now?]]",
"end": 128,
"score": 0.9999257922172546,
"start": 114,
"tag": "EMAIL",
"value": "sacha@bushi.do"
},
{
"context": "deo%20in%20HD%20-%20.mp3\"\n \"@sacha Be careful with that\"\n \"H",
"end": 1669,
"score": 0.8683662414550781,
"start": 1662,
"tag": "USERNAME",
"value": "\"@sacha"
},
{
"context": "e careful with that\"\n \"Hey @nb - I got you something nice... (not really)\"])\n ",
"end": 1725,
"score": 0.970746636390686,
"start": 1722,
"tag": "USERNAME",
"value": "@nb"
},
{
"context": "-in ch [\"1\"] assoc :selected true))\n :users {\"sean@bushi.do\" {:full-name \"Sean Grove\"\n ",
"end": 4080,
"score": 0.9999262690544128,
"start": 4067,
"tag": "EMAIL",
"value": "sean@bushi.do"
},
{
"context": " true))\n :users {\"sean@bushi.do\" {:full-name \"Sean Grove\"\n :email \"sean@bushi",
"end": 4105,
"score": 0.999886155128479,
"start": 4095,
"tag": "NAME",
"value": "Sean Grove"
},
{
"context": "Sean Grove\"\n :email \"sean@bushi.do\"\n :username \"sgrove\"",
"end": 4158,
"score": 0.9999274015426636,
"start": 4145,
"tag": "EMAIL",
"value": "sean@bushi.do"
},
{
"context": "ushi.do\"\n :username \"sgrove\"}\n \"nb@bushi.do\" {:full-name \"Nathan ",
"end": 4207,
"score": 0.9995729327201843,
"start": 4201,
"tag": "USERNAME",
"value": "sgrove"
},
{
"context": " :username \"sgrove\"}\n \"nb@bushi.do\" {:full-name \"Nathan Broadbent\"\n ",
"end": 4235,
"score": 0.9999261498451233,
"start": 4224,
"tag": "EMAIL",
"value": "nb@bushi.do"
},
{
"context": "\"sgrove\"}\n \"nb@bushi.do\" {:full-name \"Nathan Broadbent\"\n :email \"nb@bushi.do\"",
"end": 4266,
"score": 0.9998914003372192,
"start": 4250,
"tag": "NAME",
"value": "Nathan Broadbent"
},
{
"context": "an Broadbent\"\n :email \"nb@bushi.do\"\n :username \"nb\"}\n ",
"end": 4315,
"score": 0.9999271035194397,
"start": 4304,
"tag": "EMAIL",
"value": "nb@bushi.do"
},
{
"context": "@bushi.do\"\n :username \"nb\"}\n \"sacha@bushi.do\" {:full-name \"Sach",
"end": 4358,
"score": 0.9995425939559937,
"start": 4356,
"tag": "USERNAME",
"value": "nb"
},
{
"context": " :username \"nb\"}\n \"sacha@bushi.do\" {:full-name \"Sacha Greif\"\n ",
"end": 4389,
"score": 0.9999246001243591,
"start": 4375,
"tag": "EMAIL",
"value": "sacha@bushi.do"
},
{
"context": " \"nb\"}\n \"sacha@bushi.do\" {:full-name \"Sacha Greif\"\n :email \"sacha@bus",
"end": 4415,
"score": 0.9998777508735657,
"start": 4404,
"tag": "NAME",
"value": "Sacha Greif"
},
{
"context": "cha Greif\"\n :email \"sacha@bushi.do\"\n :username \"sacha\"",
"end": 4470,
"score": 0.9999257326126099,
"start": 4456,
"tag": "EMAIL",
"value": "sacha@bushi.do"
},
{
"context": "shi.do\"\n :username \"sacha\"}}\n :current-user-email \"sean@bushi.do\"\n ",
"end": 4519,
"score": 0.9992599487304688,
"start": 4514,
"tag": "USERNAME",
"value": "sacha"
},
{
"context": " :username \"sacha\"}}\n :current-user-email \"sean@bushi.do\"\n :comms comms}))\n",
"end": 4562,
"score": 0.999925971031189,
"start": 4549,
"tag": "EMAIL",
"value": "sean@bushi.do"
}
] | src/omchaya/mock_data.cljs | sgrove/omchaya | 66 | (ns omchaya.mock-data
(:require [omchaya.utils :as utils]))
(def user-emails
["sean@bushi.do" "nb@bushi.do" "sacha@bushi.do"])
(defn random-message [channel-id & [at-now?]]
(let [at (if at-now?
(js/Date.)
(as-> (js/Date.) x
(.getTime x)
(- x (rand-int (* 1000 60 24 60)))
(js/Date. x)))]
{:created_at at
:author (rand-nth user-emails)
:content (rand-nth ["deployed with ruby on...?"
"ha, dat stuff works"
"Random content"
"Heh, :+1:"
"Wow, :exclamation:"
"@sgrove Ok, let's do this!"
"/queue http://mp3.tom7.org/t7es/2008/t7es_msiegler.mp3"
"/queue http://mp3.tom7.org/t7es/2008/t7es_goog.mp3"
"/queue http://mp3.tom7.org/t7es/2008/t7es_petrolatum.mp3"
"/queue http://mp3.tom7.org/t7es/2009/t7es-sans-pellegrino.mp3"
"/queue http://mp3.tom7.org/t7es/2008/t7es_rt2i.mp3"
"/queue http://mp3.tom7.org/t7es/2007/tom7=rutgers.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/11%20Charlotte.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/Golf%20Clap.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/cheer.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/Why%20This%20Kolaveri%20Di%20Full%20Song%20Promo%20Video%20in%20HD%20-%20.mp3"
"@sacha Be careful with that"
"Hey @nb - I got you something nice... (not really)"])
:channel-id channel-id}))
(defn random-title []
(rand-nth ["Background"
"A dark place"
"한국어"
"Zork lovers"
"The War Room"
"Emotional Trance"
"8 out of 10 cats"
"Was it something I said?"
"Example"]))
(def media
[{:src "/system/attachments/files/000/000/098/original/call-centre-woman.jpg?1392265218"
:name "call-centre-woman.jpg"}
{:src "/system/attachments/files/000/000/098/original/design.pdf?1392265218"
:name "design.pdf"}
{:src "/system/attachments/files/000/000/098/original/example.mp3?1392265218"
:name "example.mp3"}])
(defn random-channel [order & [title]]
(let [title (or title (random-title))]
{:id (utils/safe-sel title)
:order order
:title title
:selected false
:users (take (inc (rand-int (count user-emails))) (shuffle user-emails))
:activities (vec
(sort-by :created_at (repeatedly (inc (rand-int 0))
#(random-message (utils/safe-sel title)))))
:media (vec
(take (inc (rand-int 0))
(shuffle media)))
:sfx {:source-url nil}
:player {:source-url "https://dl.dropboxusercontent.com/u/412963/Why%20This%20Kolaveri%20Di%20Full%20Song%20Promo%20Video%20in%20HD%20-%20.mp3"
:playing-order -1
:state :playing
:loading false
:playlist []}}))
(defn initial-state [comms]
(let [channels (into {} (map (comp (juxt :id identity) random-channel) (range 2 100)))]
{:audio {:volume 100
:muted true}
:windows {:window-inspector {:open false}}
:settings {:message-limit 50
:forms {:search {:focused false}
:user-message {:focused false}}
:menus {:user-menu {:open false}}
:sidebar {:left {:open false}
:right {:open false}}
:inspector {:path [:users]}}
:selected-channel "1"
:channels (as-> channels ch
(assoc ch "1" (-> (random-channel 1 "Lobby")
(assoc :id "1")))
(update-in ch ["1"] assoc :selected true))
:users {"sean@bushi.do" {:full-name "Sean Grove"
:email "sean@bushi.do"
:username "sgrove"}
"nb@bushi.do" {:full-name "Nathan Broadbent"
:email "nb@bushi.do"
:username "nb"}
"sacha@bushi.do" {:full-name "Sacha Greif"
:email "sacha@bushi.do"
:username "sacha"}}
:current-user-email "sean@bushi.do"
:comms comms}))
| 101414 | (ns omchaya.mock-data
(:require [omchaya.utils :as utils]))
(def user-emails
["<EMAIL>" "<EMAIL>" "<EMAIL>"])
(defn random-message [channel-id & [at-now?]]
(let [at (if at-now?
(js/Date.)
(as-> (js/Date.) x
(.getTime x)
(- x (rand-int (* 1000 60 24 60)))
(js/Date. x)))]
{:created_at at
:author (rand-nth user-emails)
:content (rand-nth ["deployed with ruby on...?"
"ha, dat stuff works"
"Random content"
"Heh, :+1:"
"Wow, :exclamation:"
"@sgrove Ok, let's do this!"
"/queue http://mp3.tom7.org/t7es/2008/t7es_msiegler.mp3"
"/queue http://mp3.tom7.org/t7es/2008/t7es_goog.mp3"
"/queue http://mp3.tom7.org/t7es/2008/t7es_petrolatum.mp3"
"/queue http://mp3.tom7.org/t7es/2009/t7es-sans-pellegrino.mp3"
"/queue http://mp3.tom7.org/t7es/2008/t7es_rt2i.mp3"
"/queue http://mp3.tom7.org/t7es/2007/tom7=rutgers.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/11%20Charlotte.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/Golf%20Clap.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/cheer.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/Why%20This%20Kolaveri%20Di%20Full%20Song%20Promo%20Video%20in%20HD%20-%20.mp3"
"@sacha Be careful with that"
"Hey @nb - I got you something nice... (not really)"])
:channel-id channel-id}))
(defn random-title []
(rand-nth ["Background"
"A dark place"
"한국어"
"Zork lovers"
"The War Room"
"Emotional Trance"
"8 out of 10 cats"
"Was it something I said?"
"Example"]))
(def media
[{:src "/system/attachments/files/000/000/098/original/call-centre-woman.jpg?1392265218"
:name "call-centre-woman.jpg"}
{:src "/system/attachments/files/000/000/098/original/design.pdf?1392265218"
:name "design.pdf"}
{:src "/system/attachments/files/000/000/098/original/example.mp3?1392265218"
:name "example.mp3"}])
(defn random-channel [order & [title]]
(let [title (or title (random-title))]
{:id (utils/safe-sel title)
:order order
:title title
:selected false
:users (take (inc (rand-int (count user-emails))) (shuffle user-emails))
:activities (vec
(sort-by :created_at (repeatedly (inc (rand-int 0))
#(random-message (utils/safe-sel title)))))
:media (vec
(take (inc (rand-int 0))
(shuffle media)))
:sfx {:source-url nil}
:player {:source-url "https://dl.dropboxusercontent.com/u/412963/Why%20This%20Kolaveri%20Di%20Full%20Song%20Promo%20Video%20in%20HD%20-%20.mp3"
:playing-order -1
:state :playing
:loading false
:playlist []}}))
(defn initial-state [comms]
(let [channels (into {} (map (comp (juxt :id identity) random-channel) (range 2 100)))]
{:audio {:volume 100
:muted true}
:windows {:window-inspector {:open false}}
:settings {:message-limit 50
:forms {:search {:focused false}
:user-message {:focused false}}
:menus {:user-menu {:open false}}
:sidebar {:left {:open false}
:right {:open false}}
:inspector {:path [:users]}}
:selected-channel "1"
:channels (as-> channels ch
(assoc ch "1" (-> (random-channel 1 "Lobby")
(assoc :id "1")))
(update-in ch ["1"] assoc :selected true))
:users {"<EMAIL>" {:full-name "<NAME>"
:email "<EMAIL>"
:username "sgrove"}
"<EMAIL>" {:full-name "<NAME>"
:email "<EMAIL>"
:username "nb"}
"<EMAIL>" {:full-name "<NAME>"
:email "<EMAIL>"
:username "sacha"}}
:current-user-email "<EMAIL>"
:comms comms}))
| true | (ns omchaya.mock-data
(:require [omchaya.utils :as utils]))
(def user-emails
["PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI"])
(defn random-message [channel-id & [at-now?]]
(let [at (if at-now?
(js/Date.)
(as-> (js/Date.) x
(.getTime x)
(- x (rand-int (* 1000 60 24 60)))
(js/Date. x)))]
{:created_at at
:author (rand-nth user-emails)
:content (rand-nth ["deployed with ruby on...?"
"ha, dat stuff works"
"Random content"
"Heh, :+1:"
"Wow, :exclamation:"
"@sgrove Ok, let's do this!"
"/queue http://mp3.tom7.org/t7es/2008/t7es_msiegler.mp3"
"/queue http://mp3.tom7.org/t7es/2008/t7es_goog.mp3"
"/queue http://mp3.tom7.org/t7es/2008/t7es_petrolatum.mp3"
"/queue http://mp3.tom7.org/t7es/2009/t7es-sans-pellegrino.mp3"
"/queue http://mp3.tom7.org/t7es/2008/t7es_rt2i.mp3"
"/queue http://mp3.tom7.org/t7es/2007/tom7=rutgers.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/11%20Charlotte.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/Golf%20Clap.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/cheer.mp3"
"/queue https://dl.dropboxusercontent.com/u/412963/Why%20This%20Kolaveri%20Di%20Full%20Song%20Promo%20Video%20in%20HD%20-%20.mp3"
"@sacha Be careful with that"
"Hey @nb - I got you something nice... (not really)"])
:channel-id channel-id}))
(defn random-title []
(rand-nth ["Background"
"A dark place"
"한국어"
"Zork lovers"
"The War Room"
"Emotional Trance"
"8 out of 10 cats"
"Was it something I said?"
"Example"]))
(def media
[{:src "/system/attachments/files/000/000/098/original/call-centre-woman.jpg?1392265218"
:name "call-centre-woman.jpg"}
{:src "/system/attachments/files/000/000/098/original/design.pdf?1392265218"
:name "design.pdf"}
{:src "/system/attachments/files/000/000/098/original/example.mp3?1392265218"
:name "example.mp3"}])
(defn random-channel [order & [title]]
(let [title (or title (random-title))]
{:id (utils/safe-sel title)
:order order
:title title
:selected false
:users (take (inc (rand-int (count user-emails))) (shuffle user-emails))
:activities (vec
(sort-by :created_at (repeatedly (inc (rand-int 0))
#(random-message (utils/safe-sel title)))))
:media (vec
(take (inc (rand-int 0))
(shuffle media)))
:sfx {:source-url nil}
:player {:source-url "https://dl.dropboxusercontent.com/u/412963/Why%20This%20Kolaveri%20Di%20Full%20Song%20Promo%20Video%20in%20HD%20-%20.mp3"
:playing-order -1
:state :playing
:loading false
:playlist []}}))
(defn initial-state [comms]
(let [channels (into {} (map (comp (juxt :id identity) random-channel) (range 2 100)))]
{:audio {:volume 100
:muted true}
:windows {:window-inspector {:open false}}
:settings {:message-limit 50
:forms {:search {:focused false}
:user-message {:focused false}}
:menus {:user-menu {:open false}}
:sidebar {:left {:open false}
:right {:open false}}
:inspector {:path [:users]}}
:selected-channel "1"
:channels (as-> channels ch
(assoc ch "1" (-> (random-channel 1 "Lobby")
(assoc :id "1")))
(update-in ch ["1"] assoc :selected true))
:users {"PI:EMAIL:<EMAIL>END_PI" {:full-name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:username "sgrove"}
"PI:EMAIL:<EMAIL>END_PI" {:full-name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:username "nb"}
"PI:EMAIL:<EMAIL>END_PI" {:full-name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:username "sacha"}}
:current-user-email "PI:EMAIL:<EMAIL>END_PI"
:comms comms}))
|
[
{
"context": "\"]\n :repositories [[\"snapshots\" \"file://C:/Users/Mike Aldred/.m2/repository\"]]\n :dependencies [[org.clojure/c",
"end": 493,
"score": 0.9998653531074524,
"start": 482,
"tag": "NAME",
"value": "Mike Aldred"
}
] | project.clj | DirectCommunications/Greentree-Interface | 0 | (defproject org.clojars.luminousmonkey/greentree-interface "0.0.2-SNAPSHOT"
:description "Clojure library for interfacing with Greentree."
:url "http://example.com/FIXME"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:distribution :repo
:year 2017
:key "mit"}
:min-lein-version "2.0.0"
:source-paths ["src/clojure"]
:java-source-paths ["src/java"]
:repositories [["snapshots" "file://C:/Users/Mike Aldred/.m2/repository"]]
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojars.luminousmonkey/javajom "6.3.9.1"]
[org.clojars.luminousmonkey/javajom-native "6.3.9.1"]]
:profiles {:dev {:source-paths ["dev"]
:dependencies [[org.clojure/tools.namespace "0.2.3"]
[org.clojure/java.classpath "0.2.0"]
[midje "1.6-alpha2"]]}})
| 13328 | (defproject org.clojars.luminousmonkey/greentree-interface "0.0.2-SNAPSHOT"
:description "Clojure library for interfacing with Greentree."
:url "http://example.com/FIXME"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:distribution :repo
:year 2017
:key "mit"}
:min-lein-version "2.0.0"
:source-paths ["src/clojure"]
:java-source-paths ["src/java"]
:repositories [["snapshots" "file://C:/Users/<NAME>/.m2/repository"]]
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojars.luminousmonkey/javajom "6.3.9.1"]
[org.clojars.luminousmonkey/javajom-native "6.3.9.1"]]
:profiles {:dev {:source-paths ["dev"]
:dependencies [[org.clojure/tools.namespace "0.2.3"]
[org.clojure/java.classpath "0.2.0"]
[midje "1.6-alpha2"]]}})
| true | (defproject org.clojars.luminousmonkey/greentree-interface "0.0.2-SNAPSHOT"
:description "Clojure library for interfacing with Greentree."
:url "http://example.com/FIXME"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:distribution :repo
:year 2017
:key "mit"}
:min-lein-version "2.0.0"
:source-paths ["src/clojure"]
:java-source-paths ["src/java"]
:repositories [["snapshots" "file://C:/Users/PI:NAME:<NAME>END_PI/.m2/repository"]]
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojars.luminousmonkey/javajom "6.3.9.1"]
[org.clojars.luminousmonkey/javajom-native "6.3.9.1"]]
:profiles {:dev {:source-paths ["dev"]
:dependencies [[org.clojure/tools.namespace "0.2.3"]
[org.clojure/java.classpath "0.2.0"]
[midje "1.6-alpha2"]]}})
|
[
{
"context": " we also supported a\n ;; key called `invalid-in-puppet-4` in the same route config, even though",
"end": 3733,
"score": 0.5680461525917053,
"start": 3733,
"tag": "KEY",
"value": ""
},
{
"context": " also supported a\n ;; key called `invalid-in-puppet-4` in the same route config, even though\n ",
"end": 3736,
"score": 0.5907402038574219,
"start": 3736,
"tag": "KEY",
"value": ""
},
{
"context": "upported a\n ;; key called `invalid-in-puppet-4` in the same route config, even though\n ;;",
"end": 3743,
"score": 0.5528491139411926,
"start": 3743,
"tag": "KEY",
"value": ""
}
] | src/clj/puppetlabs/services/master/master_service.clj | waynr/puppetserver | 0 | (ns puppetlabs.services.master.master-service
(:require [clojure.tools.logging :as log]
[puppetlabs.trapperkeeper.core :refer [defservice]]
[puppetlabs.services.master.master-core :as core]
[puppetlabs.puppetserver.certificate-authority :as ca]
[puppetlabs.trapperkeeper.services :as tk-services]
[puppetlabs.comidi :as comidi]
[puppetlabs.dujour.version-check :as version-check]
[puppetlabs.services.protocols.master :as master]
[puppetlabs.i18n.core :as i18n :refer [trs]]))
(defservice master-service
master/MasterService
[[:WebroutingService add-ring-handler get-route]
[:PuppetServerConfigService get-config]
[:RequestHandlerService handle-request]
[:CaService initialize-master-ssl! retrieve-ca-cert! retrieve-ca-crl! get-auth-handler]
[:JRubyPuppetService]
[:AuthorizationService wrap-with-authorization-check]
[:SchedulerService interspaced]
[:VersionedCodeService get-code-content]]
(init
[this context]
(core/validate-memory-requirements!)
(let [config (get-config)
certname (get-in config [:puppetserver :certname])
localcacert (get-in config [:puppetserver :localcacert])
puppet-version (get-in config [:puppetserver :puppet-version])
hostcrl (get-in config [:puppetserver :hostcrl])
settings (ca/config->master-settings config)
product-name (or (get-in config [:product :name])
{:group-id "puppetlabs"
:artifact-id "puppetserver"})
checkin-interval-millis (* 1000 60 60 24) ; once per day
update-server-url (get-in config [:product :update-server-url])
use-legacy-auth-conf (get-in config
[:jruby-puppet :use-legacy-auth-conf]
true)
jruby-service (tk-services/get-service this :JRubyPuppetService)
environment-class-cache-enabled (get-in config
[:jruby-puppet
:environment-class-cache-enabled]
false)]
(interspaced checkin-interval-millis
(fn [] (version-check/check-for-updates! {:product-name product-name} update-server-url)))
(retrieve-ca-cert! localcacert)
(retrieve-ca-crl! hostcrl)
(initialize-master-ssl! settings certname)
(log/info (trs "Master Service adding ring handlers"))
(let [route-config (core/get-master-route-config ::master-service config)
path (core/get-master-mount ::master-service route-config)
ring-handler (when path
(-> (core/construct-root-routes puppet-version
use-legacy-auth-conf
jruby-service
get-code-content
handle-request
(get-auth-handler)
environment-class-cache-enabled)
((partial comidi/context path))
comidi/routes->handler))]
;; if the webrouting config uses the old-style config where
;; there is a single key with a route-id, we need to deal with that
;; for backward compat. We have a hard-coded assumption that this route-id
;; must be `master-routes`. In Puppet Server 2.0, we also supported a
;; key called `invalid-in-puppet-4` in the same route config, even though
;; that key is no longer used for Puppet Server 2.1 and later. We
;; should be able to remove this hack as soon as we are able to get rid
;; of the legacy routes.
(if (and (map? route-config)
(contains? route-config :master-routes))
(add-ring-handler this
ring-handler
{:route-id :master-routes
:normalize-request-uri true})
(add-ring-handler this
ring-handler
{:normalize-request-uri true}))))
context)
(start
[this context]
(log/info (trs "Puppet Server has successfully started and is now ready to handle requests"))
context))
| 61210 | (ns puppetlabs.services.master.master-service
(:require [clojure.tools.logging :as log]
[puppetlabs.trapperkeeper.core :refer [defservice]]
[puppetlabs.services.master.master-core :as core]
[puppetlabs.puppetserver.certificate-authority :as ca]
[puppetlabs.trapperkeeper.services :as tk-services]
[puppetlabs.comidi :as comidi]
[puppetlabs.dujour.version-check :as version-check]
[puppetlabs.services.protocols.master :as master]
[puppetlabs.i18n.core :as i18n :refer [trs]]))
(defservice master-service
master/MasterService
[[:WebroutingService add-ring-handler get-route]
[:PuppetServerConfigService get-config]
[:RequestHandlerService handle-request]
[:CaService initialize-master-ssl! retrieve-ca-cert! retrieve-ca-crl! get-auth-handler]
[:JRubyPuppetService]
[:AuthorizationService wrap-with-authorization-check]
[:SchedulerService interspaced]
[:VersionedCodeService get-code-content]]
(init
[this context]
(core/validate-memory-requirements!)
(let [config (get-config)
certname (get-in config [:puppetserver :certname])
localcacert (get-in config [:puppetserver :localcacert])
puppet-version (get-in config [:puppetserver :puppet-version])
hostcrl (get-in config [:puppetserver :hostcrl])
settings (ca/config->master-settings config)
product-name (or (get-in config [:product :name])
{:group-id "puppetlabs"
:artifact-id "puppetserver"})
checkin-interval-millis (* 1000 60 60 24) ; once per day
update-server-url (get-in config [:product :update-server-url])
use-legacy-auth-conf (get-in config
[:jruby-puppet :use-legacy-auth-conf]
true)
jruby-service (tk-services/get-service this :JRubyPuppetService)
environment-class-cache-enabled (get-in config
[:jruby-puppet
:environment-class-cache-enabled]
false)]
(interspaced checkin-interval-millis
(fn [] (version-check/check-for-updates! {:product-name product-name} update-server-url)))
(retrieve-ca-cert! localcacert)
(retrieve-ca-crl! hostcrl)
(initialize-master-ssl! settings certname)
(log/info (trs "Master Service adding ring handlers"))
(let [route-config (core/get-master-route-config ::master-service config)
path (core/get-master-mount ::master-service route-config)
ring-handler (when path
(-> (core/construct-root-routes puppet-version
use-legacy-auth-conf
jruby-service
get-code-content
handle-request
(get-auth-handler)
environment-class-cache-enabled)
((partial comidi/context path))
comidi/routes->handler))]
;; if the webrouting config uses the old-style config where
;; there is a single key with a route-id, we need to deal with that
;; for backward compat. We have a hard-coded assumption that this route-id
;; must be `master-routes`. In Puppet Server 2.0, we also supported a
;; key called `invalid<KEY>-in<KEY>-puppet<KEY>-4` in the same route config, even though
;; that key is no longer used for Puppet Server 2.1 and later. We
;; should be able to remove this hack as soon as we are able to get rid
;; of the legacy routes.
(if (and (map? route-config)
(contains? route-config :master-routes))
(add-ring-handler this
ring-handler
{:route-id :master-routes
:normalize-request-uri true})
(add-ring-handler this
ring-handler
{:normalize-request-uri true}))))
context)
(start
[this context]
(log/info (trs "Puppet Server has successfully started and is now ready to handle requests"))
context))
| true | (ns puppetlabs.services.master.master-service
(:require [clojure.tools.logging :as log]
[puppetlabs.trapperkeeper.core :refer [defservice]]
[puppetlabs.services.master.master-core :as core]
[puppetlabs.puppetserver.certificate-authority :as ca]
[puppetlabs.trapperkeeper.services :as tk-services]
[puppetlabs.comidi :as comidi]
[puppetlabs.dujour.version-check :as version-check]
[puppetlabs.services.protocols.master :as master]
[puppetlabs.i18n.core :as i18n :refer [trs]]))
(defservice master-service
master/MasterService
[[:WebroutingService add-ring-handler get-route]
[:PuppetServerConfigService get-config]
[:RequestHandlerService handle-request]
[:CaService initialize-master-ssl! retrieve-ca-cert! retrieve-ca-crl! get-auth-handler]
[:JRubyPuppetService]
[:AuthorizationService wrap-with-authorization-check]
[:SchedulerService interspaced]
[:VersionedCodeService get-code-content]]
(init
[this context]
(core/validate-memory-requirements!)
(let [config (get-config)
certname (get-in config [:puppetserver :certname])
localcacert (get-in config [:puppetserver :localcacert])
puppet-version (get-in config [:puppetserver :puppet-version])
hostcrl (get-in config [:puppetserver :hostcrl])
settings (ca/config->master-settings config)
product-name (or (get-in config [:product :name])
{:group-id "puppetlabs"
:artifact-id "puppetserver"})
checkin-interval-millis (* 1000 60 60 24) ; once per day
update-server-url (get-in config [:product :update-server-url])
use-legacy-auth-conf (get-in config
[:jruby-puppet :use-legacy-auth-conf]
true)
jruby-service (tk-services/get-service this :JRubyPuppetService)
environment-class-cache-enabled (get-in config
[:jruby-puppet
:environment-class-cache-enabled]
false)]
(interspaced checkin-interval-millis
(fn [] (version-check/check-for-updates! {:product-name product-name} update-server-url)))
(retrieve-ca-cert! localcacert)
(retrieve-ca-crl! hostcrl)
(initialize-master-ssl! settings certname)
(log/info (trs "Master Service adding ring handlers"))
(let [route-config (core/get-master-route-config ::master-service config)
path (core/get-master-mount ::master-service route-config)
ring-handler (when path
(-> (core/construct-root-routes puppet-version
use-legacy-auth-conf
jruby-service
get-code-content
handle-request
(get-auth-handler)
environment-class-cache-enabled)
((partial comidi/context path))
comidi/routes->handler))]
;; if the webrouting config uses the old-style config where
;; there is a single key with a route-id, we need to deal with that
;; for backward compat. We have a hard-coded assumption that this route-id
;; must be `master-routes`. In Puppet Server 2.0, we also supported a
;; key called `invalidPI:KEY:<KEY>END_PI-inPI:KEY:<KEY>END_PI-puppetPI:KEY:<KEY>END_PI-4` in the same route config, even though
;; that key is no longer used for Puppet Server 2.1 and later. We
;; should be able to remove this hack as soon as we are able to get rid
;; of the legacy routes.
(if (and (map? route-config)
(contains? route-config :master-routes))
(add-ring-handler this
ring-handler
{:route-id :master-routes
:normalize-request-uri true})
(add-ring-handler this
ring-handler
{:normalize-request-uri true}))))
context)
(start
[this context]
(log/info (trs "Puppet Server has successfully started and is now ready to handle requests"))
context))
|
[
{
"context": " [\n ; {\n ; \"key\": \"Hurricane\",\n ; \"doc_count\": 6,\n ; ",
"end": 13574,
"score": 0.9869903326034546,
"start": 13565,
"tag": "KEY",
"value": "Hurricane"
},
{
"context": " {\n ; \"key\": \"C1200000000-PROV1\",\n ; \"doc_count\": 1\n",
"end": 13975,
"score": 0.9991208910942078,
"start": 13958,
"tag": "KEY",
"value": "C1200000000-PROV1"
}
] | search-app/src/cmr/search/services/query_execution/facets/facets_results_feature.clj | indiejames/Common-Metadata-Repository | 0 | (ns cmr.search.services.query-execution.facets.facets-results-feature
"This enables returning facets with collection search results"
(:require [cmr.common-app.services.search.query-execution :as query-execution]
[cmr.common-app.services.kms-fetcher :as kms-fetcher]
[cmr.common-app.services.search.results-model :as r]
[camel-snake-kebab.core :as csk]
[clojure.data.xml :as x]))
(def UNLIMITED_TERMS_SIZE
"The maximum number of results to return from any terms query"
;; FIXME: We shouldn't try to handle this many different values.
;; We should have a limit and if that's exceeded in the elastic response we should note that in
;; the values returned. This can be handled as a part of CMR-1101.
10000)
(defn- terms-facet
[field]
{:terms {:field field :size UNLIMITED_TERMS_SIZE}})
(def collection-count-aggregation
"Used to build an aggregation to get a count of unique concepts included in the current nested
aggregation."
{:reverse_nested {}
:aggs {:concept-id {:terms {:field :concept-id :size 1}}}})
(def hierarchical-facet-order
"Order in which hierarchical facets are returned in the facet response."
[:data-centers :archive-centers :platforms :instruments :science-keywords :location-keywords])
(defn- hierarchical-aggregation-builder
"Build an aggregations query for the given hierarchical field."
[field field-hierarchy]
(when-let [subfield (first field-hierarchy)]
{subfield {:terms {:field (str (name field) "." (name subfield))
:size UNLIMITED_TERMS_SIZE}
:aggs (merge {:coll-count collection-count-aggregation}
(hierarchical-aggregation-builder field (rest field-hierarchy)))}}))
(defn- nested-facet
"Returns the nested aggregation query for the given hierarchical field."
[field]
;; Removing field :url because it's necessary in keyword search but not in facets.
{:nested {:path field}
:aggs (hierarchical-aggregation-builder field (remove #{:url} (field kms-fetcher/nested-fields-mappings)))})
(def ^:private flat-facet-aggregations
"This is the aggregations map that will be passed to elasticsearch to request faceted results
from a collection search."
{:data-center (terms-facet :data-center)
:archive-center (terms-facet :archive-center)
:project (terms-facet :project-sn2)
:platform (terms-facet :platform-sn)
:instrument (terms-facet :instrument-sn)
:sensor (terms-facet :sensor-sn)
:two-d-coordinate-system-name (terms-facet :two-d-coord-name)
:processing-level-id (terms-facet :processing-level-id)
:category (terms-facet :category)
:topic (terms-facet :topic)
:term (terms-facet :term)
:variable-level-1 (terms-facet :variable-level-1)
:variable-level-2 (terms-facet :variable-level-2)
:variable-level-3 (terms-facet :variable-level-3)
:detailed-variable (terms-facet :detailed-variable)})
(def ^:private hierarchical-facet-aggregations
"This is the aggregations map that will be passed to elasticsearch to request faceted results
from a collection search."
{:data-centers (nested-facet :data-centers)
:archive-centers (nested-facet :archive-centers)
:project (terms-facet :project-sn2)
:platforms (nested-facet :platforms)
:instruments (nested-facet :instruments)
:sensor (terms-facet :sensor-sn)
:two-d-coordinate-system-name (terms-facet :two-d-coord-name)
:processing-level-id (terms-facet :processing-level-id)
:location-keywords (nested-facet :location-keywords)
:science-keywords (nested-facet :science-keywords)
;; Detailed variable is technically part of the science keyword hierarchy directly below
;; variable level 1 (at the same level as variable level 2.)
;; Opened ticket CMR-1722 to address.
:detailed-variable (terms-facet :detailed-variable)})
(defmethod query-execution/pre-process-query-result-feature :facets
[context query feature]
(assoc query :aggregations flat-facet-aggregations))
(defmethod query-execution/pre-process-query-result-feature :hierarchical-facets
[context query feature]
(assoc query :aggregations hierarchical-facet-aggregations))
(defn buckets->value-count-pairs
"Processes an elasticsearch aggregation response of buckets to a sequence of value and count
tuples"
[bucket-map]
(->> bucket-map
:buckets
(map (fn [{v :key n :doc_count}]
[v n]))))
(defn- bucket-map->facets
"Takes a map of elastic aggregation results containing keys to buckets and a list of the bucket
names. Returns a facet map of those specific names with value count pairs"
[bucket-map field-names]
(for [field-name field-names]
(r/map->Facet
{:field (csk/->snake_case_string field-name)
:value-counts (buckets->value-count-pairs (get bucket-map field-name))})))
(defn- parse-hierarchical-bucket
"Parses the elasticsearch aggregations response for hierarchical fields."
[field-hierarchy bucket-map]
(when-let [field (first field-hierarchy)]
(let [empty-response {:subfields []}
value-counts (for [bucket (get-in bucket-map [field :buckets])
:let [sub-facets (parse-hierarchical-bucket (rest field-hierarchy)
bucket)]]
(merge (when-not (= sub-facets empty-response)
sub-facets)
{:count (get-in bucket [:coll-count :doc_count] (:doc_count bucket))
:value (:key bucket)}))]
(if (seq value-counts)
(let [field-snake-case (csk/->snake_case_string field)]
{:subfields [field-snake-case]
field-snake-case value-counts})
empty-response))))
(defn- hierarchical-bucket-map->facets
"Takes a map of elastic aggregation results for a nested field. Returns a hierarchical facet for
that field."
[field bucket-map]
(parse-hierarchical-bucket (field kms-fetcher/nested-fields-mappings) bucket-map))
(defn- create-hierarchical-facets
"Create the facets response with hierarchical facets. Takes an elastic aggregations result and
returns the facets."
[elastic-aggregations]
(concat (bucket-map->facets (apply dissoc elastic-aggregations hierarchical-facet-order)
[:project :sensor :two-d-coordinate-system-name
:processing-level-id :detailed-variable])
(map (fn [field]
(assoc (hierarchical-bucket-map->facets field (field elastic-aggregations))
:field (csk/->snake_case_string field))) hierarchical-facet-order)))
(defn- create-flat-facets
"Create the facets response with flat facets. Takes an elastic aggregations result and returns
the facets."
[elastic-aggregations]
(bucket-map->facets
elastic-aggregations
;; Specified here so that order will be consistent with results
[:data-center :archive-center :project :platform :instrument :sensor
:two-d-coordinate-system-name :processing-level-id :category :topic :term
:variable-level-1 :variable-level-2 :variable-level-3 :detailed-variable]))
(defmethod query-execution/post-process-query-result-feature :facets
[_ _ {:keys [aggregations]} query-results _]
(assoc query-results :facets (create-flat-facets aggregations)))
(defmethod query-execution/post-process-query-result-feature :hierarchical-facets
[_ _ {:keys [aggregations]} query-results _]
(assoc query-results :facets (create-hierarchical-facets aggregations)))
(defn- key-with-prefix
[prefix k]
(if prefix
(symbol (str prefix ":" (name k)))
k))
(defn- value-count-maps->xml-element
"Converts a list of value-count-maps into an XML element."
[ns-prefix value-count-maps]
(let [with-prefix (partial key-with-prefix ns-prefix)]
(x/element (with-prefix :value-count-maps) {}
(for [value-count-map value-count-maps]
(if-let [subfield-name (first (:subfields value-count-map))]
(when-let [subfield-facets (get value-count-map subfield-name)]
(let [child-facets (x/element (with-prefix :facet)
{:field (name subfield-name)}
(value-count-maps->xml-element ns-prefix
subfield-facets))]
(x/element (with-prefix :value-count-map) {}
[(x/element (with-prefix :value)
{:count (:count value-count-map)}
(:value value-count-map))
child-facets])))
(x/element (with-prefix :value-count-map) {}
(x/element (with-prefix :value)
{:count (:count value-count-map)}
(:value value-count-map))))))))
(defn- facet->xml-element
"Helper function for converting a facet result into an XML element"
[ns-prefix {:keys [field value-counts subfields] :as facet}]
(let [with-prefix (partial key-with-prefix ns-prefix)
xml-element-content
(if-let [subfield (first subfields)]
(x/element (with-prefix :facet)
{:field (name subfield)}
(value-count-maps->xml-element ns-prefix (get facet subfield)))
(for [[value value-count] value-counts]
(x/element (with-prefix :value) {:count value-count} value)))]
(x/element (with-prefix :facet) {:field (name field)} xml-element-content)))
(defn facets->xml-element
"Converts a facets result into an XML element"
([facets]
(facets->xml-element nil facets))
([ns-prefix facets]
(when facets
(x/element (key-with-prefix ns-prefix :facets) {}
(map (partial facet->xml-element ns-prefix) facets)))))
(def cmr-facet-name->echo-facet-keyword
"A mapping of CMR facet names to ECHO facet keywords"
{"archive_center" :archive-center
"project" :campaign-sn
"platform" :platform-sn
"instrument" :instrument-sn
"sensor" :sensor-sn
"two_d_coordinate_system_name" :twod-coord-name
"processing_level_id" :processing-level
"category" :category-keyword
"topic" :topic-keyword
"term" :term-keyword
"variable_level_1" :variable-level-1-keyword
"variable_level_2" :variable-level-2-keyword
"variable_level_3" :variable-level-3-keyword
"detailed_variable" :detailed-variable-keyword})
(defn- facet->echo-xml-element
[facet]
(let [{:keys [field value-counts]} facet
field-key (cmr-facet-name->echo-facet-keyword field)]
(x/element field-key {:type "array"}
(for [[value value-count] value-counts]
(x/element field-key {}
(x/element :term {} value)
(x/element :count {:type "integer"} value-count))))))
(defn facets->echo-xml-element
"Helper function for converting facets into an XML element in echo format"
[facets]
(when facets
(x/element :hash {}
(map facet->echo-xml-element
;; Only include facets which are present in ECHO
(filter #(cmr-facet-name->echo-facet-keyword (:field %))
facets)))))
(defn- value-count->echo-json
"Returns value count in echo json format"
[value-count]
(let [[value value-count] value-count]
{:count value-count
:term value}))
(defn- facet->echo-json
[facet]
(let [{:keys [field value-counts]} facet
field-key (csk/->snake_case_string (cmr-facet-name->echo-facet-keyword field))]
[field-key (map value-count->echo-json value-counts)]))
(defn facets->echo-json
"Helper function for converting facets into an XML element in echo format"
[facets]
(when facets
(into {} (map facet->echo-json
;; Only include facets which are present in ECHO
(filter #(cmr-facet-name->echo-facet-keyword (:field %))
facets)))))
(comment)
;; See below for snippets of the data structures used for building hierarchical facets
;; 1) The elastic aggregations query for hierarchical facets
;; GET 1_collections_v2/collection/_search
; {
; "query": {
; "match_all": {}
; },
; "size": 0,
; "aggs": {
; "science_keywords": {
; "nested": {
; "path": "science-keywords"
; },
; "aggs": {
; "category": {
; "terms": {
; "field": "science-keywords.category"
; },
; "aggs": {
; "category-coll-count": {
; "reverse_nested": {},
; "aggs": {
; "concept-id": {
; "terms": {
; "field": "concept-id",
; "size": 1
; }
; }
; }
; },
; "topic": {
; ;; ... same structure as category
; ;; repeats for each term in the science keyword hierarchy
;; Snippet of the elastic response for hierarchical facets
; "aggregations": {
; "science_keywords": {
; "doc_count": 14,
; "category": {
; "doc_count_error_upper_bound": 0,
; "sum_other_doc_count": 0,
; "buckets": [
; {
; "key": "Hurricane",
; "doc_count": 6,
; "category-coll-count": {
; "doc_count": 2,
; "concept-id": {
; "doc_count_error_upper_bound": 0,
; "sum_other_doc_count": 1,
; "buckets": [
; {
; "key": "C1200000000-PROV1",
; "doc_count": 1
; }
; ]
; }
; },
; "topic": {
; ...
;; Hierarchical facets json response
; }, {
; "field" : "detailed_variable",
; "value-counts" : [ [ "Detail1", 2 ], [ "UNIVERSAL", 2 ] ]
; }, {
; "field" : "science_keywords",
; "subfields" : [ "category" ],
; "category" : [ {
; "value" : "Hurricane",
; "count" : 2,
; "subfields" : [ "topic" ],
; "topic" : [ {
; "value" : "Popular",
; ...
;
| 63702 | (ns cmr.search.services.query-execution.facets.facets-results-feature
"This enables returning facets with collection search results"
(:require [cmr.common-app.services.search.query-execution :as query-execution]
[cmr.common-app.services.kms-fetcher :as kms-fetcher]
[cmr.common-app.services.search.results-model :as r]
[camel-snake-kebab.core :as csk]
[clojure.data.xml :as x]))
(def UNLIMITED_TERMS_SIZE
"The maximum number of results to return from any terms query"
;; FIXME: We shouldn't try to handle this many different values.
;; We should have a limit and if that's exceeded in the elastic response we should note that in
;; the values returned. This can be handled as a part of CMR-1101.
10000)
(defn- terms-facet
[field]
{:terms {:field field :size UNLIMITED_TERMS_SIZE}})
(def collection-count-aggregation
"Used to build an aggregation to get a count of unique concepts included in the current nested
aggregation."
{:reverse_nested {}
:aggs {:concept-id {:terms {:field :concept-id :size 1}}}})
(def hierarchical-facet-order
"Order in which hierarchical facets are returned in the facet response."
[:data-centers :archive-centers :platforms :instruments :science-keywords :location-keywords])
(defn- hierarchical-aggregation-builder
"Build an aggregations query for the given hierarchical field."
[field field-hierarchy]
(when-let [subfield (first field-hierarchy)]
{subfield {:terms {:field (str (name field) "." (name subfield))
:size UNLIMITED_TERMS_SIZE}
:aggs (merge {:coll-count collection-count-aggregation}
(hierarchical-aggregation-builder field (rest field-hierarchy)))}}))
(defn- nested-facet
"Returns the nested aggregation query for the given hierarchical field."
[field]
;; Removing field :url because it's necessary in keyword search but not in facets.
{:nested {:path field}
:aggs (hierarchical-aggregation-builder field (remove #{:url} (field kms-fetcher/nested-fields-mappings)))})
(def ^:private flat-facet-aggregations
"This is the aggregations map that will be passed to elasticsearch to request faceted results
from a collection search."
{:data-center (terms-facet :data-center)
:archive-center (terms-facet :archive-center)
:project (terms-facet :project-sn2)
:platform (terms-facet :platform-sn)
:instrument (terms-facet :instrument-sn)
:sensor (terms-facet :sensor-sn)
:two-d-coordinate-system-name (terms-facet :two-d-coord-name)
:processing-level-id (terms-facet :processing-level-id)
:category (terms-facet :category)
:topic (terms-facet :topic)
:term (terms-facet :term)
:variable-level-1 (terms-facet :variable-level-1)
:variable-level-2 (terms-facet :variable-level-2)
:variable-level-3 (terms-facet :variable-level-3)
:detailed-variable (terms-facet :detailed-variable)})
(def ^:private hierarchical-facet-aggregations
"This is the aggregations map that will be passed to elasticsearch to request faceted results
from a collection search."
{:data-centers (nested-facet :data-centers)
:archive-centers (nested-facet :archive-centers)
:project (terms-facet :project-sn2)
:platforms (nested-facet :platforms)
:instruments (nested-facet :instruments)
:sensor (terms-facet :sensor-sn)
:two-d-coordinate-system-name (terms-facet :two-d-coord-name)
:processing-level-id (terms-facet :processing-level-id)
:location-keywords (nested-facet :location-keywords)
:science-keywords (nested-facet :science-keywords)
;; Detailed variable is technically part of the science keyword hierarchy directly below
;; variable level 1 (at the same level as variable level 2.)
;; Opened ticket CMR-1722 to address.
:detailed-variable (terms-facet :detailed-variable)})
(defmethod query-execution/pre-process-query-result-feature :facets
[context query feature]
(assoc query :aggregations flat-facet-aggregations))
(defmethod query-execution/pre-process-query-result-feature :hierarchical-facets
[context query feature]
(assoc query :aggregations hierarchical-facet-aggregations))
(defn buckets->value-count-pairs
"Processes an elasticsearch aggregation response of buckets to a sequence of value and count
tuples"
[bucket-map]
(->> bucket-map
:buckets
(map (fn [{v :key n :doc_count}]
[v n]))))
(defn- bucket-map->facets
"Takes a map of elastic aggregation results containing keys to buckets and a list of the bucket
names. Returns a facet map of those specific names with value count pairs"
[bucket-map field-names]
(for [field-name field-names]
(r/map->Facet
{:field (csk/->snake_case_string field-name)
:value-counts (buckets->value-count-pairs (get bucket-map field-name))})))
(defn- parse-hierarchical-bucket
"Parses the elasticsearch aggregations response for hierarchical fields."
[field-hierarchy bucket-map]
(when-let [field (first field-hierarchy)]
(let [empty-response {:subfields []}
value-counts (for [bucket (get-in bucket-map [field :buckets])
:let [sub-facets (parse-hierarchical-bucket (rest field-hierarchy)
bucket)]]
(merge (when-not (= sub-facets empty-response)
sub-facets)
{:count (get-in bucket [:coll-count :doc_count] (:doc_count bucket))
:value (:key bucket)}))]
(if (seq value-counts)
(let [field-snake-case (csk/->snake_case_string field)]
{:subfields [field-snake-case]
field-snake-case value-counts})
empty-response))))
(defn- hierarchical-bucket-map->facets
"Takes a map of elastic aggregation results for a nested field. Returns a hierarchical facet for
that field."
[field bucket-map]
(parse-hierarchical-bucket (field kms-fetcher/nested-fields-mappings) bucket-map))
(defn- create-hierarchical-facets
"Create the facets response with hierarchical facets. Takes an elastic aggregations result and
returns the facets."
[elastic-aggregations]
(concat (bucket-map->facets (apply dissoc elastic-aggregations hierarchical-facet-order)
[:project :sensor :two-d-coordinate-system-name
:processing-level-id :detailed-variable])
(map (fn [field]
(assoc (hierarchical-bucket-map->facets field (field elastic-aggregations))
:field (csk/->snake_case_string field))) hierarchical-facet-order)))
(defn- create-flat-facets
"Create the facets response with flat facets. Takes an elastic aggregations result and returns
the facets."
[elastic-aggregations]
(bucket-map->facets
elastic-aggregations
;; Specified here so that order will be consistent with results
[:data-center :archive-center :project :platform :instrument :sensor
:two-d-coordinate-system-name :processing-level-id :category :topic :term
:variable-level-1 :variable-level-2 :variable-level-3 :detailed-variable]))
(defmethod query-execution/post-process-query-result-feature :facets
[_ _ {:keys [aggregations]} query-results _]
(assoc query-results :facets (create-flat-facets aggregations)))
(defmethod query-execution/post-process-query-result-feature :hierarchical-facets
[_ _ {:keys [aggregations]} query-results _]
(assoc query-results :facets (create-hierarchical-facets aggregations)))
(defn- key-with-prefix
[prefix k]
(if prefix
(symbol (str prefix ":" (name k)))
k))
(defn- value-count-maps->xml-element
"Converts a list of value-count-maps into an XML element."
[ns-prefix value-count-maps]
(let [with-prefix (partial key-with-prefix ns-prefix)]
(x/element (with-prefix :value-count-maps) {}
(for [value-count-map value-count-maps]
(if-let [subfield-name (first (:subfields value-count-map))]
(when-let [subfield-facets (get value-count-map subfield-name)]
(let [child-facets (x/element (with-prefix :facet)
{:field (name subfield-name)}
(value-count-maps->xml-element ns-prefix
subfield-facets))]
(x/element (with-prefix :value-count-map) {}
[(x/element (with-prefix :value)
{:count (:count value-count-map)}
(:value value-count-map))
child-facets])))
(x/element (with-prefix :value-count-map) {}
(x/element (with-prefix :value)
{:count (:count value-count-map)}
(:value value-count-map))))))))
(defn- facet->xml-element
"Helper function for converting a facet result into an XML element"
[ns-prefix {:keys [field value-counts subfields] :as facet}]
(let [with-prefix (partial key-with-prefix ns-prefix)
xml-element-content
(if-let [subfield (first subfields)]
(x/element (with-prefix :facet)
{:field (name subfield)}
(value-count-maps->xml-element ns-prefix (get facet subfield)))
(for [[value value-count] value-counts]
(x/element (with-prefix :value) {:count value-count} value)))]
(x/element (with-prefix :facet) {:field (name field)} xml-element-content)))
(defn facets->xml-element
"Converts a facets result into an XML element"
([facets]
(facets->xml-element nil facets))
([ns-prefix facets]
(when facets
(x/element (key-with-prefix ns-prefix :facets) {}
(map (partial facet->xml-element ns-prefix) facets)))))
(def cmr-facet-name->echo-facet-keyword
"A mapping of CMR facet names to ECHO facet keywords"
{"archive_center" :archive-center
"project" :campaign-sn
"platform" :platform-sn
"instrument" :instrument-sn
"sensor" :sensor-sn
"two_d_coordinate_system_name" :twod-coord-name
"processing_level_id" :processing-level
"category" :category-keyword
"topic" :topic-keyword
"term" :term-keyword
"variable_level_1" :variable-level-1-keyword
"variable_level_2" :variable-level-2-keyword
"variable_level_3" :variable-level-3-keyword
"detailed_variable" :detailed-variable-keyword})
(defn- facet->echo-xml-element
[facet]
(let [{:keys [field value-counts]} facet
field-key (cmr-facet-name->echo-facet-keyword field)]
(x/element field-key {:type "array"}
(for [[value value-count] value-counts]
(x/element field-key {}
(x/element :term {} value)
(x/element :count {:type "integer"} value-count))))))
(defn facets->echo-xml-element
"Helper function for converting facets into an XML element in echo format"
[facets]
(when facets
(x/element :hash {}
(map facet->echo-xml-element
;; Only include facets which are present in ECHO
(filter #(cmr-facet-name->echo-facet-keyword (:field %))
facets)))))
(defn- value-count->echo-json
"Returns value count in echo json format"
[value-count]
(let [[value value-count] value-count]
{:count value-count
:term value}))
(defn- facet->echo-json
[facet]
(let [{:keys [field value-counts]} facet
field-key (csk/->snake_case_string (cmr-facet-name->echo-facet-keyword field))]
[field-key (map value-count->echo-json value-counts)]))
(defn facets->echo-json
"Helper function for converting facets into an XML element in echo format"
[facets]
(when facets
(into {} (map facet->echo-json
;; Only include facets which are present in ECHO
(filter #(cmr-facet-name->echo-facet-keyword (:field %))
facets)))))
(comment)
;; See below for snippets of the data structures used for building hierarchical facets
;; 1) The elastic aggregations query for hierarchical facets
;; GET 1_collections_v2/collection/_search
; {
; "query": {
; "match_all": {}
; },
; "size": 0,
; "aggs": {
; "science_keywords": {
; "nested": {
; "path": "science-keywords"
; },
; "aggs": {
; "category": {
; "terms": {
; "field": "science-keywords.category"
; },
; "aggs": {
; "category-coll-count": {
; "reverse_nested": {},
; "aggs": {
; "concept-id": {
; "terms": {
; "field": "concept-id",
; "size": 1
; }
; }
; }
; },
; "topic": {
; ;; ... same structure as category
; ;; repeats for each term in the science keyword hierarchy
;; Snippet of the elastic response for hierarchical facets
; "aggregations": {
; "science_keywords": {
; "doc_count": 14,
; "category": {
; "doc_count_error_upper_bound": 0,
; "sum_other_doc_count": 0,
; "buckets": [
; {
; "key": "<KEY>",
; "doc_count": 6,
; "category-coll-count": {
; "doc_count": 2,
; "concept-id": {
; "doc_count_error_upper_bound": 0,
; "sum_other_doc_count": 1,
; "buckets": [
; {
; "key": "<KEY>",
; "doc_count": 1
; }
; ]
; }
; },
; "topic": {
; ...
;; Hierarchical facets json response
; }, {
; "field" : "detailed_variable",
; "value-counts" : [ [ "Detail1", 2 ], [ "UNIVERSAL", 2 ] ]
; }, {
; "field" : "science_keywords",
; "subfields" : [ "category" ],
; "category" : [ {
; "value" : "Hurricane",
; "count" : 2,
; "subfields" : [ "topic" ],
; "topic" : [ {
; "value" : "Popular",
; ...
;
| true | (ns cmr.search.services.query-execution.facets.facets-results-feature
"This enables returning facets with collection search results"
(:require [cmr.common-app.services.search.query-execution :as query-execution]
[cmr.common-app.services.kms-fetcher :as kms-fetcher]
[cmr.common-app.services.search.results-model :as r]
[camel-snake-kebab.core :as csk]
[clojure.data.xml :as x]))
(def UNLIMITED_TERMS_SIZE
"The maximum number of results to return from any terms query"
;; FIXME: We shouldn't try to handle this many different values.
;; We should have a limit and if that's exceeded in the elastic response we should note that in
;; the values returned. This can be handled as a part of CMR-1101.
10000)
(defn- terms-facet
[field]
{:terms {:field field :size UNLIMITED_TERMS_SIZE}})
(def collection-count-aggregation
"Used to build an aggregation to get a count of unique concepts included in the current nested
aggregation."
{:reverse_nested {}
:aggs {:concept-id {:terms {:field :concept-id :size 1}}}})
(def hierarchical-facet-order
"Order in which hierarchical facets are returned in the facet response."
[:data-centers :archive-centers :platforms :instruments :science-keywords :location-keywords])
(defn- hierarchical-aggregation-builder
"Build an aggregations query for the given hierarchical field."
[field field-hierarchy]
(when-let [subfield (first field-hierarchy)]
{subfield {:terms {:field (str (name field) "." (name subfield))
:size UNLIMITED_TERMS_SIZE}
:aggs (merge {:coll-count collection-count-aggregation}
(hierarchical-aggregation-builder field (rest field-hierarchy)))}}))
(defn- nested-facet
"Returns the nested aggregation query for the given hierarchical field."
[field]
;; Removing field :url because it's necessary in keyword search but not in facets.
{:nested {:path field}
:aggs (hierarchical-aggregation-builder field (remove #{:url} (field kms-fetcher/nested-fields-mappings)))})
(def ^:private flat-facet-aggregations
"This is the aggregations map that will be passed to elasticsearch to request faceted results
from a collection search."
{:data-center (terms-facet :data-center)
:archive-center (terms-facet :archive-center)
:project (terms-facet :project-sn2)
:platform (terms-facet :platform-sn)
:instrument (terms-facet :instrument-sn)
:sensor (terms-facet :sensor-sn)
:two-d-coordinate-system-name (terms-facet :two-d-coord-name)
:processing-level-id (terms-facet :processing-level-id)
:category (terms-facet :category)
:topic (terms-facet :topic)
:term (terms-facet :term)
:variable-level-1 (terms-facet :variable-level-1)
:variable-level-2 (terms-facet :variable-level-2)
:variable-level-3 (terms-facet :variable-level-3)
:detailed-variable (terms-facet :detailed-variable)})
(def ^:private hierarchical-facet-aggregations
"This is the aggregations map that will be passed to elasticsearch to request faceted results
from a collection search."
{:data-centers (nested-facet :data-centers)
:archive-centers (nested-facet :archive-centers)
:project (terms-facet :project-sn2)
:platforms (nested-facet :platforms)
:instruments (nested-facet :instruments)
:sensor (terms-facet :sensor-sn)
:two-d-coordinate-system-name (terms-facet :two-d-coord-name)
:processing-level-id (terms-facet :processing-level-id)
:location-keywords (nested-facet :location-keywords)
:science-keywords (nested-facet :science-keywords)
;; Detailed variable is technically part of the science keyword hierarchy directly below
;; variable level 1 (at the same level as variable level 2.)
;; Opened ticket CMR-1722 to address.
:detailed-variable (terms-facet :detailed-variable)})
(defmethod query-execution/pre-process-query-result-feature :facets
[context query feature]
(assoc query :aggregations flat-facet-aggregations))
(defmethod query-execution/pre-process-query-result-feature :hierarchical-facets
[context query feature]
(assoc query :aggregations hierarchical-facet-aggregations))
(defn buckets->value-count-pairs
"Processes an elasticsearch aggregation response of buckets to a sequence of value and count
tuples"
[bucket-map]
(->> bucket-map
:buckets
(map (fn [{v :key n :doc_count}]
[v n]))))
(defn- bucket-map->facets
"Takes a map of elastic aggregation results containing keys to buckets and a list of the bucket
names. Returns a facet map of those specific names with value count pairs"
[bucket-map field-names]
(for [field-name field-names]
(r/map->Facet
{:field (csk/->snake_case_string field-name)
:value-counts (buckets->value-count-pairs (get bucket-map field-name))})))
(defn- parse-hierarchical-bucket
"Parses the elasticsearch aggregations response for hierarchical fields."
[field-hierarchy bucket-map]
(when-let [field (first field-hierarchy)]
(let [empty-response {:subfields []}
value-counts (for [bucket (get-in bucket-map [field :buckets])
:let [sub-facets (parse-hierarchical-bucket (rest field-hierarchy)
bucket)]]
(merge (when-not (= sub-facets empty-response)
sub-facets)
{:count (get-in bucket [:coll-count :doc_count] (:doc_count bucket))
:value (:key bucket)}))]
(if (seq value-counts)
(let [field-snake-case (csk/->snake_case_string field)]
{:subfields [field-snake-case]
field-snake-case value-counts})
empty-response))))
(defn- hierarchical-bucket-map->facets
"Takes a map of elastic aggregation results for a nested field. Returns a hierarchical facet for
that field."
[field bucket-map]
(parse-hierarchical-bucket (field kms-fetcher/nested-fields-mappings) bucket-map))
(defn- create-hierarchical-facets
"Create the facets response with hierarchical facets. Takes an elastic aggregations result and
returns the facets."
[elastic-aggregations]
(concat (bucket-map->facets (apply dissoc elastic-aggregations hierarchical-facet-order)
[:project :sensor :two-d-coordinate-system-name
:processing-level-id :detailed-variable])
(map (fn [field]
(assoc (hierarchical-bucket-map->facets field (field elastic-aggregations))
:field (csk/->snake_case_string field))) hierarchical-facet-order)))
(defn- create-flat-facets
"Create the facets response with flat facets. Takes an elastic aggregations result and returns
the facets."
[elastic-aggregations]
(bucket-map->facets
elastic-aggregations
;; Specified here so that order will be consistent with results
[:data-center :archive-center :project :platform :instrument :sensor
:two-d-coordinate-system-name :processing-level-id :category :topic :term
:variable-level-1 :variable-level-2 :variable-level-3 :detailed-variable]))
(defmethod query-execution/post-process-query-result-feature :facets
[_ _ {:keys [aggregations]} query-results _]
(assoc query-results :facets (create-flat-facets aggregations)))
(defmethod query-execution/post-process-query-result-feature :hierarchical-facets
[_ _ {:keys [aggregations]} query-results _]
(assoc query-results :facets (create-hierarchical-facets aggregations)))
(defn- key-with-prefix
[prefix k]
(if prefix
(symbol (str prefix ":" (name k)))
k))
(defn- value-count-maps->xml-element
"Converts a list of value-count-maps into an XML element."
[ns-prefix value-count-maps]
(let [with-prefix (partial key-with-prefix ns-prefix)]
(x/element (with-prefix :value-count-maps) {}
(for [value-count-map value-count-maps]
(if-let [subfield-name (first (:subfields value-count-map))]
(when-let [subfield-facets (get value-count-map subfield-name)]
(let [child-facets (x/element (with-prefix :facet)
{:field (name subfield-name)}
(value-count-maps->xml-element ns-prefix
subfield-facets))]
(x/element (with-prefix :value-count-map) {}
[(x/element (with-prefix :value)
{:count (:count value-count-map)}
(:value value-count-map))
child-facets])))
(x/element (with-prefix :value-count-map) {}
(x/element (with-prefix :value)
{:count (:count value-count-map)}
(:value value-count-map))))))))
(defn- facet->xml-element
"Helper function for converting a facet result into an XML element"
[ns-prefix {:keys [field value-counts subfields] :as facet}]
(let [with-prefix (partial key-with-prefix ns-prefix)
xml-element-content
(if-let [subfield (first subfields)]
(x/element (with-prefix :facet)
{:field (name subfield)}
(value-count-maps->xml-element ns-prefix (get facet subfield)))
(for [[value value-count] value-counts]
(x/element (with-prefix :value) {:count value-count} value)))]
(x/element (with-prefix :facet) {:field (name field)} xml-element-content)))
(defn facets->xml-element
"Converts a facets result into an XML element"
([facets]
(facets->xml-element nil facets))
([ns-prefix facets]
(when facets
(x/element (key-with-prefix ns-prefix :facets) {}
(map (partial facet->xml-element ns-prefix) facets)))))
(def cmr-facet-name->echo-facet-keyword
"A mapping of CMR facet names to ECHO facet keywords"
{"archive_center" :archive-center
"project" :campaign-sn
"platform" :platform-sn
"instrument" :instrument-sn
"sensor" :sensor-sn
"two_d_coordinate_system_name" :twod-coord-name
"processing_level_id" :processing-level
"category" :category-keyword
"topic" :topic-keyword
"term" :term-keyword
"variable_level_1" :variable-level-1-keyword
"variable_level_2" :variable-level-2-keyword
"variable_level_3" :variable-level-3-keyword
"detailed_variable" :detailed-variable-keyword})
(defn- facet->echo-xml-element
[facet]
(let [{:keys [field value-counts]} facet
field-key (cmr-facet-name->echo-facet-keyword field)]
(x/element field-key {:type "array"}
(for [[value value-count] value-counts]
(x/element field-key {}
(x/element :term {} value)
(x/element :count {:type "integer"} value-count))))))
(defn facets->echo-xml-element
"Helper function for converting facets into an XML element in echo format"
[facets]
(when facets
(x/element :hash {}
(map facet->echo-xml-element
;; Only include facets which are present in ECHO
(filter #(cmr-facet-name->echo-facet-keyword (:field %))
facets)))))
(defn- value-count->echo-json
"Returns value count in echo json format"
[value-count]
(let [[value value-count] value-count]
{:count value-count
:term value}))
(defn- facet->echo-json
[facet]
(let [{:keys [field value-counts]} facet
field-key (csk/->snake_case_string (cmr-facet-name->echo-facet-keyword field))]
[field-key (map value-count->echo-json value-counts)]))
(defn facets->echo-json
"Helper function for converting facets into an XML element in echo format"
[facets]
(when facets
(into {} (map facet->echo-json
;; Only include facets which are present in ECHO
(filter #(cmr-facet-name->echo-facet-keyword (:field %))
facets)))))
(comment)
;; See below for snippets of the data structures used for building hierarchical facets
;; 1) The elastic aggregations query for hierarchical facets
;; GET 1_collections_v2/collection/_search
; {
; "query": {
; "match_all": {}
; },
; "size": 0,
; "aggs": {
; "science_keywords": {
; "nested": {
; "path": "science-keywords"
; },
; "aggs": {
; "category": {
; "terms": {
; "field": "science-keywords.category"
; },
; "aggs": {
; "category-coll-count": {
; "reverse_nested": {},
; "aggs": {
; "concept-id": {
; "terms": {
; "field": "concept-id",
; "size": 1
; }
; }
; }
; },
; "topic": {
; ;; ... same structure as category
; ;; repeats for each term in the science keyword hierarchy
;; Snippet of the elastic response for hierarchical facets
; "aggregations": {
; "science_keywords": {
; "doc_count": 14,
; "category": {
; "doc_count_error_upper_bound": 0,
; "sum_other_doc_count": 0,
; "buckets": [
; {
; "key": "PI:KEY:<KEY>END_PI",
; "doc_count": 6,
; "category-coll-count": {
; "doc_count": 2,
; "concept-id": {
; "doc_count_error_upper_bound": 0,
; "sum_other_doc_count": 1,
; "buckets": [
; {
; "key": "PI:KEY:<KEY>END_PI",
; "doc_count": 1
; }
; ]
; }
; },
; "topic": {
; ...
;; Hierarchical facets json response
; }, {
; "field" : "detailed_variable",
; "value-counts" : [ [ "Detail1", 2 ], [ "UNIVERSAL", 2 ] ]
; }, {
; "field" : "science_keywords",
; "subfields" : [ "category" ],
; "category" : [ {
; "value" : "Hurricane",
; "count" : 2,
; "subfields" : [ "topic" ],
; "topic" : [ {
; "value" : "Popular",
; ...
;
|
[
{
"context": "ctory/getLogger (str *ns*)))\n\n(def ^:const admin \"jari.rosti@gmail.com\")\n\n(defn reg-body [user]\n (str \"Hei \" user \"!\\n\\",
"end": 226,
"score": 0.9999325275421143,
"start": 206,
"tag": "EMAIL",
"value": "jari.rosti@gmail.com"
},
{
"context": "\n \"tai lähettämällä sähköpostia osoitteeseen ontrail@ontrail.net\\n\\n\"\n\n \"Yleisimmin kysyttyihin kysymyksiin ",
"end": 496,
"score": 0.9998384118080139,
"start": 477,
"tag": "EMAIL",
"value": "ontrail@ontrail.net"
},
{
"context": ".info logger (str (postal/send-message {:from \"ontrail@ontrail.net\"\n ",
"end": 839,
"score": 0.9999204277992249,
"start": 820,
"tag": "EMAIL",
"value": "ontrail@ontrail.net"
}
] | src/ontrail/emails.clj | jrosti/ontrail | 1 | (ns ontrail.emails
(:require [postal.core :as postal]
[clojure.stacktrace :as stacktrace]))
(def #^{:private true} logger (org.slf4j.LoggerFactory/getLogger (str *ns*)))
(def ^:const admin "jari.rosti@gmail.com")
(defn reg-body [user]
(str "Hei " user "!\n\n"
"Tervetuloa käyttämään Ontrailia!\n\n"
"Ontrailin ylläpidon tavoittaa Facebook-ryhmässä: https://www.facebook.com/groups/ontrail/\n"
"tai lähettämällä sähköpostia osoitteeseen ontrail@ontrail.net\n\n"
"Yleisimmin kysyttyihin kysymyksiin löydät vastauksia ylläpitäjän sivuilta ontrailista osoitteesta\n\n"
"http://ontrail.net/#user/admin\n\n"
"--\nYstävällisin terveisin, Ontrail-tiimi"))
(defn send-register-msg [user email]
(try
(future (.info logger (str (postal/send-message {:from "ontrail@ontrail.net"
:to [email]
:cc [admin]
:subject "Tervetuloa Ontrailiin!"
:body (reg-body user)}))))
(catch Exception exception
(.error logger (str exception))
(stacktrace/print-stack-trace exception 100)
nil))) | 108611 | (ns ontrail.emails
(:require [postal.core :as postal]
[clojure.stacktrace :as stacktrace]))
(def #^{:private true} logger (org.slf4j.LoggerFactory/getLogger (str *ns*)))
(def ^:const admin "<EMAIL>")
(defn reg-body [user]
(str "Hei " user "!\n\n"
"Tervetuloa käyttämään Ontrailia!\n\n"
"Ontrailin ylläpidon tavoittaa Facebook-ryhmässä: https://www.facebook.com/groups/ontrail/\n"
"tai lähettämällä sähköpostia osoitteeseen <EMAIL>\n\n"
"Yleisimmin kysyttyihin kysymyksiin löydät vastauksia ylläpitäjän sivuilta ontrailista osoitteesta\n\n"
"http://ontrail.net/#user/admin\n\n"
"--\nYstävällisin terveisin, Ontrail-tiimi"))
(defn send-register-msg [user email]
(try
(future (.info logger (str (postal/send-message {:from "<EMAIL>"
:to [email]
:cc [admin]
:subject "Tervetuloa Ontrailiin!"
:body (reg-body user)}))))
(catch Exception exception
(.error logger (str exception))
(stacktrace/print-stack-trace exception 100)
nil))) | true | (ns ontrail.emails
(:require [postal.core :as postal]
[clojure.stacktrace :as stacktrace]))
(def #^{:private true} logger (org.slf4j.LoggerFactory/getLogger (str *ns*)))
(def ^:const admin "PI:EMAIL:<EMAIL>END_PI")
(defn reg-body [user]
(str "Hei " user "!\n\n"
"Tervetuloa käyttämään Ontrailia!\n\n"
"Ontrailin ylläpidon tavoittaa Facebook-ryhmässä: https://www.facebook.com/groups/ontrail/\n"
"tai lähettämällä sähköpostia osoitteeseen PI:EMAIL:<EMAIL>END_PI\n\n"
"Yleisimmin kysyttyihin kysymyksiin löydät vastauksia ylläpitäjän sivuilta ontrailista osoitteesta\n\n"
"http://ontrail.net/#user/admin\n\n"
"--\nYstävällisin terveisin, Ontrail-tiimi"))
(defn send-register-msg [user email]
(try
(future (.info logger (str (postal/send-message {:from "PI:EMAIL:<EMAIL>END_PI"
:to [email]
:cc [admin]
:subject "Tervetuloa Ontrailiin!"
:body (reg-body user)}))))
(catch Exception exception
(.error logger (str exception))
(stacktrace/print-stack-trace exception 100)
nil))) |
[
{
"context": "epl.clj\")\n\n(def system (pro/connect {:access-key \"mbrainz\"\n :secret \"mbrainz\"\n ",
"end": 70,
"score": 0.9990532398223877,
"start": 63,
"tag": "KEY",
"value": "mbrainz"
},
{
"context": "-key \"mbrainz\"\n :secret \"mbrainz\"\n :region \"none\"\n ",
"end": 114,
"score": 0.9990513920783997,
"start": 107,
"tag": "KEY",
"value": "mbrainz"
}
] | examples/explore_db.clj | jeffp42ker/mbrainz-importer | 73 | (load-file "repl.clj")
(def system (pro/connect {:access-key "mbrainz"
:secret "mbrainz"
:region "none"
:endpoint "localhost:8998"
:service "peer-server"}))
(def conn (<!! (client/connect system {:db-name "mbrainz"})))
(def db (client/db conn))
(def unique-attrs (->> (client/q conn {:query '[:find ?attr
:where
[?e :db/unique]
[?e :db/ident ?attr]]
:args [db]})
(a/transduce (comp (halt-when ::anom/category)
(map #(map first %)))
into [])
<!!))
;; how many of each unique entity type?
(->> unique-attrs
(mapv #(client/q conn {:query '[:find ?attr (count ?e)
:in $ ?attr
:where [?e ?attr]]
:args [db %]}))
(transduce
(comp (map <!!) (halt-when ::anom/category))
into {}))
(defn batch-entity
[batch-id]
(str/replace batch-id #"-.*" ""))
(->> (client/q conn {:query '[:find ?id
:where [_ :mbrainz.initial-import/batch-id ?id]]
:args [db]})
(a/transduce
(comp (halt-when ::anom/category)
(map #(map (comp batch-entity first) %)))
into [])
<!!
frequencies)
| 28908 | (load-file "repl.clj")
(def system (pro/connect {:access-key "<KEY>"
:secret "<KEY>"
:region "none"
:endpoint "localhost:8998"
:service "peer-server"}))
(def conn (<!! (client/connect system {:db-name "mbrainz"})))
(def db (client/db conn))
(def unique-attrs (->> (client/q conn {:query '[:find ?attr
:where
[?e :db/unique]
[?e :db/ident ?attr]]
:args [db]})
(a/transduce (comp (halt-when ::anom/category)
(map #(map first %)))
into [])
<!!))
;; how many of each unique entity type?
(->> unique-attrs
(mapv #(client/q conn {:query '[:find ?attr (count ?e)
:in $ ?attr
:where [?e ?attr]]
:args [db %]}))
(transduce
(comp (map <!!) (halt-when ::anom/category))
into {}))
(defn batch-entity
[batch-id]
(str/replace batch-id #"-.*" ""))
(->> (client/q conn {:query '[:find ?id
:where [_ :mbrainz.initial-import/batch-id ?id]]
:args [db]})
(a/transduce
(comp (halt-when ::anom/category)
(map #(map (comp batch-entity first) %)))
into [])
<!!
frequencies)
| true | (load-file "repl.clj")
(def system (pro/connect {:access-key "PI:KEY:<KEY>END_PI"
:secret "PI:KEY:<KEY>END_PI"
:region "none"
:endpoint "localhost:8998"
:service "peer-server"}))
(def conn (<!! (client/connect system {:db-name "mbrainz"})))
(def db (client/db conn))
(def unique-attrs (->> (client/q conn {:query '[:find ?attr
:where
[?e :db/unique]
[?e :db/ident ?attr]]
:args [db]})
(a/transduce (comp (halt-when ::anom/category)
(map #(map first %)))
into [])
<!!))
;; how many of each unique entity type?
(->> unique-attrs
(mapv #(client/q conn {:query '[:find ?attr (count ?e)
:in $ ?attr
:where [?e ?attr]]
:args [db %]}))
(transduce
(comp (map <!!) (halt-when ::anom/category))
into {}))
(defn batch-entity
[batch-id]
(str/replace batch-id #"-.*" ""))
(->> (client/q conn {:query '[:find ?id
:where [_ :mbrainz.initial-import/batch-id ?id]]
:args [db]})
(a/transduce
(comp (halt-when ::anom/category)
(map #(map (comp batch-entity first) %)))
into [])
<!!
frequencies)
|
[
{
"context": "(ns #^{:author \"Roger Allen\"\n :doc \"Shadertoy-like core library.\"}\n sh",
"end": 27,
"score": 0.9998422861099243,
"start": 16,
"tag": "NAME",
"value": "Roger Allen"
},
{
"context": "=====\n;; code modified from\n;; https://github.com/ztellman/penumbra/blob/master/src/penumbra/opengl/core.clj",
"end": 3557,
"score": 0.998434841632843,
"start": 3549,
"tag": "USERNAME",
"value": "ztellman"
}
] | src/shadertone/shader.clj | baskeboler/shadertone | 304 | (ns #^{:author "Roger Allen"
:doc "Shadertoy-like core library."}
shadertone.shader
(:require [watchtower.core :as watcher]
clojure.string)
(:import (java.awt.image BufferedImage DataBuffer DataBufferByte WritableRaster)
(java.io File FileInputStream)
(java.nio IntBuffer ByteBuffer FloatBuffer ByteOrder)
(java.util Calendar)
(javax.imageio ImageIO)
(java.lang.reflect Field)
(org.lwjgl BufferUtils)
(org.lwjgl.input Mouse)
(org.lwjgl.opengl ContextAttribs Display DisplayMode
GL11 GL12 GL13 GL15 GL20
PixelFormat)))
;; ======================================================================
;; State Variables
;; a map of state variables for use in the gl thread
(defonce default-state-values
{:active :no ;; :yes/:stopping/:no
:width 0
:height 0
:title ""
:display-sync-hz 60
:start-time 0
:last-time 0
;; mouse
:mouse-clicked false
:mouse-pos-x 0
:mouse-pos-y 0
:mouse-ori-x 0
:mouse-ori-y 0
;; geom ids
:vbo-id 0
:vertices-count 0
;; shader program
:shader-good true ;; false in error condition
:shader-filename nil
:shader-str-atom (atom nil)
:shader-str ""
:vs-id 0
:fs-id 0
:pgm-id 0
;; shader uniforms
:i-resolution-loc 0
:i-global-time-loc 0
:i-channel-time-loc 0
:i-mouse-loc 0
:i-channel-loc [0 0 0 0]
:i-channel-res-loc 0
:i-date-loc 0
:channel-time-buffer (-> (BufferUtils/createFloatBuffer 4)
(.put (float-array
[0.0 0.0 0.0 0.0]))
(.flip))
:channel-res-buffer (-> (BufferUtils/createFloatBuffer (* 3 4))
(.put (float-array
[0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0]))
(.flip))
;; textures
:tex-filenames []
:tex-ids []
:tex-types [] ; :cubemap, :previous-frame
;; a user draw function
:user-fn nil
;; pixel read
:pixel-read-enable false
:pixel-read-pos-x 0
:pixel-read-pos-y 0
:pixel-read-data (-> (BufferUtils/createByteBuffer 3)
(.put (byte-array (map byte [0 0 0])))
(.flip))
})
;; GLOBAL STATE ATOMS
;; Tried to get rid of this atom, but LWJGL is limited to only
;; one window. So, we just keep a single atom containing the
;; current window state here.
(defonce the-window-state (atom default-state-values))
;; The reload-shader atom communicates across the gl & watcher threads
(defonce reload-shader (atom false))
(defonce reload-shader-str (atom ""))
;; Atom for the directory watcher future
(defonce watcher-future (atom (future (fn [] nil))))
;; Flag to help avoid reloading shader right after loading it for the
;; first time.
(defonce watcher-just-started (atom true))
(defonce throw-on-gl-error (atom true))
;;
(defonce pixel-value (atom [0.0 0.0 0.0]))
;; ======================================================================
;; code modified from
;; https://github.com/ztellman/penumbra/blob/master/src/penumbra/opengl/core.clj
(defn- get-fields [#^Class static-class]
(. static-class getFields))
(defn- gl-enum-name
"Takes the numeric value of a gl constant (i.e. GL_LINEAR), and gives the name"
[enum-value]
(if (= 0 enum-value)
"NONE"
(.getName #^Field (some
#(if (= enum-value (.get #^Field % nil)) % nil)
(mapcat get-fields [GL11 GL12 GL13 GL15 GL20])))))
(defn- except-gl-errors
[msg]
(let [error (GL11/glGetError)
error-string (str "OpenGL Error(" error "):"
(gl-enum-name error) ": " msg)]
(if (and (not (zero? error)) @throw-on-gl-error)
(throw (Exception. error-string)))))
;; ======================================================================
(defn- fill-tex-filenames
"return a vector of 4 items, always. Use nil if no filename"
[tex-filenames]
(apply vector
(for [i (range 4)]
(if (< i (count tex-filenames))
(nth tex-filenames i)))))
(defn- uniform-sampler-type-str
[tex-types n]
(format "uniform sampler%s iChannel%s;\n"
(if (= :cubemap (nth tex-types 0)) "Cube" "2D")
n))
(defn- slurp-fs
"do whatever it takes to modify shadertoy fragment shader source to
be useable"
[locals filename]
(let [{:keys [tex-types]} @locals
;;file-str (slurp filename)
file-str (str "#version 120\n"
"uniform vec3 iResolution;\n"
"uniform float iGlobalTime;\n"
"uniform float iChannelTime[4];\n"
"uniform vec3 iChannelResolution[4];\n"
"uniform vec4 iMouse;\n"
(uniform-sampler-type-str tex-types 0)
(uniform-sampler-type-str tex-types 1)
(uniform-sampler-type-str tex-types 2)
(uniform-sampler-type-str tex-types 3)
"uniform vec4 iDate;\n"
"\n"
(slurp filename))]
file-str))
(defn- cubemap-filename?
"if a filename contains a '*' char, it is a cubemap"
[filename]
(if (string? filename)
(not (nil? (re-find #"\*" filename)))
false))
(defn- get-texture-type
[tex-filename]
(cond
(cubemap-filename? tex-filename) :cubemap
(= :previous-frame tex-filename) :previous-frame
:default :twod))
(defn- init-window
"Initialise a shader-powered window with the specified
display-mode. If true-fullscreen? is true, fullscreen mode is
attempted if the display-mode is compatible. See display-modes for a
list of available modes and fullscreen-display-modes for a list of
fullscreen compatible modes.."
[locals display-mode title shader-filename shader-str-atom tex-filenames true-fullscreen? user-fn display-sync-hz]
(let [width (.getWidth ^DisplayMode display-mode)
height (.getHeight ^DisplayMode display-mode)
pixel-format (PixelFormat.)
context-attributes (-> (ContextAttribs. 2 1)) ;; GL2.1
current-time-millis (System/currentTimeMillis)
tex-filenames (fill-tex-filenames tex-filenames)
tex-types (map get-texture-type tex-filenames)]
(swap! locals
assoc
:active :yes
:width width
:height height
:title title
:display-sync-hz display-sync-hz
:start-time current-time-millis
:last-time current-time-millis
:shader-filename shader-filename
:shader-str-atom shader-str-atom
:tex-filenames tex-filenames
:tex-types tex-types
:user-fn user-fn)
;; slurp-fs requires :tex-types, so we need a 2 pass setup
(let [shader-str (if (nil? shader-filename)
@shader-str-atom
(slurp-fs locals (:shader-filename @locals)))]
(swap! locals assoc :shader-str shader-str)
(Display/setDisplayMode display-mode)
(when true-fullscreen?
(Display/setFullscreen true))
(Display/setTitle title)
(Display/setVSyncEnabled true)
(Display/setLocation 0 0)
(Display/create pixel-format context-attributes))))
(defn- init-buffers
[locals]
(let [vertices (float-array
[-1.0 -1.0 0.0 1.0
1.0 -1.0 0.0 1.0
-1.0 1.0 0.0 1.0
-1.0 1.0 0.0 1.0
1.0 -1.0 0.0 1.0
1.0 1.0 0.0 1.0])
vertices-buffer (-> (BufferUtils/createFloatBuffer (count vertices))
(.put vertices)
(.flip))
vertices-count (count vertices)
vbo-id (GL15/glGenBuffers)
_ (GL15/glBindBuffer GL15/GL_ARRAY_BUFFER vbo-id)
_ (GL15/glBufferData GL15/GL_ARRAY_BUFFER
^FloatBuffer vertices-buffer
GL15/GL_STATIC_DRAW)
_ (except-gl-errors "@ end of init-buffers")]
(swap! locals
assoc
:vbo-id vbo-id
:vertices-count vertices-count)))
(def vs-shader
(str "#version 120\n"
"void main(void) {\n"
" gl_Position = gl_Vertex;\n"
"}\n"))
(defn- load-shader
[^String shader-str ^Integer shader-type]
(let [shader-id (GL20/glCreateShader shader-type)
_ (except-gl-errors "@ load-shader glCreateShader ")
_ (GL20/glShaderSource shader-id shader-str)
_ (except-gl-errors "@ load-shader glShaderSource ")
_ (GL20/glCompileShader shader-id)
_ (except-gl-errors "@ load-shader glCompileShader ")
gl-compile-status (GL20/glGetShaderi shader-id GL20/GL_COMPILE_STATUS)
_ (except-gl-errors "@ end of let load-shader")]
(when (== gl-compile-status GL11/GL_FALSE)
(println "ERROR: Loading a Shader:")
(println (GL20/glGetShaderInfoLog shader-id 10000)))
[gl-compile-status shader-id]))
(defn- init-shaders
[locals]
(let [[ok? vs-id] (load-shader vs-shader GL20/GL_VERTEX_SHADER)
_ (assert (== ok? GL11/GL_TRUE)) ;; something is really wrong if our vs is bad
_ (if (nil? (:shader-filename @locals))
(println "Loading shader from string")
(println "Loading shader from file:" (:shader-filename @locals)))
[ok? fs-id] (load-shader (:shader-str @locals) GL20/GL_FRAGMENT_SHADER)]
(if (== ok? GL11/GL_TRUE)
(let [pgm-id (GL20/glCreateProgram)
_ (except-gl-errors "@ let init-shaders glCreateProgram")
_ (GL20/glAttachShader pgm-id vs-id)
_ (except-gl-errors "@ let init-shaders glAttachShader VS")
_ (GL20/glAttachShader pgm-id fs-id)
_ (except-gl-errors "@ let init-shaders glAttachShader FS")
_ (GL20/glLinkProgram pgm-id)
_ (except-gl-errors "@ let init-shaders glLinkProgram")
gl-link-status (GL20/glGetProgrami pgm-id GL20/GL_LINK_STATUS)
_ (except-gl-errors "@ let init-shaders glGetProgram link status")
_ (when (== gl-link-status GL11/GL_FALSE)
(println "ERROR: Linking Shaders:")
(println (GL20/glGetProgramInfoLog pgm-id 10000)))
_ (except-gl-errors "@ let before GetUniformLocation")
i-resolution-loc (GL20/glGetUniformLocation pgm-id "iResolution")
i-global-time-loc (GL20/glGetUniformLocation pgm-id "iGlobalTime")
i-channel-time-loc (GL20/glGetUniformLocation pgm-id "iChannelTime")
i-mouse-loc (GL20/glGetUniformLocation pgm-id "iMouse")
i-channel0-loc (GL20/glGetUniformLocation pgm-id "iChannel0")
i-channel1-loc (GL20/glGetUniformLocation pgm-id "iChannel1")
i-channel2-loc (GL20/glGetUniformLocation pgm-id "iChannel2")
i-channel3-loc (GL20/glGetUniformLocation pgm-id "iChannel3")
i-channel-res-loc (GL20/glGetUniformLocation pgm-id "iChannelResolution")
i-date-loc (GL20/glGetUniformLocation pgm-id "iDate")
_ (except-gl-errors "@ end of let init-shaders")
]
(swap! locals
assoc
:shader-good true
:vs-id vs-id
:fs-id fs-id
:pgm-id pgm-id
:i-resolution-loc i-resolution-loc
:i-global-time-loc i-global-time-loc
:i-channel-time-loc i-channel-time-loc
:i-mouse-loc i-mouse-loc
:i-channel-loc [i-channel0-loc i-channel1-loc i-channel2-loc i-channel3-loc]
:i-channel-res-loc i-channel-res-loc
:i-date-loc i-date-loc))
;; we didn't load the shader, don't be drawing
(swap! locals assoc :shader-good false))))
(defn- buffer-swizzle-0123-1230
"given a ARGB pixel array, swizzle it to be RGBA. Or, ABGR to BGRA"
^bytes [^bytes data] ;; Wow! That ^bytes changes this from 10s for a 256x256 tex to instantaneous.
(dotimes [i (/ (alength data) 4)]
(let [i0 (* i 4)
i1 (inc i0)
i2 (inc i1)
i3 (inc i2)
tmp (aget data i0)]
(aset data i0 (aget data i1))
(aset data i1 (aget data i2))
(aset data i2 (aget data i3))
(aset data i3 tmp)))
data)
(defn- cubemap-filename
[filename i]
(clojure.string/replace filename "*" (str i)))
(defn- put-texture-data
"put the data from the image into the buffer and return the buffer"
^ByteBuffer
[^ByteBuffer buffer ^BufferedImage image ^Boolean swizzle-0123-1230]
(let [data ^bytes (-> ^WritableRaster (.getRaster image)
^DataBufferByte (.getDataBuffer)
(.getData))
data (if swizzle-0123-1230
(buffer-swizzle-0123-1230 data)
data)
buffer (.put buffer data 0 (alength data))] ; (.order (ByteOrder/nativeOrder)) ?
buffer))
(defn- tex-image-bytes
"return the number of bytes per pixel in this image"
[^BufferedImage image]
(let [image-type (.getType image)
image-bytes (if (or (= image-type BufferedImage/TYPE_3BYTE_BGR)
(= image-type BufferedImage/TYPE_INT_RGB))
3
(if (or (= image-type BufferedImage/TYPE_4BYTE_ABGR)
(= image-type BufferedImage/TYPE_INT_ARGB))
4
0)) ;; unhandled image type--what to do?
;; _ (println "image-type"
;; (cond
;; (= image-type BufferedImage/TYPE_3BYTE_BGR) "TYPE_3BYTE_BGR"
;; (= image-type BufferedImage/TYPE_INT_RGB) "TYPE_INT_RGB"
;; (= image-type BufferedImage/TYPE_4BYTE_ABGR) "TYPE_4BYTE_ABGR"
;; (= image-type BufferedImage/TYPE_INT_ARGB) "TYPE_INT_ARGB"
;; :else image-type))
_ (assert (pos? image-bytes))] ;; die on unhandled image
image-bytes))
(defn- tex-internal-format
"return the internal-format for the glTexImage2D call for this image"
^Integer
[^BufferedImage image]
(let [image-type (.getType image)
internal-format (cond
(= image-type BufferedImage/TYPE_3BYTE_BGR) GL11/GL_RGB8
(= image-type BufferedImage/TYPE_INT_RGB) GL11/GL_RGB8
(= image-type BufferedImage/TYPE_4BYTE_ABGR) GL11/GL_RGBA8
(= image-type BufferedImage/TYPE_INT_ARGB) GL11/GL_RGBA8)]
internal-format))
(defn- tex-format
"return the format for the glTexImage2D call for this image"
^Integer
[^BufferedImage image]
(let [image-type (.getType image)
format (cond
(= image-type BufferedImage/TYPE_3BYTE_BGR) GL12/GL_BGR
(= image-type BufferedImage/TYPE_INT_RGB) GL11/GL_RGB
(= image-type BufferedImage/TYPE_4BYTE_ABGR) GL12/GL_BGRA
(= image-type BufferedImage/TYPE_INT_ARGB) GL11/GL_RGBA)]
format))
(defn- load-texture
"load, bind texture from filename. returns a texture info vector
[tex-id width height z]. returns nil tex-id if filename is nil"
([^String filename]
(let [tex-id (GL11/glGenTextures)]
(if (cubemap-filename? filename)
(do
(dotimes [i 6]
(load-texture (cubemap-filename filename i)
GL13/GL_TEXTURE_CUBE_MAP tex-id i))
[tex-id 0.0 0.0 0.0]) ;; cubemaps don't update w/h
(load-texture filename GL11/GL_TEXTURE_2D tex-id 0))))
([^String filename ^Integer target ^Integer tex-id ^Integer i]
(if (string? filename)
;; load from file
(let [_ (println "Loading texture:" filename)
image (ImageIO/read (FileInputStream. filename))
image-bytes (tex-image-bytes image)
internal-format (tex-internal-format image)
format (tex-format image)
nbytes (* image-bytes (.getWidth image) (.getHeight image))
buffer ^ByteBuffer (-> (BufferUtils/createByteBuffer nbytes)
(put-texture-data image (= image-bytes 4))
(.flip))
tex-image-target ^Integer (if (= target GL13/GL_TEXTURE_CUBE_MAP)
(+ i GL13/GL_TEXTURE_CUBE_MAP_POSITIVE_X)
target)]
(GL11/glBindTexture target tex-id)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MAG_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MIN_FILTER GL11/GL_LINEAR)
(if (== target GL11/GL_TEXTURE_2D)
(do
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_S GL11/GL_REPEAT)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_T GL11/GL_REPEAT))
(do ;; CUBE_MAP
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)))
(GL11/glTexImage2D ^Integer tex-image-target 0 ^Integer internal-format
^Integer (.getWidth image) ^Integer (.getHeight image) 0
^Integer format
GL11/GL_UNSIGNED_BYTE
^ByteBuffer buffer)
(except-gl-errors "@ end of load-texture if-stmt")
[tex-id (.getWidth image) (.getHeight image) 1.0])
(if (= filename :previous-frame)
(do ;; :previous-frame initial setup
(println "setting up :previous-frame texture")
(GL11/glBindTexture target tex-id)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MAG_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MIN_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)
(except-gl-errors "@ end of load-texture else-stmt")
;; use negative as flag to indicate using window width, height
[tex-id -1.0 -1.0 1.0])
;; else must be nil texture
[nil 0.0 0.0 0.0]))))
(defn- init-textures
[locals]
(let [tex-infos (map load-texture (:tex-filenames @locals))
;;_ (println "raw" tex-infos)
tex-ids (map first tex-infos)
tex-whd (map rest tex-infos)
tex-whd (flatten
(map #(if (< (first %) 0.0)
[(:width @locals) (:height @locals) 1.0]
%)
tex-whd))
;; update channel-res-buffer
_ (-> ^FloatBuffer (:channel-res-buffer @locals)
(.put ^floats (float-array tex-whd))
(.flip))
]
(swap! locals assoc
:tex-ids tex-ids)))
(defn- init-gl
[locals]
(let [{:keys [width height user-fn]} @locals]
;;(println "OpenGL version:" (GL11/glGetString GL11/GL_VERSION))
(GL11/glClearColor 0.0 0.0 0.0 0.0)
(GL11/glViewport 0 0 width height)
(init-buffers locals)
(init-textures locals)
(init-shaders locals)
(when (and (not (nil? user-fn)) (:shader-good @locals))
(user-fn :init (:pgm-id @locals)))))
(defn- try-reload-shader
[locals]
(let [{:keys [vs-id fs-id pgm-id shader-filename user-fn]} @locals
vs-id (if (= vs-id 0)
(let [[ok? vs-id] (load-shader vs-shader GL20/GL_VERTEX_SHADER)
_ (assert (== ok? GL11/GL_TRUE))]
vs-id)
vs-id)
fs-shader (if (nil? shader-filename)
@reload-shader-str
(slurp-fs locals shader-filename))
[ok? new-fs-id] (load-shader fs-shader GL20/GL_FRAGMENT_SHADER)
_ (reset! reload-shader false)]
(if (== ok? GL11/GL_FALSE)
;; we didn't reload a good shader. Go back to the old one if possible
(when (:shader-good @locals)
(GL20/glUseProgram pgm-id)
(except-gl-errors "@ try-reload-shader useProgram1"))
;; the load shader went well, keep going...
(let [new-pgm-id (GL20/glCreateProgram)
_ (except-gl-errors "@ try-reload-shader glCreateProgram")
_ (GL20/glAttachShader new-pgm-id vs-id)
_ (except-gl-errors "@ try-reload-shader glAttachShader VS")
_ (GL20/glAttachShader new-pgm-id new-fs-id)
_ (except-gl-errors "@ try-reload-shader glAttachShader FS")
_ (GL20/glLinkProgram new-pgm-id)
_ (except-gl-errors "@ try-reload-shader glLinkProgram")
gl-link-status (GL20/glGetProgrami new-pgm-id GL20/GL_LINK_STATUS)
_ (except-gl-errors "@ end of let try-reload-shader")]
(if (== gl-link-status GL11/GL_FALSE)
(do
(println "ERROR: Linking Shaders: (reloading previous program)")
(println (GL20/glGetProgramInfoLog new-pgm-id 10000))
(GL20/glUseProgram pgm-id)
(except-gl-errors "@ try-reload-shader useProgram2"))
(let [_ (println "Reloading shader:" shader-filename)
i-resolution-loc (GL20/glGetUniformLocation new-pgm-id "iResolution")
i-global-time-loc (GL20/glGetUniformLocation new-pgm-id "iGlobalTime")
i-channel-time-loc (GL20/glGetUniformLocation new-pgm-id "iChannelTime")
i-mouse-loc (GL20/glGetUniformLocation new-pgm-id "iMouse")
i-channel0-loc (GL20/glGetUniformLocation new-pgm-id "iChannel0")
i-channel1-loc (GL20/glGetUniformLocation new-pgm-id "iChannel1")
i-channel2-loc (GL20/glGetUniformLocation new-pgm-id "iChannel2")
i-channel3-loc (GL20/glGetUniformLocation new-pgm-id "iChannel3")
i-channel-res-loc (GL20/glGetUniformLocation new-pgm-id "iChannelResolution")
i-date-loc (GL20/glGetUniformLocation new-pgm-id "iDate")]
(GL20/glUseProgram new-pgm-id)
(except-gl-errors "@ try-reload-shader useProgram")
(when user-fn
(user-fn :init new-pgm-id))
;; cleanup the old program
(when (not= pgm-id 0)
(GL20/glDetachShader pgm-id vs-id)
(GL20/glDetachShader pgm-id fs-id)
(GL20/glDeleteShader fs-id))
(except-gl-errors "@ try-reload-shader detach/delete")
(swap! locals
assoc
:shader-good true
:fs-id new-fs-id
:pgm-id new-pgm-id
:i-resolution-loc i-resolution-loc
:i-global-time-loc i-global-time-loc
:i-channel-time-loc i-channel-time-loc
:i-mouse-loc i-mouse-loc
:i-channel-loc [i-channel0-loc i-channel1-loc i-channel2-loc i-channel3-loc]
:i-channel-res-loc i-channel-res-loc
:i-date-loc i-date-loc
:shader-str fs-shader)))))))
(defn- get-pixel-value
[^ByteBuffer rgb-bytes]
(let [rf (/ (float (int (bit-and 0xFF (.get rgb-bytes 0)))) 255.0)
gf (/ (float (int (bit-and 0xFF (.get rgb-bytes 1)))) 255.0)
bf (/ (float (int (bit-and 0xFF (.get rgb-bytes 2)))) 255.0)]
[rf gf bf]))
(defn- draw
[locals]
(let [{:keys [width height i-resolution-loc
start-time last-time i-global-time-loc
i-date-loc
pgm-id vbo-id
vertices-count
i-mouse-loc
mouse-pos-x mouse-pos-y
mouse-ori-x mouse-ori-y
i-channel-time-loc i-channel-loc
i-channel-res-loc
channel-time-buffer channel-res-buffer
old-pgm-id old-fs-id
tex-ids tex-types
user-fn
pixel-read-enable
pixel-read-pos-x pixel-read-pos-y
pixel-read-data]} @locals
cur-time (/ (- last-time start-time) 1000.0)
_ (.put ^FloatBuffer channel-time-buffer 0 (float cur-time))
_ (.put ^FloatBuffer channel-time-buffer 1 (float cur-time))
_ (.put ^FloatBuffer channel-time-buffer 2 (float cur-time))
_ (.put ^FloatBuffer channel-time-buffer 3 (float cur-time))
cur-date (Calendar/getInstance)
cur-year (.get cur-date Calendar/YEAR) ;; four digit year
cur-month (.get cur-date Calendar/MONTH) ;; month 0-11
cur-day (.get cur-date Calendar/DAY_OF_MONTH) ;; day 1-31
cur-seconds (+ (* (.get cur-date Calendar/HOUR_OF_DAY) 60.0 60.0)
(* (.get cur-date Calendar/MINUTE) 60.0)
(.get cur-date Calendar/SECOND))]
(except-gl-errors "@ draw before clear")
(GL11/glClear GL11/GL_COLOR_BUFFER_BIT)
(when user-fn
(user-fn :pre-draw pgm-id))
;; activate textures
(dotimes [i (count tex-ids)]
(when (nth tex-ids i)
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 i))
(cond
(= :cubemap (nth tex-types i))
(GL11/glBindTexture GL13/GL_TEXTURE_CUBE_MAP (nth tex-ids i))
(= :previous-frame (nth tex-types i))
(GL11/glBindTexture GL11/GL_TEXTURE_2D (nth tex-ids i))
:default
(GL11/glBindTexture GL11/GL_TEXTURE_2D (nth tex-ids i)))))
(except-gl-errors "@ draw after activate textures")
;; setup our uniform
(GL20/glUniform3f i-resolution-loc width height 1.0)
(GL20/glUniform1f i-global-time-loc cur-time)
(GL20/glUniform1 ^Integer i-channel-time-loc ^FloatBuffer channel-time-buffer)
(GL20/glUniform4f i-mouse-loc
mouse-pos-x
mouse-pos-y
mouse-ori-x
mouse-ori-y)
(GL20/glUniform1i (nth i-channel-loc 0) 0)
(GL20/glUniform1i (nth i-channel-loc 1) 1)
(GL20/glUniform1i (nth i-channel-loc 2) 2)
(GL20/glUniform1i (nth i-channel-loc 3) 3)
(GL20/glUniform3 ^Integer i-channel-res-loc ^FloatBuffer channel-res-buffer)
(GL20/glUniform4f i-date-loc cur-year cur-month cur-day cur-seconds)
;; get vertex array ready
(GL11/glEnableClientState GL11/GL_VERTEX_ARRAY)
(GL15/glBindBuffer GL15/GL_ARRAY_BUFFER vbo-id)
(GL11/glVertexPointer 4 GL11/GL_FLOAT 0 0)
(except-gl-errors "@ draw prior to DrawArrays")
;; Draw the vertices
(GL11/glDrawArrays GL11/GL_TRIANGLES 0 vertices-count)
(except-gl-errors "@ draw after DrawArrays")
;; Put everything back to default (deselect)
(GL15/glBindBuffer GL15/GL_ARRAY_BUFFER 0)
(GL11/glDisableClientState GL11/GL_VERTEX_ARRAY)
;; unbind textures
(dotimes [i (count tex-ids)]
(when (nth tex-ids i)
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 i))
(GL11/glBindTexture GL13/GL_TEXTURE_CUBE_MAP 0)
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0)))
(except-gl-errors "@ draw prior to post-draw")
(when user-fn
(user-fn :post-draw pgm-id))
(except-gl-errors "@ draw after post-draw")
(GL20/glUseProgram 0)
;; copy the rendered image
(dotimes [i (count tex-ids)]
(when (= :previous-frame (nth tex-types i))
(GL11/glBindTexture GL11/GL_TEXTURE_2D (nth tex-ids i))
(GL11/glCopyTexImage2D GL11/GL_TEXTURE_2D 0 GL11/GL_RGBA8 0 0 width height 0)
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0)))
(except-gl-errors "@ draw after copy")
;; read a pixel value
(when pixel-read-enable
(GL11/glReadPixels ^Integer pixel-read-pos-x ^Integer pixel-read-pos-y
1 1
GL11/GL_RGB GL11/GL_UNSIGNED_BYTE
^ByteBuffer pixel-read-data)
(except-gl-errors "@ draw after pixel read")
(reset! pixel-value (get-pixel-value ^ByteBuffer pixel-read-data)))))
(defn- update-and-draw
[locals]
(let [{:keys [width height last-time pgm-id
mouse-pos-x mouse-pos-y
mouse-clicked mouse-ori-x mouse-ori-y]} @locals
cur-time (System/currentTimeMillis)
cur-mouse-clicked (Mouse/isButtonDown 0)
mouse-down-event (and cur-mouse-clicked (not mouse-clicked))
cur-mouse-pos-x (if cur-mouse-clicked (Mouse/getX) mouse-pos-x)
cur-mouse-pos-y (if cur-mouse-clicked (Mouse/getY) mouse-pos-y)
cur-mouse-ori-x (if mouse-down-event
(Mouse/getX)
(if cur-mouse-clicked
mouse-ori-x
(- (Math/abs ^float mouse-ori-x))))
cur-mouse-ori-y (if mouse-down-event
(Mouse/getY)
(if cur-mouse-clicked
mouse-ori-y
(- (Math/abs ^float mouse-ori-y))))]
(swap! locals
assoc
:last-time cur-time
:mouse-clicked cur-mouse-clicked
:mouse-pos-x cur-mouse-pos-x
:mouse-pos-y cur-mouse-pos-y
:mouse-ori-x cur-mouse-ori-x
:mouse-ori-y cur-mouse-ori-y)
(if (:shader-good @locals)
(do
(if @reload-shader
(try-reload-shader locals) ; this must call glUseProgram
(GL20/glUseProgram pgm-id)) ; else, normal path...
(draw locals))
;; else clear to prevent strobing awfulness
(do
(GL11/glClear GL11/GL_COLOR_BUFFER_BIT)
(except-gl-errors "@ bad-draw glClear ")
(if @reload-shader
(try-reload-shader locals))))))
(defn- destroy-gl
[locals]
(let [{:keys [pgm-id vs-id fs-id vbo-id user-fn]} @locals]
;; Delete any user state
(when user-fn
(user-fn :destroy pgm-id))
;; Delete the shaders
(GL20/glUseProgram 0)
(GL20/glDetachShader pgm-id vs-id)
(GL20/glDetachShader pgm-id fs-id)
(GL20/glDeleteShader vs-id)
(GL20/glDeleteShader fs-id)
(GL20/glDeleteProgram pgm-id)
;; Delete the vertex VBO
(GL15/glBindBuffer GL15/GL_ARRAY_BUFFER 0)
(GL15/glDeleteBuffers ^Integer vbo-id)))
(defn- run-thread
[locals mode shader-filename shader-str-atom tex-filenames title true-fullscreen? user-fn display-sync-hz]
(init-window locals mode title shader-filename shader-str-atom tex-filenames true-fullscreen? user-fn display-sync-hz)
(init-gl locals)
(while (and (= :yes (:active @locals))
(not (Display/isCloseRequested)))
(update-and-draw locals)
(Display/update)
(Display/sync (:display-sync-hz @locals)))
(destroy-gl locals)
(Display/destroy)
(swap! locals assoc :active :no))
(defn- good-tex-count
[textures]
(if (<= (count textures) 4)
true
(do
(println "ERROR: number of textures must be <= 4")
false)))
(defn- expand-filename
"if there is a cubemap filename, expand it 0..5 for the
cubemaps. otherwise leave it alone."
[filename]
(if (cubemap-filename? filename)
(for [i (range 6)] (cubemap-filename filename i))
filename))
(defn- files-exist
"check to see that the filenames actually exist. One tweak is to
allow nil or keyword 'filenames'. Those are important placeholders.
Another tweak is to expand names for cubemap textures."
[filenames]
(let [full-filenames (flatten (map expand-filename filenames))]
(reduce #(and %1 %2) ; kibit keep
(for [fn full-filenames]
(if (or (nil? fn)
(and (keyword? fn) (= fn :previous-frame))
(.exists (File. ^String fn)))
true
(do
(println "ERROR:" fn "does not exist.")
false))))))
(defn- sane-user-inputs
[mode shader-filename shader-str textures title true-fullscreen? user-fn]
(and (good-tex-count textures)
(files-exist (flatten [shader-filename textures]))
(not (and (nil? shader-filename) (nil? shader-str)))))
;; watch the shader-str-atom to reload on a change
(defn- watch-shader-str-atom
[key identity old new]
(when (not= old new)
;; if already reloading, wait for that to finish
(while @reload-shader
;; FIXME this can hang. We should timeout instead
(Thread/sleep 100))
(reset! reload-shader-str new)
(reset! reload-shader true)))
;; watch the shader directory & reload the current shader if it changes.
(defn- if-match-reload-shader
[shader-filename files]
(if @watcher-just-started
;; allow first, automatic call to pass unnoticed
(reset! watcher-just-started false)
;; otherwise do the reload check
(doseq [f files]
(when (= (.getPath ^File f) shader-filename)
;; set a flag that the opengl thread will use
(reset! reload-shader true)))))
(defn- start-watcher
"create a watch for glsl shaders in the directory and return the global
future atom for that watcher"
[shader-filename]
(let [dir (.getParent (File. ^String shader-filename))]
(reset! watcher-just-started true)
(watcher/watcher
[dir]
(watcher/rate 100)
(watcher/file-filter watcher/ignore-dotfiles)
(watcher/file-filter (watcher/extensions :glsl))
(watcher/on-change (partial if-match-reload-shader shader-filename)))))
(defn- stop-watcher
"given a watcher-future f, put a stop to it"
[f]
(when-not (or (future-done? f) (future-cancelled? f))
(if (not (future-cancel f))
(println "ERROR: unable to stop-watcher!"))))
;; ======================================================================
;; allow shader to have user-data, just like tone.
;; I'd like to make this better follow DRY, but this seems okay for now
(defonce shader-user-data (atom {}))
(defonce shader-user-locs (atom {}))
(defn- shader-default-fn
[dispatch pgm-id]
(case dispatch ;; FIXME defmulti?
:init ;; find Uniform Location
(doseq [key (keys @shader-user-data)]
(let [loc (GL20/glGetUniformLocation ^Integer pgm-id ^String key)]
(swap! shader-user-locs assoc key loc)))
:pre-draw
(doseq [key (keys @shader-user-data)]
(let [loc (@shader-user-locs key)
val (deref (@shader-user-data key))]
;;(println key loc val)
(if (float? val)
(GL20/glUniform1f loc val)
(when (vector? val)
(case (count val)
1 (GL20/glUniform1f loc (nth val 0))
2 (GL20/glUniform2f loc (nth val 0) (nth val 1))
3 (GL20/glUniform3f loc (nth val 0) (nth val 1) (nth val 2))
4 (GL20/glUniform4f loc (nth val 0) (nth val 1) (nth val 2) (nth val 3)))))))
:post-draw
nil ;; nothing to do
:destroy
nil ;; nothing to do
))
;; Public API ===================================================
(defn display-modes
"Returns a seq of display modes sorted by resolution size with highest
resolution first and lowest last."
[]
(sort (fn [^DisplayMode a ^DisplayMode b]
(let [res-a (* (.getWidth a)
(.getHeight a))
res-b (* (.getWidth b)
(.getHeight b))
bit-depth-a (.getBitsPerPixel a)
bit-depth-b (.getBitsPerPixel b) ]
(if (= res-a res-b)
(> bit-depth-a bit-depth-b)
(> res-a res-b))))
(Display/getAvailableDisplayModes)))
(defn fullscreen-display-modes
"Returns a seq of fullscreen compatible display modes sorted by
resolution size with highest resolution first and lowest last."
[]
(filter #(.isFullscreenCapable ^DisplayMode %) (display-modes)))
(defn undecorate-display!
"All future display windows will be undecorated (i.e. no title bar)"
[]
(System/setProperty "org.lwjgl.opengl.Window.undecorated" "true"))
(defn decorate-display!
"All future display windows will be decorated (i.e. have a title bar)"
[]
(System/setProperty "org.lwjgl.opengl.Window.undecorated" "false"))
(defn active?
"Returns true if the shader display is currently running"
[]
(= :yes (:active @the-window-state)))
(defn inactive?
"Returns true if the shader display is completely done running."
[]
(= :no (:active @the-window-state)))
(defn stop
"Stop and destroy the shader display. Blocks until completed."
[]
(when (active?)
(swap! the-window-state assoc :active :stopping)
(while (not (inactive?))
(Thread/sleep 100)))
(remove-watch (:shader-str-atom @the-window-state) :shader-str-watch)
(stop-watcher @watcher-future))
(defn start-shader-display
"Start a new shader display with the specified mode. Prefer start or
start-fullscreen for simpler usage."
[mode shader-filename-or-str-atom textures title true-fullscreen?
user-data user-fn display-sync-hz]
(let [is-filename (not (instance? clojure.lang.Atom shader-filename-or-str-atom))
shader-filename (if is-filename
shader-filename-or-str-atom)
;; Fix for issue 15. Normalize the given shader-filename to the
;; path separators that the system will use. If user gives path/to/shader.glsl
;; and windows returns this as path\to\shader.glsl from .getPath, this
;; change should make comparison to path\to\shader.glsl work.
shader-filename (if (and is-filename (not (nil? shader-filename)))
(.getPath (File. ^String shader-filename)))
shader-str-atom (if-not is-filename
shader-filename-or-str-atom
(atom nil))
shader-str (if-not is-filename
@shader-str-atom)]
(when (sane-user-inputs mode shader-filename shader-str textures title true-fullscreen? user-fn)
;; stop the current shader
(stop)
;; start the watchers
(if is-filename
(when-not (nil? shader-filename)
(swap! watcher-future
(fn [x] (start-watcher shader-filename))))
(add-watch shader-str-atom :shader-str-watch watch-shader-str-atom))
;; set a global window-state instead of creating a new one
(reset! the-window-state default-state-values)
;; set user data
(reset! shader-user-data user-data)
;; start the requested shader
(.start (Thread.
(fn [] (run-thread the-window-state
mode
shader-filename
shader-str-atom
textures
title
true-fullscreen?
user-fn
display-sync-hz)))))))
(defn start
"Start a new shader display. Forces the display window to be
decorated (i.e. have a title bar)."
[shader-filename-or-str-atom
&{:keys [width height title display-sync-hz
textures user-data user-fn]
:or {width 600
height 600
title "shadertone"
display-sync-hz 60
textures []
user-data {}
user-fn shader-default-fn}}]
(let [mode (DisplayMode. width height)]
(decorate-display!)
(start-shader-display mode shader-filename-or-str-atom textures title false user-data user-fn display-sync-hz)))
(defn start-fullscreen
"Start a new shader display in pseudo fullscreen mode. This creates
a new borderless window which is the size of the current
resolution. There are therefore no OS controls for closing the
shader window. Use (stop) to close things manually."
[shader-filename-or-str-atom
&{:keys [display-sync-hz textures user-data user-fn]
:or {display-sync-hz 60
textures [nil]
user-data {}
user-fn shader-default-fn}}]
(let [mode (Display/getDisplayMode)]
(undecorate-display!)
(start-shader-display mode shader-filename-or-str-atom textures "" false user-data user-fn display-sync-hz)))
(defn throw-exceptions-on-gl-errors!
"When v is true, throw exceptions when glGetError() returns
non-zero. This is the default setting. When v is false, do not
throw the exception. Perhaps setting to false during a performance
will allow you to avoid over-agressive exceptions. Leave this true
otherwise." [v]
(reset! throw-on-gl-error v))
(defn pixel-read-enable!
"Enable reading a pixel each frame from location x,y. Be sure x,y
are valid or things may crash! Results are available via the
function (pixel) and via the atom @pixel-value"
[x y]
(swap! the-window-state assoc
:pixel-read-enable true
:pixel-read-pos-x x
:pixel-read-pos-y y)
nil)
(defn pixel-read-disable!
"Disable reading pixel values each frame."
[]
(swap! the-window-state assoc
:pixel-read-enable false)
nil)
(defn pixel
"Return the data that was read from the currently drawn frame at the
x,y location specified in the (pixel-read-enable! x y) call. When
enabled, a [red green blue] vector of floating point [0.0,1.0]
values is returned. Otherwise, [0.0 0.0 0.0] is returned."
[]
(if (:pixel-read-enable @the-window-state)
(get-pixel-value (:pixel-read-data @the-window-state))
[0.0 0.0 0.0]))
| 99203 | (ns #^{:author "<NAME>"
:doc "Shadertoy-like core library."}
shadertone.shader
(:require [watchtower.core :as watcher]
clojure.string)
(:import (java.awt.image BufferedImage DataBuffer DataBufferByte WritableRaster)
(java.io File FileInputStream)
(java.nio IntBuffer ByteBuffer FloatBuffer ByteOrder)
(java.util Calendar)
(javax.imageio ImageIO)
(java.lang.reflect Field)
(org.lwjgl BufferUtils)
(org.lwjgl.input Mouse)
(org.lwjgl.opengl ContextAttribs Display DisplayMode
GL11 GL12 GL13 GL15 GL20
PixelFormat)))
;; ======================================================================
;; State Variables
;; a map of state variables for use in the gl thread
(defonce default-state-values
{:active :no ;; :yes/:stopping/:no
:width 0
:height 0
:title ""
:display-sync-hz 60
:start-time 0
:last-time 0
;; mouse
:mouse-clicked false
:mouse-pos-x 0
:mouse-pos-y 0
:mouse-ori-x 0
:mouse-ori-y 0
;; geom ids
:vbo-id 0
:vertices-count 0
;; shader program
:shader-good true ;; false in error condition
:shader-filename nil
:shader-str-atom (atom nil)
:shader-str ""
:vs-id 0
:fs-id 0
:pgm-id 0
;; shader uniforms
:i-resolution-loc 0
:i-global-time-loc 0
:i-channel-time-loc 0
:i-mouse-loc 0
:i-channel-loc [0 0 0 0]
:i-channel-res-loc 0
:i-date-loc 0
:channel-time-buffer (-> (BufferUtils/createFloatBuffer 4)
(.put (float-array
[0.0 0.0 0.0 0.0]))
(.flip))
:channel-res-buffer (-> (BufferUtils/createFloatBuffer (* 3 4))
(.put (float-array
[0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0]))
(.flip))
;; textures
:tex-filenames []
:tex-ids []
:tex-types [] ; :cubemap, :previous-frame
;; a user draw function
:user-fn nil
;; pixel read
:pixel-read-enable false
:pixel-read-pos-x 0
:pixel-read-pos-y 0
:pixel-read-data (-> (BufferUtils/createByteBuffer 3)
(.put (byte-array (map byte [0 0 0])))
(.flip))
})
;; GLOBAL STATE ATOMS
;; Tried to get rid of this atom, but LWJGL is limited to only
;; one window. So, we just keep a single atom containing the
;; current window state here.
(defonce the-window-state (atom default-state-values))
;; The reload-shader atom communicates across the gl & watcher threads
(defonce reload-shader (atom false))
(defonce reload-shader-str (atom ""))
;; Atom for the directory watcher future
(defonce watcher-future (atom (future (fn [] nil))))
;; Flag to help avoid reloading shader right after loading it for the
;; first time.
(defonce watcher-just-started (atom true))
(defonce throw-on-gl-error (atom true))
;;
(defonce pixel-value (atom [0.0 0.0 0.0]))
;; ======================================================================
;; code modified from
;; https://github.com/ztellman/penumbra/blob/master/src/penumbra/opengl/core.clj
(defn- get-fields [#^Class static-class]
(. static-class getFields))
(defn- gl-enum-name
"Takes the numeric value of a gl constant (i.e. GL_LINEAR), and gives the name"
[enum-value]
(if (= 0 enum-value)
"NONE"
(.getName #^Field (some
#(if (= enum-value (.get #^Field % nil)) % nil)
(mapcat get-fields [GL11 GL12 GL13 GL15 GL20])))))
(defn- except-gl-errors
[msg]
(let [error (GL11/glGetError)
error-string (str "OpenGL Error(" error "):"
(gl-enum-name error) ": " msg)]
(if (and (not (zero? error)) @throw-on-gl-error)
(throw (Exception. error-string)))))
;; ======================================================================
(defn- fill-tex-filenames
"return a vector of 4 items, always. Use nil if no filename"
[tex-filenames]
(apply vector
(for [i (range 4)]
(if (< i (count tex-filenames))
(nth tex-filenames i)))))
(defn- uniform-sampler-type-str
[tex-types n]
(format "uniform sampler%s iChannel%s;\n"
(if (= :cubemap (nth tex-types 0)) "Cube" "2D")
n))
(defn- slurp-fs
"do whatever it takes to modify shadertoy fragment shader source to
be useable"
[locals filename]
(let [{:keys [tex-types]} @locals
;;file-str (slurp filename)
file-str (str "#version 120\n"
"uniform vec3 iResolution;\n"
"uniform float iGlobalTime;\n"
"uniform float iChannelTime[4];\n"
"uniform vec3 iChannelResolution[4];\n"
"uniform vec4 iMouse;\n"
(uniform-sampler-type-str tex-types 0)
(uniform-sampler-type-str tex-types 1)
(uniform-sampler-type-str tex-types 2)
(uniform-sampler-type-str tex-types 3)
"uniform vec4 iDate;\n"
"\n"
(slurp filename))]
file-str))
(defn- cubemap-filename?
"if a filename contains a '*' char, it is a cubemap"
[filename]
(if (string? filename)
(not (nil? (re-find #"\*" filename)))
false))
(defn- get-texture-type
[tex-filename]
(cond
(cubemap-filename? tex-filename) :cubemap
(= :previous-frame tex-filename) :previous-frame
:default :twod))
(defn- init-window
"Initialise a shader-powered window with the specified
display-mode. If true-fullscreen? is true, fullscreen mode is
attempted if the display-mode is compatible. See display-modes for a
list of available modes and fullscreen-display-modes for a list of
fullscreen compatible modes.."
[locals display-mode title shader-filename shader-str-atom tex-filenames true-fullscreen? user-fn display-sync-hz]
(let [width (.getWidth ^DisplayMode display-mode)
height (.getHeight ^DisplayMode display-mode)
pixel-format (PixelFormat.)
context-attributes (-> (ContextAttribs. 2 1)) ;; GL2.1
current-time-millis (System/currentTimeMillis)
tex-filenames (fill-tex-filenames tex-filenames)
tex-types (map get-texture-type tex-filenames)]
(swap! locals
assoc
:active :yes
:width width
:height height
:title title
:display-sync-hz display-sync-hz
:start-time current-time-millis
:last-time current-time-millis
:shader-filename shader-filename
:shader-str-atom shader-str-atom
:tex-filenames tex-filenames
:tex-types tex-types
:user-fn user-fn)
;; slurp-fs requires :tex-types, so we need a 2 pass setup
(let [shader-str (if (nil? shader-filename)
@shader-str-atom
(slurp-fs locals (:shader-filename @locals)))]
(swap! locals assoc :shader-str shader-str)
(Display/setDisplayMode display-mode)
(when true-fullscreen?
(Display/setFullscreen true))
(Display/setTitle title)
(Display/setVSyncEnabled true)
(Display/setLocation 0 0)
(Display/create pixel-format context-attributes))))
(defn- init-buffers
[locals]
(let [vertices (float-array
[-1.0 -1.0 0.0 1.0
1.0 -1.0 0.0 1.0
-1.0 1.0 0.0 1.0
-1.0 1.0 0.0 1.0
1.0 -1.0 0.0 1.0
1.0 1.0 0.0 1.0])
vertices-buffer (-> (BufferUtils/createFloatBuffer (count vertices))
(.put vertices)
(.flip))
vertices-count (count vertices)
vbo-id (GL15/glGenBuffers)
_ (GL15/glBindBuffer GL15/GL_ARRAY_BUFFER vbo-id)
_ (GL15/glBufferData GL15/GL_ARRAY_BUFFER
^FloatBuffer vertices-buffer
GL15/GL_STATIC_DRAW)
_ (except-gl-errors "@ end of init-buffers")]
(swap! locals
assoc
:vbo-id vbo-id
:vertices-count vertices-count)))
(def vs-shader
(str "#version 120\n"
"void main(void) {\n"
" gl_Position = gl_Vertex;\n"
"}\n"))
(defn- load-shader
[^String shader-str ^Integer shader-type]
(let [shader-id (GL20/glCreateShader shader-type)
_ (except-gl-errors "@ load-shader glCreateShader ")
_ (GL20/glShaderSource shader-id shader-str)
_ (except-gl-errors "@ load-shader glShaderSource ")
_ (GL20/glCompileShader shader-id)
_ (except-gl-errors "@ load-shader glCompileShader ")
gl-compile-status (GL20/glGetShaderi shader-id GL20/GL_COMPILE_STATUS)
_ (except-gl-errors "@ end of let load-shader")]
(when (== gl-compile-status GL11/GL_FALSE)
(println "ERROR: Loading a Shader:")
(println (GL20/glGetShaderInfoLog shader-id 10000)))
[gl-compile-status shader-id]))
(defn- init-shaders
[locals]
(let [[ok? vs-id] (load-shader vs-shader GL20/GL_VERTEX_SHADER)
_ (assert (== ok? GL11/GL_TRUE)) ;; something is really wrong if our vs is bad
_ (if (nil? (:shader-filename @locals))
(println "Loading shader from string")
(println "Loading shader from file:" (:shader-filename @locals)))
[ok? fs-id] (load-shader (:shader-str @locals) GL20/GL_FRAGMENT_SHADER)]
(if (== ok? GL11/GL_TRUE)
(let [pgm-id (GL20/glCreateProgram)
_ (except-gl-errors "@ let init-shaders glCreateProgram")
_ (GL20/glAttachShader pgm-id vs-id)
_ (except-gl-errors "@ let init-shaders glAttachShader VS")
_ (GL20/glAttachShader pgm-id fs-id)
_ (except-gl-errors "@ let init-shaders glAttachShader FS")
_ (GL20/glLinkProgram pgm-id)
_ (except-gl-errors "@ let init-shaders glLinkProgram")
gl-link-status (GL20/glGetProgrami pgm-id GL20/GL_LINK_STATUS)
_ (except-gl-errors "@ let init-shaders glGetProgram link status")
_ (when (== gl-link-status GL11/GL_FALSE)
(println "ERROR: Linking Shaders:")
(println (GL20/glGetProgramInfoLog pgm-id 10000)))
_ (except-gl-errors "@ let before GetUniformLocation")
i-resolution-loc (GL20/glGetUniformLocation pgm-id "iResolution")
i-global-time-loc (GL20/glGetUniformLocation pgm-id "iGlobalTime")
i-channel-time-loc (GL20/glGetUniformLocation pgm-id "iChannelTime")
i-mouse-loc (GL20/glGetUniformLocation pgm-id "iMouse")
i-channel0-loc (GL20/glGetUniformLocation pgm-id "iChannel0")
i-channel1-loc (GL20/glGetUniformLocation pgm-id "iChannel1")
i-channel2-loc (GL20/glGetUniformLocation pgm-id "iChannel2")
i-channel3-loc (GL20/glGetUniformLocation pgm-id "iChannel3")
i-channel-res-loc (GL20/glGetUniformLocation pgm-id "iChannelResolution")
i-date-loc (GL20/glGetUniformLocation pgm-id "iDate")
_ (except-gl-errors "@ end of let init-shaders")
]
(swap! locals
assoc
:shader-good true
:vs-id vs-id
:fs-id fs-id
:pgm-id pgm-id
:i-resolution-loc i-resolution-loc
:i-global-time-loc i-global-time-loc
:i-channel-time-loc i-channel-time-loc
:i-mouse-loc i-mouse-loc
:i-channel-loc [i-channel0-loc i-channel1-loc i-channel2-loc i-channel3-loc]
:i-channel-res-loc i-channel-res-loc
:i-date-loc i-date-loc))
;; we didn't load the shader, don't be drawing
(swap! locals assoc :shader-good false))))
(defn- buffer-swizzle-0123-1230
"given a ARGB pixel array, swizzle it to be RGBA. Or, ABGR to BGRA"
^bytes [^bytes data] ;; Wow! That ^bytes changes this from 10s for a 256x256 tex to instantaneous.
(dotimes [i (/ (alength data) 4)]
(let [i0 (* i 4)
i1 (inc i0)
i2 (inc i1)
i3 (inc i2)
tmp (aget data i0)]
(aset data i0 (aget data i1))
(aset data i1 (aget data i2))
(aset data i2 (aget data i3))
(aset data i3 tmp)))
data)
(defn- cubemap-filename
[filename i]
(clojure.string/replace filename "*" (str i)))
(defn- put-texture-data
"put the data from the image into the buffer and return the buffer"
^ByteBuffer
[^ByteBuffer buffer ^BufferedImage image ^Boolean swizzle-0123-1230]
(let [data ^bytes (-> ^WritableRaster (.getRaster image)
^DataBufferByte (.getDataBuffer)
(.getData))
data (if swizzle-0123-1230
(buffer-swizzle-0123-1230 data)
data)
buffer (.put buffer data 0 (alength data))] ; (.order (ByteOrder/nativeOrder)) ?
buffer))
(defn- tex-image-bytes
"return the number of bytes per pixel in this image"
[^BufferedImage image]
(let [image-type (.getType image)
image-bytes (if (or (= image-type BufferedImage/TYPE_3BYTE_BGR)
(= image-type BufferedImage/TYPE_INT_RGB))
3
(if (or (= image-type BufferedImage/TYPE_4BYTE_ABGR)
(= image-type BufferedImage/TYPE_INT_ARGB))
4
0)) ;; unhandled image type--what to do?
;; _ (println "image-type"
;; (cond
;; (= image-type BufferedImage/TYPE_3BYTE_BGR) "TYPE_3BYTE_BGR"
;; (= image-type BufferedImage/TYPE_INT_RGB) "TYPE_INT_RGB"
;; (= image-type BufferedImage/TYPE_4BYTE_ABGR) "TYPE_4BYTE_ABGR"
;; (= image-type BufferedImage/TYPE_INT_ARGB) "TYPE_INT_ARGB"
;; :else image-type))
_ (assert (pos? image-bytes))] ;; die on unhandled image
image-bytes))
(defn- tex-internal-format
"return the internal-format for the glTexImage2D call for this image"
^Integer
[^BufferedImage image]
(let [image-type (.getType image)
internal-format (cond
(= image-type BufferedImage/TYPE_3BYTE_BGR) GL11/GL_RGB8
(= image-type BufferedImage/TYPE_INT_RGB) GL11/GL_RGB8
(= image-type BufferedImage/TYPE_4BYTE_ABGR) GL11/GL_RGBA8
(= image-type BufferedImage/TYPE_INT_ARGB) GL11/GL_RGBA8)]
internal-format))
(defn- tex-format
"return the format for the glTexImage2D call for this image"
^Integer
[^BufferedImage image]
(let [image-type (.getType image)
format (cond
(= image-type BufferedImage/TYPE_3BYTE_BGR) GL12/GL_BGR
(= image-type BufferedImage/TYPE_INT_RGB) GL11/GL_RGB
(= image-type BufferedImage/TYPE_4BYTE_ABGR) GL12/GL_BGRA
(= image-type BufferedImage/TYPE_INT_ARGB) GL11/GL_RGBA)]
format))
(defn- load-texture
"load, bind texture from filename. returns a texture info vector
[tex-id width height z]. returns nil tex-id if filename is nil"
([^String filename]
(let [tex-id (GL11/glGenTextures)]
(if (cubemap-filename? filename)
(do
(dotimes [i 6]
(load-texture (cubemap-filename filename i)
GL13/GL_TEXTURE_CUBE_MAP tex-id i))
[tex-id 0.0 0.0 0.0]) ;; cubemaps don't update w/h
(load-texture filename GL11/GL_TEXTURE_2D tex-id 0))))
([^String filename ^Integer target ^Integer tex-id ^Integer i]
(if (string? filename)
;; load from file
(let [_ (println "Loading texture:" filename)
image (ImageIO/read (FileInputStream. filename))
image-bytes (tex-image-bytes image)
internal-format (tex-internal-format image)
format (tex-format image)
nbytes (* image-bytes (.getWidth image) (.getHeight image))
buffer ^ByteBuffer (-> (BufferUtils/createByteBuffer nbytes)
(put-texture-data image (= image-bytes 4))
(.flip))
tex-image-target ^Integer (if (= target GL13/GL_TEXTURE_CUBE_MAP)
(+ i GL13/GL_TEXTURE_CUBE_MAP_POSITIVE_X)
target)]
(GL11/glBindTexture target tex-id)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MAG_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MIN_FILTER GL11/GL_LINEAR)
(if (== target GL11/GL_TEXTURE_2D)
(do
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_S GL11/GL_REPEAT)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_T GL11/GL_REPEAT))
(do ;; CUBE_MAP
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)))
(GL11/glTexImage2D ^Integer tex-image-target 0 ^Integer internal-format
^Integer (.getWidth image) ^Integer (.getHeight image) 0
^Integer format
GL11/GL_UNSIGNED_BYTE
^ByteBuffer buffer)
(except-gl-errors "@ end of load-texture if-stmt")
[tex-id (.getWidth image) (.getHeight image) 1.0])
(if (= filename :previous-frame)
(do ;; :previous-frame initial setup
(println "setting up :previous-frame texture")
(GL11/glBindTexture target tex-id)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MAG_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MIN_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)
(except-gl-errors "@ end of load-texture else-stmt")
;; use negative as flag to indicate using window width, height
[tex-id -1.0 -1.0 1.0])
;; else must be nil texture
[nil 0.0 0.0 0.0]))))
(defn- init-textures
[locals]
(let [tex-infos (map load-texture (:tex-filenames @locals))
;;_ (println "raw" tex-infos)
tex-ids (map first tex-infos)
tex-whd (map rest tex-infos)
tex-whd (flatten
(map #(if (< (first %) 0.0)
[(:width @locals) (:height @locals) 1.0]
%)
tex-whd))
;; update channel-res-buffer
_ (-> ^FloatBuffer (:channel-res-buffer @locals)
(.put ^floats (float-array tex-whd))
(.flip))
]
(swap! locals assoc
:tex-ids tex-ids)))
(defn- init-gl
[locals]
(let [{:keys [width height user-fn]} @locals]
;;(println "OpenGL version:" (GL11/glGetString GL11/GL_VERSION))
(GL11/glClearColor 0.0 0.0 0.0 0.0)
(GL11/glViewport 0 0 width height)
(init-buffers locals)
(init-textures locals)
(init-shaders locals)
(when (and (not (nil? user-fn)) (:shader-good @locals))
(user-fn :init (:pgm-id @locals)))))
(defn- try-reload-shader
[locals]
(let [{:keys [vs-id fs-id pgm-id shader-filename user-fn]} @locals
vs-id (if (= vs-id 0)
(let [[ok? vs-id] (load-shader vs-shader GL20/GL_VERTEX_SHADER)
_ (assert (== ok? GL11/GL_TRUE))]
vs-id)
vs-id)
fs-shader (if (nil? shader-filename)
@reload-shader-str
(slurp-fs locals shader-filename))
[ok? new-fs-id] (load-shader fs-shader GL20/GL_FRAGMENT_SHADER)
_ (reset! reload-shader false)]
(if (== ok? GL11/GL_FALSE)
;; we didn't reload a good shader. Go back to the old one if possible
(when (:shader-good @locals)
(GL20/glUseProgram pgm-id)
(except-gl-errors "@ try-reload-shader useProgram1"))
;; the load shader went well, keep going...
(let [new-pgm-id (GL20/glCreateProgram)
_ (except-gl-errors "@ try-reload-shader glCreateProgram")
_ (GL20/glAttachShader new-pgm-id vs-id)
_ (except-gl-errors "@ try-reload-shader glAttachShader VS")
_ (GL20/glAttachShader new-pgm-id new-fs-id)
_ (except-gl-errors "@ try-reload-shader glAttachShader FS")
_ (GL20/glLinkProgram new-pgm-id)
_ (except-gl-errors "@ try-reload-shader glLinkProgram")
gl-link-status (GL20/glGetProgrami new-pgm-id GL20/GL_LINK_STATUS)
_ (except-gl-errors "@ end of let try-reload-shader")]
(if (== gl-link-status GL11/GL_FALSE)
(do
(println "ERROR: Linking Shaders: (reloading previous program)")
(println (GL20/glGetProgramInfoLog new-pgm-id 10000))
(GL20/glUseProgram pgm-id)
(except-gl-errors "@ try-reload-shader useProgram2"))
(let [_ (println "Reloading shader:" shader-filename)
i-resolution-loc (GL20/glGetUniformLocation new-pgm-id "iResolution")
i-global-time-loc (GL20/glGetUniformLocation new-pgm-id "iGlobalTime")
i-channel-time-loc (GL20/glGetUniformLocation new-pgm-id "iChannelTime")
i-mouse-loc (GL20/glGetUniformLocation new-pgm-id "iMouse")
i-channel0-loc (GL20/glGetUniformLocation new-pgm-id "iChannel0")
i-channel1-loc (GL20/glGetUniformLocation new-pgm-id "iChannel1")
i-channel2-loc (GL20/glGetUniformLocation new-pgm-id "iChannel2")
i-channel3-loc (GL20/glGetUniformLocation new-pgm-id "iChannel3")
i-channel-res-loc (GL20/glGetUniformLocation new-pgm-id "iChannelResolution")
i-date-loc (GL20/glGetUniformLocation new-pgm-id "iDate")]
(GL20/glUseProgram new-pgm-id)
(except-gl-errors "@ try-reload-shader useProgram")
(when user-fn
(user-fn :init new-pgm-id))
;; cleanup the old program
(when (not= pgm-id 0)
(GL20/glDetachShader pgm-id vs-id)
(GL20/glDetachShader pgm-id fs-id)
(GL20/glDeleteShader fs-id))
(except-gl-errors "@ try-reload-shader detach/delete")
(swap! locals
assoc
:shader-good true
:fs-id new-fs-id
:pgm-id new-pgm-id
:i-resolution-loc i-resolution-loc
:i-global-time-loc i-global-time-loc
:i-channel-time-loc i-channel-time-loc
:i-mouse-loc i-mouse-loc
:i-channel-loc [i-channel0-loc i-channel1-loc i-channel2-loc i-channel3-loc]
:i-channel-res-loc i-channel-res-loc
:i-date-loc i-date-loc
:shader-str fs-shader)))))))
(defn- get-pixel-value
[^ByteBuffer rgb-bytes]
(let [rf (/ (float (int (bit-and 0xFF (.get rgb-bytes 0)))) 255.0)
gf (/ (float (int (bit-and 0xFF (.get rgb-bytes 1)))) 255.0)
bf (/ (float (int (bit-and 0xFF (.get rgb-bytes 2)))) 255.0)]
[rf gf bf]))
(defn- draw
[locals]
(let [{:keys [width height i-resolution-loc
start-time last-time i-global-time-loc
i-date-loc
pgm-id vbo-id
vertices-count
i-mouse-loc
mouse-pos-x mouse-pos-y
mouse-ori-x mouse-ori-y
i-channel-time-loc i-channel-loc
i-channel-res-loc
channel-time-buffer channel-res-buffer
old-pgm-id old-fs-id
tex-ids tex-types
user-fn
pixel-read-enable
pixel-read-pos-x pixel-read-pos-y
pixel-read-data]} @locals
cur-time (/ (- last-time start-time) 1000.0)
_ (.put ^FloatBuffer channel-time-buffer 0 (float cur-time))
_ (.put ^FloatBuffer channel-time-buffer 1 (float cur-time))
_ (.put ^FloatBuffer channel-time-buffer 2 (float cur-time))
_ (.put ^FloatBuffer channel-time-buffer 3 (float cur-time))
cur-date (Calendar/getInstance)
cur-year (.get cur-date Calendar/YEAR) ;; four digit year
cur-month (.get cur-date Calendar/MONTH) ;; month 0-11
cur-day (.get cur-date Calendar/DAY_OF_MONTH) ;; day 1-31
cur-seconds (+ (* (.get cur-date Calendar/HOUR_OF_DAY) 60.0 60.0)
(* (.get cur-date Calendar/MINUTE) 60.0)
(.get cur-date Calendar/SECOND))]
(except-gl-errors "@ draw before clear")
(GL11/glClear GL11/GL_COLOR_BUFFER_BIT)
(when user-fn
(user-fn :pre-draw pgm-id))
;; activate textures
(dotimes [i (count tex-ids)]
(when (nth tex-ids i)
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 i))
(cond
(= :cubemap (nth tex-types i))
(GL11/glBindTexture GL13/GL_TEXTURE_CUBE_MAP (nth tex-ids i))
(= :previous-frame (nth tex-types i))
(GL11/glBindTexture GL11/GL_TEXTURE_2D (nth tex-ids i))
:default
(GL11/glBindTexture GL11/GL_TEXTURE_2D (nth tex-ids i)))))
(except-gl-errors "@ draw after activate textures")
;; setup our uniform
(GL20/glUniform3f i-resolution-loc width height 1.0)
(GL20/glUniform1f i-global-time-loc cur-time)
(GL20/glUniform1 ^Integer i-channel-time-loc ^FloatBuffer channel-time-buffer)
(GL20/glUniform4f i-mouse-loc
mouse-pos-x
mouse-pos-y
mouse-ori-x
mouse-ori-y)
(GL20/glUniform1i (nth i-channel-loc 0) 0)
(GL20/glUniform1i (nth i-channel-loc 1) 1)
(GL20/glUniform1i (nth i-channel-loc 2) 2)
(GL20/glUniform1i (nth i-channel-loc 3) 3)
(GL20/glUniform3 ^Integer i-channel-res-loc ^FloatBuffer channel-res-buffer)
(GL20/glUniform4f i-date-loc cur-year cur-month cur-day cur-seconds)
;; get vertex array ready
(GL11/glEnableClientState GL11/GL_VERTEX_ARRAY)
(GL15/glBindBuffer GL15/GL_ARRAY_BUFFER vbo-id)
(GL11/glVertexPointer 4 GL11/GL_FLOAT 0 0)
(except-gl-errors "@ draw prior to DrawArrays")
;; Draw the vertices
(GL11/glDrawArrays GL11/GL_TRIANGLES 0 vertices-count)
(except-gl-errors "@ draw after DrawArrays")
;; Put everything back to default (deselect)
(GL15/glBindBuffer GL15/GL_ARRAY_BUFFER 0)
(GL11/glDisableClientState GL11/GL_VERTEX_ARRAY)
;; unbind textures
(dotimes [i (count tex-ids)]
(when (nth tex-ids i)
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 i))
(GL11/glBindTexture GL13/GL_TEXTURE_CUBE_MAP 0)
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0)))
(except-gl-errors "@ draw prior to post-draw")
(when user-fn
(user-fn :post-draw pgm-id))
(except-gl-errors "@ draw after post-draw")
(GL20/glUseProgram 0)
;; copy the rendered image
(dotimes [i (count tex-ids)]
(when (= :previous-frame (nth tex-types i))
(GL11/glBindTexture GL11/GL_TEXTURE_2D (nth tex-ids i))
(GL11/glCopyTexImage2D GL11/GL_TEXTURE_2D 0 GL11/GL_RGBA8 0 0 width height 0)
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0)))
(except-gl-errors "@ draw after copy")
;; read a pixel value
(when pixel-read-enable
(GL11/glReadPixels ^Integer pixel-read-pos-x ^Integer pixel-read-pos-y
1 1
GL11/GL_RGB GL11/GL_UNSIGNED_BYTE
^ByteBuffer pixel-read-data)
(except-gl-errors "@ draw after pixel read")
(reset! pixel-value (get-pixel-value ^ByteBuffer pixel-read-data)))))
(defn- update-and-draw
[locals]
(let [{:keys [width height last-time pgm-id
mouse-pos-x mouse-pos-y
mouse-clicked mouse-ori-x mouse-ori-y]} @locals
cur-time (System/currentTimeMillis)
cur-mouse-clicked (Mouse/isButtonDown 0)
mouse-down-event (and cur-mouse-clicked (not mouse-clicked))
cur-mouse-pos-x (if cur-mouse-clicked (Mouse/getX) mouse-pos-x)
cur-mouse-pos-y (if cur-mouse-clicked (Mouse/getY) mouse-pos-y)
cur-mouse-ori-x (if mouse-down-event
(Mouse/getX)
(if cur-mouse-clicked
mouse-ori-x
(- (Math/abs ^float mouse-ori-x))))
cur-mouse-ori-y (if mouse-down-event
(Mouse/getY)
(if cur-mouse-clicked
mouse-ori-y
(- (Math/abs ^float mouse-ori-y))))]
(swap! locals
assoc
:last-time cur-time
:mouse-clicked cur-mouse-clicked
:mouse-pos-x cur-mouse-pos-x
:mouse-pos-y cur-mouse-pos-y
:mouse-ori-x cur-mouse-ori-x
:mouse-ori-y cur-mouse-ori-y)
(if (:shader-good @locals)
(do
(if @reload-shader
(try-reload-shader locals) ; this must call glUseProgram
(GL20/glUseProgram pgm-id)) ; else, normal path...
(draw locals))
;; else clear to prevent strobing awfulness
(do
(GL11/glClear GL11/GL_COLOR_BUFFER_BIT)
(except-gl-errors "@ bad-draw glClear ")
(if @reload-shader
(try-reload-shader locals))))))
(defn- destroy-gl
[locals]
(let [{:keys [pgm-id vs-id fs-id vbo-id user-fn]} @locals]
;; Delete any user state
(when user-fn
(user-fn :destroy pgm-id))
;; Delete the shaders
(GL20/glUseProgram 0)
(GL20/glDetachShader pgm-id vs-id)
(GL20/glDetachShader pgm-id fs-id)
(GL20/glDeleteShader vs-id)
(GL20/glDeleteShader fs-id)
(GL20/glDeleteProgram pgm-id)
;; Delete the vertex VBO
(GL15/glBindBuffer GL15/GL_ARRAY_BUFFER 0)
(GL15/glDeleteBuffers ^Integer vbo-id)))
(defn- run-thread
[locals mode shader-filename shader-str-atom tex-filenames title true-fullscreen? user-fn display-sync-hz]
(init-window locals mode title shader-filename shader-str-atom tex-filenames true-fullscreen? user-fn display-sync-hz)
(init-gl locals)
(while (and (= :yes (:active @locals))
(not (Display/isCloseRequested)))
(update-and-draw locals)
(Display/update)
(Display/sync (:display-sync-hz @locals)))
(destroy-gl locals)
(Display/destroy)
(swap! locals assoc :active :no))
(defn- good-tex-count
[textures]
(if (<= (count textures) 4)
true
(do
(println "ERROR: number of textures must be <= 4")
false)))
(defn- expand-filename
"if there is a cubemap filename, expand it 0..5 for the
cubemaps. otherwise leave it alone."
[filename]
(if (cubemap-filename? filename)
(for [i (range 6)] (cubemap-filename filename i))
filename))
(defn- files-exist
"check to see that the filenames actually exist. One tweak is to
allow nil or keyword 'filenames'. Those are important placeholders.
Another tweak is to expand names for cubemap textures."
[filenames]
(let [full-filenames (flatten (map expand-filename filenames))]
(reduce #(and %1 %2) ; kibit keep
(for [fn full-filenames]
(if (or (nil? fn)
(and (keyword? fn) (= fn :previous-frame))
(.exists (File. ^String fn)))
true
(do
(println "ERROR:" fn "does not exist.")
false))))))
(defn- sane-user-inputs
[mode shader-filename shader-str textures title true-fullscreen? user-fn]
(and (good-tex-count textures)
(files-exist (flatten [shader-filename textures]))
(not (and (nil? shader-filename) (nil? shader-str)))))
;; watch the shader-str-atom to reload on a change
(defn- watch-shader-str-atom
[key identity old new]
(when (not= old new)
;; if already reloading, wait for that to finish
(while @reload-shader
;; FIXME this can hang. We should timeout instead
(Thread/sleep 100))
(reset! reload-shader-str new)
(reset! reload-shader true)))
;; watch the shader directory & reload the current shader if it changes.
(defn- if-match-reload-shader
[shader-filename files]
(if @watcher-just-started
;; allow first, automatic call to pass unnoticed
(reset! watcher-just-started false)
;; otherwise do the reload check
(doseq [f files]
(when (= (.getPath ^File f) shader-filename)
;; set a flag that the opengl thread will use
(reset! reload-shader true)))))
(defn- start-watcher
"create a watch for glsl shaders in the directory and return the global
future atom for that watcher"
[shader-filename]
(let [dir (.getParent (File. ^String shader-filename))]
(reset! watcher-just-started true)
(watcher/watcher
[dir]
(watcher/rate 100)
(watcher/file-filter watcher/ignore-dotfiles)
(watcher/file-filter (watcher/extensions :glsl))
(watcher/on-change (partial if-match-reload-shader shader-filename)))))
(defn- stop-watcher
"given a watcher-future f, put a stop to it"
[f]
(when-not (or (future-done? f) (future-cancelled? f))
(if (not (future-cancel f))
(println "ERROR: unable to stop-watcher!"))))
;; ======================================================================
;; allow shader to have user-data, just like tone.
;; I'd like to make this better follow DRY, but this seems okay for now
(defonce shader-user-data (atom {}))
(defonce shader-user-locs (atom {}))
(defn- shader-default-fn
[dispatch pgm-id]
(case dispatch ;; FIXME defmulti?
:init ;; find Uniform Location
(doseq [key (keys @shader-user-data)]
(let [loc (GL20/glGetUniformLocation ^Integer pgm-id ^String key)]
(swap! shader-user-locs assoc key loc)))
:pre-draw
(doseq [key (keys @shader-user-data)]
(let [loc (@shader-user-locs key)
val (deref (@shader-user-data key))]
;;(println key loc val)
(if (float? val)
(GL20/glUniform1f loc val)
(when (vector? val)
(case (count val)
1 (GL20/glUniform1f loc (nth val 0))
2 (GL20/glUniform2f loc (nth val 0) (nth val 1))
3 (GL20/glUniform3f loc (nth val 0) (nth val 1) (nth val 2))
4 (GL20/glUniform4f loc (nth val 0) (nth val 1) (nth val 2) (nth val 3)))))))
:post-draw
nil ;; nothing to do
:destroy
nil ;; nothing to do
))
;; Public API ===================================================
(defn display-modes
"Returns a seq of display modes sorted by resolution size with highest
resolution first and lowest last."
[]
(sort (fn [^DisplayMode a ^DisplayMode b]
(let [res-a (* (.getWidth a)
(.getHeight a))
res-b (* (.getWidth b)
(.getHeight b))
bit-depth-a (.getBitsPerPixel a)
bit-depth-b (.getBitsPerPixel b) ]
(if (= res-a res-b)
(> bit-depth-a bit-depth-b)
(> res-a res-b))))
(Display/getAvailableDisplayModes)))
(defn fullscreen-display-modes
"Returns a seq of fullscreen compatible display modes sorted by
resolution size with highest resolution first and lowest last."
[]
(filter #(.isFullscreenCapable ^DisplayMode %) (display-modes)))
(defn undecorate-display!
"All future display windows will be undecorated (i.e. no title bar)"
[]
(System/setProperty "org.lwjgl.opengl.Window.undecorated" "true"))
(defn decorate-display!
"All future display windows will be decorated (i.e. have a title bar)"
[]
(System/setProperty "org.lwjgl.opengl.Window.undecorated" "false"))
(defn active?
"Returns true if the shader display is currently running"
[]
(= :yes (:active @the-window-state)))
(defn inactive?
"Returns true if the shader display is completely done running."
[]
(= :no (:active @the-window-state)))
(defn stop
"Stop and destroy the shader display. Blocks until completed."
[]
(when (active?)
(swap! the-window-state assoc :active :stopping)
(while (not (inactive?))
(Thread/sleep 100)))
(remove-watch (:shader-str-atom @the-window-state) :shader-str-watch)
(stop-watcher @watcher-future))
(defn start-shader-display
"Start a new shader display with the specified mode. Prefer start or
start-fullscreen for simpler usage."
[mode shader-filename-or-str-atom textures title true-fullscreen?
user-data user-fn display-sync-hz]
(let [is-filename (not (instance? clojure.lang.Atom shader-filename-or-str-atom))
shader-filename (if is-filename
shader-filename-or-str-atom)
;; Fix for issue 15. Normalize the given shader-filename to the
;; path separators that the system will use. If user gives path/to/shader.glsl
;; and windows returns this as path\to\shader.glsl from .getPath, this
;; change should make comparison to path\to\shader.glsl work.
shader-filename (if (and is-filename (not (nil? shader-filename)))
(.getPath (File. ^String shader-filename)))
shader-str-atom (if-not is-filename
shader-filename-or-str-atom
(atom nil))
shader-str (if-not is-filename
@shader-str-atom)]
(when (sane-user-inputs mode shader-filename shader-str textures title true-fullscreen? user-fn)
;; stop the current shader
(stop)
;; start the watchers
(if is-filename
(when-not (nil? shader-filename)
(swap! watcher-future
(fn [x] (start-watcher shader-filename))))
(add-watch shader-str-atom :shader-str-watch watch-shader-str-atom))
;; set a global window-state instead of creating a new one
(reset! the-window-state default-state-values)
;; set user data
(reset! shader-user-data user-data)
;; start the requested shader
(.start (Thread.
(fn [] (run-thread the-window-state
mode
shader-filename
shader-str-atom
textures
title
true-fullscreen?
user-fn
display-sync-hz)))))))
(defn start
"Start a new shader display. Forces the display window to be
decorated (i.e. have a title bar)."
[shader-filename-or-str-atom
&{:keys [width height title display-sync-hz
textures user-data user-fn]
:or {width 600
height 600
title "shadertone"
display-sync-hz 60
textures []
user-data {}
user-fn shader-default-fn}}]
(let [mode (DisplayMode. width height)]
(decorate-display!)
(start-shader-display mode shader-filename-or-str-atom textures title false user-data user-fn display-sync-hz)))
(defn start-fullscreen
"Start a new shader display in pseudo fullscreen mode. This creates
a new borderless window which is the size of the current
resolution. There are therefore no OS controls for closing the
shader window. Use (stop) to close things manually."
[shader-filename-or-str-atom
&{:keys [display-sync-hz textures user-data user-fn]
:or {display-sync-hz 60
textures [nil]
user-data {}
user-fn shader-default-fn}}]
(let [mode (Display/getDisplayMode)]
(undecorate-display!)
(start-shader-display mode shader-filename-or-str-atom textures "" false user-data user-fn display-sync-hz)))
(defn throw-exceptions-on-gl-errors!
"When v is true, throw exceptions when glGetError() returns
non-zero. This is the default setting. When v is false, do not
throw the exception. Perhaps setting to false during a performance
will allow you to avoid over-agressive exceptions. Leave this true
otherwise." [v]
(reset! throw-on-gl-error v))
(defn pixel-read-enable!
"Enable reading a pixel each frame from location x,y. Be sure x,y
are valid or things may crash! Results are available via the
function (pixel) and via the atom @pixel-value"
[x y]
(swap! the-window-state assoc
:pixel-read-enable true
:pixel-read-pos-x x
:pixel-read-pos-y y)
nil)
(defn pixel-read-disable!
"Disable reading pixel values each frame."
[]
(swap! the-window-state assoc
:pixel-read-enable false)
nil)
(defn pixel
"Return the data that was read from the currently drawn frame at the
x,y location specified in the (pixel-read-enable! x y) call. When
enabled, a [red green blue] vector of floating point [0.0,1.0]
values is returned. Otherwise, [0.0 0.0 0.0] is returned."
[]
(if (:pixel-read-enable @the-window-state)
(get-pixel-value (:pixel-read-data @the-window-state))
[0.0 0.0 0.0]))
| true | (ns #^{:author "PI:NAME:<NAME>END_PI"
:doc "Shadertoy-like core library."}
shadertone.shader
(:require [watchtower.core :as watcher]
clojure.string)
(:import (java.awt.image BufferedImage DataBuffer DataBufferByte WritableRaster)
(java.io File FileInputStream)
(java.nio IntBuffer ByteBuffer FloatBuffer ByteOrder)
(java.util Calendar)
(javax.imageio ImageIO)
(java.lang.reflect Field)
(org.lwjgl BufferUtils)
(org.lwjgl.input Mouse)
(org.lwjgl.opengl ContextAttribs Display DisplayMode
GL11 GL12 GL13 GL15 GL20
PixelFormat)))
;; ======================================================================
;; State Variables
;; a map of state variables for use in the gl thread
(defonce default-state-values
{:active :no ;; :yes/:stopping/:no
:width 0
:height 0
:title ""
:display-sync-hz 60
:start-time 0
:last-time 0
;; mouse
:mouse-clicked false
:mouse-pos-x 0
:mouse-pos-y 0
:mouse-ori-x 0
:mouse-ori-y 0
;; geom ids
:vbo-id 0
:vertices-count 0
;; shader program
:shader-good true ;; false in error condition
:shader-filename nil
:shader-str-atom (atom nil)
:shader-str ""
:vs-id 0
:fs-id 0
:pgm-id 0
;; shader uniforms
:i-resolution-loc 0
:i-global-time-loc 0
:i-channel-time-loc 0
:i-mouse-loc 0
:i-channel-loc [0 0 0 0]
:i-channel-res-loc 0
:i-date-loc 0
:channel-time-buffer (-> (BufferUtils/createFloatBuffer 4)
(.put (float-array
[0.0 0.0 0.0 0.0]))
(.flip))
:channel-res-buffer (-> (BufferUtils/createFloatBuffer (* 3 4))
(.put (float-array
[0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0]))
(.flip))
;; textures
:tex-filenames []
:tex-ids []
:tex-types [] ; :cubemap, :previous-frame
;; a user draw function
:user-fn nil
;; pixel read
:pixel-read-enable false
:pixel-read-pos-x 0
:pixel-read-pos-y 0
:pixel-read-data (-> (BufferUtils/createByteBuffer 3)
(.put (byte-array (map byte [0 0 0])))
(.flip))
})
;; GLOBAL STATE ATOMS
;; Tried to get rid of this atom, but LWJGL is limited to only
;; one window. So, we just keep a single atom containing the
;; current window state here.
(defonce the-window-state (atom default-state-values))
;; The reload-shader atom communicates across the gl & watcher threads
(defonce reload-shader (atom false))
(defonce reload-shader-str (atom ""))
;; Atom for the directory watcher future
(defonce watcher-future (atom (future (fn [] nil))))
;; Flag to help avoid reloading shader right after loading it for the
;; first time.
(defonce watcher-just-started (atom true))
(defonce throw-on-gl-error (atom true))
;;
(defonce pixel-value (atom [0.0 0.0 0.0]))
;; ======================================================================
;; code modified from
;; https://github.com/ztellman/penumbra/blob/master/src/penumbra/opengl/core.clj
(defn- get-fields [#^Class static-class]
(. static-class getFields))
(defn- gl-enum-name
"Takes the numeric value of a gl constant (i.e. GL_LINEAR), and gives the name"
[enum-value]
(if (= 0 enum-value)
"NONE"
(.getName #^Field (some
#(if (= enum-value (.get #^Field % nil)) % nil)
(mapcat get-fields [GL11 GL12 GL13 GL15 GL20])))))
(defn- except-gl-errors
[msg]
(let [error (GL11/glGetError)
error-string (str "OpenGL Error(" error "):"
(gl-enum-name error) ": " msg)]
(if (and (not (zero? error)) @throw-on-gl-error)
(throw (Exception. error-string)))))
;; ======================================================================
(defn- fill-tex-filenames
"return a vector of 4 items, always. Use nil if no filename"
[tex-filenames]
(apply vector
(for [i (range 4)]
(if (< i (count tex-filenames))
(nth tex-filenames i)))))
(defn- uniform-sampler-type-str
[tex-types n]
(format "uniform sampler%s iChannel%s;\n"
(if (= :cubemap (nth tex-types 0)) "Cube" "2D")
n))
(defn- slurp-fs
"do whatever it takes to modify shadertoy fragment shader source to
be useable"
[locals filename]
(let [{:keys [tex-types]} @locals
;;file-str (slurp filename)
file-str (str "#version 120\n"
"uniform vec3 iResolution;\n"
"uniform float iGlobalTime;\n"
"uniform float iChannelTime[4];\n"
"uniform vec3 iChannelResolution[4];\n"
"uniform vec4 iMouse;\n"
(uniform-sampler-type-str tex-types 0)
(uniform-sampler-type-str tex-types 1)
(uniform-sampler-type-str tex-types 2)
(uniform-sampler-type-str tex-types 3)
"uniform vec4 iDate;\n"
"\n"
(slurp filename))]
file-str))
(defn- cubemap-filename?
"if a filename contains a '*' char, it is a cubemap"
[filename]
(if (string? filename)
(not (nil? (re-find #"\*" filename)))
false))
(defn- get-texture-type
[tex-filename]
(cond
(cubemap-filename? tex-filename) :cubemap
(= :previous-frame tex-filename) :previous-frame
:default :twod))
(defn- init-window
"Initialise a shader-powered window with the specified
display-mode. If true-fullscreen? is true, fullscreen mode is
attempted if the display-mode is compatible. See display-modes for a
list of available modes and fullscreen-display-modes for a list of
fullscreen compatible modes.."
[locals display-mode title shader-filename shader-str-atom tex-filenames true-fullscreen? user-fn display-sync-hz]
(let [width (.getWidth ^DisplayMode display-mode)
height (.getHeight ^DisplayMode display-mode)
pixel-format (PixelFormat.)
context-attributes (-> (ContextAttribs. 2 1)) ;; GL2.1
current-time-millis (System/currentTimeMillis)
tex-filenames (fill-tex-filenames tex-filenames)
tex-types (map get-texture-type tex-filenames)]
(swap! locals
assoc
:active :yes
:width width
:height height
:title title
:display-sync-hz display-sync-hz
:start-time current-time-millis
:last-time current-time-millis
:shader-filename shader-filename
:shader-str-atom shader-str-atom
:tex-filenames tex-filenames
:tex-types tex-types
:user-fn user-fn)
;; slurp-fs requires :tex-types, so we need a 2 pass setup
(let [shader-str (if (nil? shader-filename)
@shader-str-atom
(slurp-fs locals (:shader-filename @locals)))]
(swap! locals assoc :shader-str shader-str)
(Display/setDisplayMode display-mode)
(when true-fullscreen?
(Display/setFullscreen true))
(Display/setTitle title)
(Display/setVSyncEnabled true)
(Display/setLocation 0 0)
(Display/create pixel-format context-attributes))))
(defn- init-buffers
[locals]
(let [vertices (float-array
[-1.0 -1.0 0.0 1.0
1.0 -1.0 0.0 1.0
-1.0 1.0 0.0 1.0
-1.0 1.0 0.0 1.0
1.0 -1.0 0.0 1.0
1.0 1.0 0.0 1.0])
vertices-buffer (-> (BufferUtils/createFloatBuffer (count vertices))
(.put vertices)
(.flip))
vertices-count (count vertices)
vbo-id (GL15/glGenBuffers)
_ (GL15/glBindBuffer GL15/GL_ARRAY_BUFFER vbo-id)
_ (GL15/glBufferData GL15/GL_ARRAY_BUFFER
^FloatBuffer vertices-buffer
GL15/GL_STATIC_DRAW)
_ (except-gl-errors "@ end of init-buffers")]
(swap! locals
assoc
:vbo-id vbo-id
:vertices-count vertices-count)))
(def vs-shader
(str "#version 120\n"
"void main(void) {\n"
" gl_Position = gl_Vertex;\n"
"}\n"))
(defn- load-shader
[^String shader-str ^Integer shader-type]
(let [shader-id (GL20/glCreateShader shader-type)
_ (except-gl-errors "@ load-shader glCreateShader ")
_ (GL20/glShaderSource shader-id shader-str)
_ (except-gl-errors "@ load-shader glShaderSource ")
_ (GL20/glCompileShader shader-id)
_ (except-gl-errors "@ load-shader glCompileShader ")
gl-compile-status (GL20/glGetShaderi shader-id GL20/GL_COMPILE_STATUS)
_ (except-gl-errors "@ end of let load-shader")]
(when (== gl-compile-status GL11/GL_FALSE)
(println "ERROR: Loading a Shader:")
(println (GL20/glGetShaderInfoLog shader-id 10000)))
[gl-compile-status shader-id]))
(defn- init-shaders
[locals]
(let [[ok? vs-id] (load-shader vs-shader GL20/GL_VERTEX_SHADER)
_ (assert (== ok? GL11/GL_TRUE)) ;; something is really wrong if our vs is bad
_ (if (nil? (:shader-filename @locals))
(println "Loading shader from string")
(println "Loading shader from file:" (:shader-filename @locals)))
[ok? fs-id] (load-shader (:shader-str @locals) GL20/GL_FRAGMENT_SHADER)]
(if (== ok? GL11/GL_TRUE)
(let [pgm-id (GL20/glCreateProgram)
_ (except-gl-errors "@ let init-shaders glCreateProgram")
_ (GL20/glAttachShader pgm-id vs-id)
_ (except-gl-errors "@ let init-shaders glAttachShader VS")
_ (GL20/glAttachShader pgm-id fs-id)
_ (except-gl-errors "@ let init-shaders glAttachShader FS")
_ (GL20/glLinkProgram pgm-id)
_ (except-gl-errors "@ let init-shaders glLinkProgram")
gl-link-status (GL20/glGetProgrami pgm-id GL20/GL_LINK_STATUS)
_ (except-gl-errors "@ let init-shaders glGetProgram link status")
_ (when (== gl-link-status GL11/GL_FALSE)
(println "ERROR: Linking Shaders:")
(println (GL20/glGetProgramInfoLog pgm-id 10000)))
_ (except-gl-errors "@ let before GetUniformLocation")
i-resolution-loc (GL20/glGetUniformLocation pgm-id "iResolution")
i-global-time-loc (GL20/glGetUniformLocation pgm-id "iGlobalTime")
i-channel-time-loc (GL20/glGetUniformLocation pgm-id "iChannelTime")
i-mouse-loc (GL20/glGetUniformLocation pgm-id "iMouse")
i-channel0-loc (GL20/glGetUniformLocation pgm-id "iChannel0")
i-channel1-loc (GL20/glGetUniformLocation pgm-id "iChannel1")
i-channel2-loc (GL20/glGetUniformLocation pgm-id "iChannel2")
i-channel3-loc (GL20/glGetUniformLocation pgm-id "iChannel3")
i-channel-res-loc (GL20/glGetUniformLocation pgm-id "iChannelResolution")
i-date-loc (GL20/glGetUniformLocation pgm-id "iDate")
_ (except-gl-errors "@ end of let init-shaders")
]
(swap! locals
assoc
:shader-good true
:vs-id vs-id
:fs-id fs-id
:pgm-id pgm-id
:i-resolution-loc i-resolution-loc
:i-global-time-loc i-global-time-loc
:i-channel-time-loc i-channel-time-loc
:i-mouse-loc i-mouse-loc
:i-channel-loc [i-channel0-loc i-channel1-loc i-channel2-loc i-channel3-loc]
:i-channel-res-loc i-channel-res-loc
:i-date-loc i-date-loc))
;; we didn't load the shader, don't be drawing
(swap! locals assoc :shader-good false))))
(defn- buffer-swizzle-0123-1230
"given a ARGB pixel array, swizzle it to be RGBA. Or, ABGR to BGRA"
^bytes [^bytes data] ;; Wow! That ^bytes changes this from 10s for a 256x256 tex to instantaneous.
(dotimes [i (/ (alength data) 4)]
(let [i0 (* i 4)
i1 (inc i0)
i2 (inc i1)
i3 (inc i2)
tmp (aget data i0)]
(aset data i0 (aget data i1))
(aset data i1 (aget data i2))
(aset data i2 (aget data i3))
(aset data i3 tmp)))
data)
(defn- cubemap-filename
[filename i]
(clojure.string/replace filename "*" (str i)))
(defn- put-texture-data
"put the data from the image into the buffer and return the buffer"
^ByteBuffer
[^ByteBuffer buffer ^BufferedImage image ^Boolean swizzle-0123-1230]
(let [data ^bytes (-> ^WritableRaster (.getRaster image)
^DataBufferByte (.getDataBuffer)
(.getData))
data (if swizzle-0123-1230
(buffer-swizzle-0123-1230 data)
data)
buffer (.put buffer data 0 (alength data))] ; (.order (ByteOrder/nativeOrder)) ?
buffer))
(defn- tex-image-bytes
"return the number of bytes per pixel in this image"
[^BufferedImage image]
(let [image-type (.getType image)
image-bytes (if (or (= image-type BufferedImage/TYPE_3BYTE_BGR)
(= image-type BufferedImage/TYPE_INT_RGB))
3
(if (or (= image-type BufferedImage/TYPE_4BYTE_ABGR)
(= image-type BufferedImage/TYPE_INT_ARGB))
4
0)) ;; unhandled image type--what to do?
;; _ (println "image-type"
;; (cond
;; (= image-type BufferedImage/TYPE_3BYTE_BGR) "TYPE_3BYTE_BGR"
;; (= image-type BufferedImage/TYPE_INT_RGB) "TYPE_INT_RGB"
;; (= image-type BufferedImage/TYPE_4BYTE_ABGR) "TYPE_4BYTE_ABGR"
;; (= image-type BufferedImage/TYPE_INT_ARGB) "TYPE_INT_ARGB"
;; :else image-type))
_ (assert (pos? image-bytes))] ;; die on unhandled image
image-bytes))
(defn- tex-internal-format
"return the internal-format for the glTexImage2D call for this image"
^Integer
[^BufferedImage image]
(let [image-type (.getType image)
internal-format (cond
(= image-type BufferedImage/TYPE_3BYTE_BGR) GL11/GL_RGB8
(= image-type BufferedImage/TYPE_INT_RGB) GL11/GL_RGB8
(= image-type BufferedImage/TYPE_4BYTE_ABGR) GL11/GL_RGBA8
(= image-type BufferedImage/TYPE_INT_ARGB) GL11/GL_RGBA8)]
internal-format))
(defn- tex-format
"return the format for the glTexImage2D call for this image"
^Integer
[^BufferedImage image]
(let [image-type (.getType image)
format (cond
(= image-type BufferedImage/TYPE_3BYTE_BGR) GL12/GL_BGR
(= image-type BufferedImage/TYPE_INT_RGB) GL11/GL_RGB
(= image-type BufferedImage/TYPE_4BYTE_ABGR) GL12/GL_BGRA
(= image-type BufferedImage/TYPE_INT_ARGB) GL11/GL_RGBA)]
format))
(defn- load-texture
"load, bind texture from filename. returns a texture info vector
[tex-id width height z]. returns nil tex-id if filename is nil"
([^String filename]
(let [tex-id (GL11/glGenTextures)]
(if (cubemap-filename? filename)
(do
(dotimes [i 6]
(load-texture (cubemap-filename filename i)
GL13/GL_TEXTURE_CUBE_MAP tex-id i))
[tex-id 0.0 0.0 0.0]) ;; cubemaps don't update w/h
(load-texture filename GL11/GL_TEXTURE_2D tex-id 0))))
([^String filename ^Integer target ^Integer tex-id ^Integer i]
(if (string? filename)
;; load from file
(let [_ (println "Loading texture:" filename)
image (ImageIO/read (FileInputStream. filename))
image-bytes (tex-image-bytes image)
internal-format (tex-internal-format image)
format (tex-format image)
nbytes (* image-bytes (.getWidth image) (.getHeight image))
buffer ^ByteBuffer (-> (BufferUtils/createByteBuffer nbytes)
(put-texture-data image (= image-bytes 4))
(.flip))
tex-image-target ^Integer (if (= target GL13/GL_TEXTURE_CUBE_MAP)
(+ i GL13/GL_TEXTURE_CUBE_MAP_POSITIVE_X)
target)]
(GL11/glBindTexture target tex-id)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MAG_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MIN_FILTER GL11/GL_LINEAR)
(if (== target GL11/GL_TEXTURE_2D)
(do
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_S GL11/GL_REPEAT)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_T GL11/GL_REPEAT))
(do ;; CUBE_MAP
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)))
(GL11/glTexImage2D ^Integer tex-image-target 0 ^Integer internal-format
^Integer (.getWidth image) ^Integer (.getHeight image) 0
^Integer format
GL11/GL_UNSIGNED_BYTE
^ByteBuffer buffer)
(except-gl-errors "@ end of load-texture if-stmt")
[tex-id (.getWidth image) (.getHeight image) 1.0])
(if (= filename :previous-frame)
(do ;; :previous-frame initial setup
(println "setting up :previous-frame texture")
(GL11/glBindTexture target tex-id)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MAG_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri target GL11/GL_TEXTURE_MIN_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri target GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)
(except-gl-errors "@ end of load-texture else-stmt")
;; use negative as flag to indicate using window width, height
[tex-id -1.0 -1.0 1.0])
;; else must be nil texture
[nil 0.0 0.0 0.0]))))
(defn- init-textures
[locals]
(let [tex-infos (map load-texture (:tex-filenames @locals))
;;_ (println "raw" tex-infos)
tex-ids (map first tex-infos)
tex-whd (map rest tex-infos)
tex-whd (flatten
(map #(if (< (first %) 0.0)
[(:width @locals) (:height @locals) 1.0]
%)
tex-whd))
;; update channel-res-buffer
_ (-> ^FloatBuffer (:channel-res-buffer @locals)
(.put ^floats (float-array tex-whd))
(.flip))
]
(swap! locals assoc
:tex-ids tex-ids)))
(defn- init-gl
[locals]
(let [{:keys [width height user-fn]} @locals]
;;(println "OpenGL version:" (GL11/glGetString GL11/GL_VERSION))
(GL11/glClearColor 0.0 0.0 0.0 0.0)
(GL11/glViewport 0 0 width height)
(init-buffers locals)
(init-textures locals)
(init-shaders locals)
(when (and (not (nil? user-fn)) (:shader-good @locals))
(user-fn :init (:pgm-id @locals)))))
(defn- try-reload-shader
[locals]
(let [{:keys [vs-id fs-id pgm-id shader-filename user-fn]} @locals
vs-id (if (= vs-id 0)
(let [[ok? vs-id] (load-shader vs-shader GL20/GL_VERTEX_SHADER)
_ (assert (== ok? GL11/GL_TRUE))]
vs-id)
vs-id)
fs-shader (if (nil? shader-filename)
@reload-shader-str
(slurp-fs locals shader-filename))
[ok? new-fs-id] (load-shader fs-shader GL20/GL_FRAGMENT_SHADER)
_ (reset! reload-shader false)]
(if (== ok? GL11/GL_FALSE)
;; we didn't reload a good shader. Go back to the old one if possible
(when (:shader-good @locals)
(GL20/glUseProgram pgm-id)
(except-gl-errors "@ try-reload-shader useProgram1"))
;; the load shader went well, keep going...
(let [new-pgm-id (GL20/glCreateProgram)
_ (except-gl-errors "@ try-reload-shader glCreateProgram")
_ (GL20/glAttachShader new-pgm-id vs-id)
_ (except-gl-errors "@ try-reload-shader glAttachShader VS")
_ (GL20/glAttachShader new-pgm-id new-fs-id)
_ (except-gl-errors "@ try-reload-shader glAttachShader FS")
_ (GL20/glLinkProgram new-pgm-id)
_ (except-gl-errors "@ try-reload-shader glLinkProgram")
gl-link-status (GL20/glGetProgrami new-pgm-id GL20/GL_LINK_STATUS)
_ (except-gl-errors "@ end of let try-reload-shader")]
(if (== gl-link-status GL11/GL_FALSE)
(do
(println "ERROR: Linking Shaders: (reloading previous program)")
(println (GL20/glGetProgramInfoLog new-pgm-id 10000))
(GL20/glUseProgram pgm-id)
(except-gl-errors "@ try-reload-shader useProgram2"))
(let [_ (println "Reloading shader:" shader-filename)
i-resolution-loc (GL20/glGetUniformLocation new-pgm-id "iResolution")
i-global-time-loc (GL20/glGetUniformLocation new-pgm-id "iGlobalTime")
i-channel-time-loc (GL20/glGetUniformLocation new-pgm-id "iChannelTime")
i-mouse-loc (GL20/glGetUniformLocation new-pgm-id "iMouse")
i-channel0-loc (GL20/glGetUniformLocation new-pgm-id "iChannel0")
i-channel1-loc (GL20/glGetUniformLocation new-pgm-id "iChannel1")
i-channel2-loc (GL20/glGetUniformLocation new-pgm-id "iChannel2")
i-channel3-loc (GL20/glGetUniformLocation new-pgm-id "iChannel3")
i-channel-res-loc (GL20/glGetUniformLocation new-pgm-id "iChannelResolution")
i-date-loc (GL20/glGetUniformLocation new-pgm-id "iDate")]
(GL20/glUseProgram new-pgm-id)
(except-gl-errors "@ try-reload-shader useProgram")
(when user-fn
(user-fn :init new-pgm-id))
;; cleanup the old program
(when (not= pgm-id 0)
(GL20/glDetachShader pgm-id vs-id)
(GL20/glDetachShader pgm-id fs-id)
(GL20/glDeleteShader fs-id))
(except-gl-errors "@ try-reload-shader detach/delete")
(swap! locals
assoc
:shader-good true
:fs-id new-fs-id
:pgm-id new-pgm-id
:i-resolution-loc i-resolution-loc
:i-global-time-loc i-global-time-loc
:i-channel-time-loc i-channel-time-loc
:i-mouse-loc i-mouse-loc
:i-channel-loc [i-channel0-loc i-channel1-loc i-channel2-loc i-channel3-loc]
:i-channel-res-loc i-channel-res-loc
:i-date-loc i-date-loc
:shader-str fs-shader)))))))
(defn- get-pixel-value
[^ByteBuffer rgb-bytes]
(let [rf (/ (float (int (bit-and 0xFF (.get rgb-bytes 0)))) 255.0)
gf (/ (float (int (bit-and 0xFF (.get rgb-bytes 1)))) 255.0)
bf (/ (float (int (bit-and 0xFF (.get rgb-bytes 2)))) 255.0)]
[rf gf bf]))
(defn- draw
[locals]
(let [{:keys [width height i-resolution-loc
start-time last-time i-global-time-loc
i-date-loc
pgm-id vbo-id
vertices-count
i-mouse-loc
mouse-pos-x mouse-pos-y
mouse-ori-x mouse-ori-y
i-channel-time-loc i-channel-loc
i-channel-res-loc
channel-time-buffer channel-res-buffer
old-pgm-id old-fs-id
tex-ids tex-types
user-fn
pixel-read-enable
pixel-read-pos-x pixel-read-pos-y
pixel-read-data]} @locals
cur-time (/ (- last-time start-time) 1000.0)
_ (.put ^FloatBuffer channel-time-buffer 0 (float cur-time))
_ (.put ^FloatBuffer channel-time-buffer 1 (float cur-time))
_ (.put ^FloatBuffer channel-time-buffer 2 (float cur-time))
_ (.put ^FloatBuffer channel-time-buffer 3 (float cur-time))
cur-date (Calendar/getInstance)
cur-year (.get cur-date Calendar/YEAR) ;; four digit year
cur-month (.get cur-date Calendar/MONTH) ;; month 0-11
cur-day (.get cur-date Calendar/DAY_OF_MONTH) ;; day 1-31
cur-seconds (+ (* (.get cur-date Calendar/HOUR_OF_DAY) 60.0 60.0)
(* (.get cur-date Calendar/MINUTE) 60.0)
(.get cur-date Calendar/SECOND))]
(except-gl-errors "@ draw before clear")
(GL11/glClear GL11/GL_COLOR_BUFFER_BIT)
(when user-fn
(user-fn :pre-draw pgm-id))
;; activate textures
(dotimes [i (count tex-ids)]
(when (nth tex-ids i)
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 i))
(cond
(= :cubemap (nth tex-types i))
(GL11/glBindTexture GL13/GL_TEXTURE_CUBE_MAP (nth tex-ids i))
(= :previous-frame (nth tex-types i))
(GL11/glBindTexture GL11/GL_TEXTURE_2D (nth tex-ids i))
:default
(GL11/glBindTexture GL11/GL_TEXTURE_2D (nth tex-ids i)))))
(except-gl-errors "@ draw after activate textures")
;; setup our uniform
(GL20/glUniform3f i-resolution-loc width height 1.0)
(GL20/glUniform1f i-global-time-loc cur-time)
(GL20/glUniform1 ^Integer i-channel-time-loc ^FloatBuffer channel-time-buffer)
(GL20/glUniform4f i-mouse-loc
mouse-pos-x
mouse-pos-y
mouse-ori-x
mouse-ori-y)
(GL20/glUniform1i (nth i-channel-loc 0) 0)
(GL20/glUniform1i (nth i-channel-loc 1) 1)
(GL20/glUniform1i (nth i-channel-loc 2) 2)
(GL20/glUniform1i (nth i-channel-loc 3) 3)
(GL20/glUniform3 ^Integer i-channel-res-loc ^FloatBuffer channel-res-buffer)
(GL20/glUniform4f i-date-loc cur-year cur-month cur-day cur-seconds)
;; get vertex array ready
(GL11/glEnableClientState GL11/GL_VERTEX_ARRAY)
(GL15/glBindBuffer GL15/GL_ARRAY_BUFFER vbo-id)
(GL11/glVertexPointer 4 GL11/GL_FLOAT 0 0)
(except-gl-errors "@ draw prior to DrawArrays")
;; Draw the vertices
(GL11/glDrawArrays GL11/GL_TRIANGLES 0 vertices-count)
(except-gl-errors "@ draw after DrawArrays")
;; Put everything back to default (deselect)
(GL15/glBindBuffer GL15/GL_ARRAY_BUFFER 0)
(GL11/glDisableClientState GL11/GL_VERTEX_ARRAY)
;; unbind textures
(dotimes [i (count tex-ids)]
(when (nth tex-ids i)
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 i))
(GL11/glBindTexture GL13/GL_TEXTURE_CUBE_MAP 0)
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0)))
(except-gl-errors "@ draw prior to post-draw")
(when user-fn
(user-fn :post-draw pgm-id))
(except-gl-errors "@ draw after post-draw")
(GL20/glUseProgram 0)
;; copy the rendered image
(dotimes [i (count tex-ids)]
(when (= :previous-frame (nth tex-types i))
(GL11/glBindTexture GL11/GL_TEXTURE_2D (nth tex-ids i))
(GL11/glCopyTexImage2D GL11/GL_TEXTURE_2D 0 GL11/GL_RGBA8 0 0 width height 0)
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0)))
(except-gl-errors "@ draw after copy")
;; read a pixel value
(when pixel-read-enable
(GL11/glReadPixels ^Integer pixel-read-pos-x ^Integer pixel-read-pos-y
1 1
GL11/GL_RGB GL11/GL_UNSIGNED_BYTE
^ByteBuffer pixel-read-data)
(except-gl-errors "@ draw after pixel read")
(reset! pixel-value (get-pixel-value ^ByteBuffer pixel-read-data)))))
(defn- update-and-draw
[locals]
(let [{:keys [width height last-time pgm-id
mouse-pos-x mouse-pos-y
mouse-clicked mouse-ori-x mouse-ori-y]} @locals
cur-time (System/currentTimeMillis)
cur-mouse-clicked (Mouse/isButtonDown 0)
mouse-down-event (and cur-mouse-clicked (not mouse-clicked))
cur-mouse-pos-x (if cur-mouse-clicked (Mouse/getX) mouse-pos-x)
cur-mouse-pos-y (if cur-mouse-clicked (Mouse/getY) mouse-pos-y)
cur-mouse-ori-x (if mouse-down-event
(Mouse/getX)
(if cur-mouse-clicked
mouse-ori-x
(- (Math/abs ^float mouse-ori-x))))
cur-mouse-ori-y (if mouse-down-event
(Mouse/getY)
(if cur-mouse-clicked
mouse-ori-y
(- (Math/abs ^float mouse-ori-y))))]
(swap! locals
assoc
:last-time cur-time
:mouse-clicked cur-mouse-clicked
:mouse-pos-x cur-mouse-pos-x
:mouse-pos-y cur-mouse-pos-y
:mouse-ori-x cur-mouse-ori-x
:mouse-ori-y cur-mouse-ori-y)
(if (:shader-good @locals)
(do
(if @reload-shader
(try-reload-shader locals) ; this must call glUseProgram
(GL20/glUseProgram pgm-id)) ; else, normal path...
(draw locals))
;; else clear to prevent strobing awfulness
(do
(GL11/glClear GL11/GL_COLOR_BUFFER_BIT)
(except-gl-errors "@ bad-draw glClear ")
(if @reload-shader
(try-reload-shader locals))))))
(defn- destroy-gl
[locals]
(let [{:keys [pgm-id vs-id fs-id vbo-id user-fn]} @locals]
;; Delete any user state
(when user-fn
(user-fn :destroy pgm-id))
;; Delete the shaders
(GL20/glUseProgram 0)
(GL20/glDetachShader pgm-id vs-id)
(GL20/glDetachShader pgm-id fs-id)
(GL20/glDeleteShader vs-id)
(GL20/glDeleteShader fs-id)
(GL20/glDeleteProgram pgm-id)
;; Delete the vertex VBO
(GL15/glBindBuffer GL15/GL_ARRAY_BUFFER 0)
(GL15/glDeleteBuffers ^Integer vbo-id)))
(defn- run-thread
[locals mode shader-filename shader-str-atom tex-filenames title true-fullscreen? user-fn display-sync-hz]
(init-window locals mode title shader-filename shader-str-atom tex-filenames true-fullscreen? user-fn display-sync-hz)
(init-gl locals)
(while (and (= :yes (:active @locals))
(not (Display/isCloseRequested)))
(update-and-draw locals)
(Display/update)
(Display/sync (:display-sync-hz @locals)))
(destroy-gl locals)
(Display/destroy)
(swap! locals assoc :active :no))
(defn- good-tex-count
[textures]
(if (<= (count textures) 4)
true
(do
(println "ERROR: number of textures must be <= 4")
false)))
(defn- expand-filename
"if there is a cubemap filename, expand it 0..5 for the
cubemaps. otherwise leave it alone."
[filename]
(if (cubemap-filename? filename)
(for [i (range 6)] (cubemap-filename filename i))
filename))
(defn- files-exist
"check to see that the filenames actually exist. One tweak is to
allow nil or keyword 'filenames'. Those are important placeholders.
Another tweak is to expand names for cubemap textures."
[filenames]
(let [full-filenames (flatten (map expand-filename filenames))]
(reduce #(and %1 %2) ; kibit keep
(for [fn full-filenames]
(if (or (nil? fn)
(and (keyword? fn) (= fn :previous-frame))
(.exists (File. ^String fn)))
true
(do
(println "ERROR:" fn "does not exist.")
false))))))
(defn- sane-user-inputs
[mode shader-filename shader-str textures title true-fullscreen? user-fn]
(and (good-tex-count textures)
(files-exist (flatten [shader-filename textures]))
(not (and (nil? shader-filename) (nil? shader-str)))))
;; watch the shader-str-atom to reload on a change
(defn- watch-shader-str-atom
[key identity old new]
(when (not= old new)
;; if already reloading, wait for that to finish
(while @reload-shader
;; FIXME this can hang. We should timeout instead
(Thread/sleep 100))
(reset! reload-shader-str new)
(reset! reload-shader true)))
;; watch the shader directory & reload the current shader if it changes.
(defn- if-match-reload-shader
[shader-filename files]
(if @watcher-just-started
;; allow first, automatic call to pass unnoticed
(reset! watcher-just-started false)
;; otherwise do the reload check
(doseq [f files]
(when (= (.getPath ^File f) shader-filename)
;; set a flag that the opengl thread will use
(reset! reload-shader true)))))
(defn- start-watcher
"create a watch for glsl shaders in the directory and return the global
future atom for that watcher"
[shader-filename]
(let [dir (.getParent (File. ^String shader-filename))]
(reset! watcher-just-started true)
(watcher/watcher
[dir]
(watcher/rate 100)
(watcher/file-filter watcher/ignore-dotfiles)
(watcher/file-filter (watcher/extensions :glsl))
(watcher/on-change (partial if-match-reload-shader shader-filename)))))
(defn- stop-watcher
"given a watcher-future f, put a stop to it"
[f]
(when-not (or (future-done? f) (future-cancelled? f))
(if (not (future-cancel f))
(println "ERROR: unable to stop-watcher!"))))
;; ======================================================================
;; allow shader to have user-data, just like tone.
;; I'd like to make this better follow DRY, but this seems okay for now
(defonce shader-user-data (atom {}))
(defonce shader-user-locs (atom {}))
(defn- shader-default-fn
[dispatch pgm-id]
(case dispatch ;; FIXME defmulti?
:init ;; find Uniform Location
(doseq [key (keys @shader-user-data)]
(let [loc (GL20/glGetUniformLocation ^Integer pgm-id ^String key)]
(swap! shader-user-locs assoc key loc)))
:pre-draw
(doseq [key (keys @shader-user-data)]
(let [loc (@shader-user-locs key)
val (deref (@shader-user-data key))]
;;(println key loc val)
(if (float? val)
(GL20/glUniform1f loc val)
(when (vector? val)
(case (count val)
1 (GL20/glUniform1f loc (nth val 0))
2 (GL20/glUniform2f loc (nth val 0) (nth val 1))
3 (GL20/glUniform3f loc (nth val 0) (nth val 1) (nth val 2))
4 (GL20/glUniform4f loc (nth val 0) (nth val 1) (nth val 2) (nth val 3)))))))
:post-draw
nil ;; nothing to do
:destroy
nil ;; nothing to do
))
;; Public API ===================================================
(defn display-modes
"Returns a seq of display modes sorted by resolution size with highest
resolution first and lowest last."
[]
(sort (fn [^DisplayMode a ^DisplayMode b]
(let [res-a (* (.getWidth a)
(.getHeight a))
res-b (* (.getWidth b)
(.getHeight b))
bit-depth-a (.getBitsPerPixel a)
bit-depth-b (.getBitsPerPixel b) ]
(if (= res-a res-b)
(> bit-depth-a bit-depth-b)
(> res-a res-b))))
(Display/getAvailableDisplayModes)))
(defn fullscreen-display-modes
"Returns a seq of fullscreen compatible display modes sorted by
resolution size with highest resolution first and lowest last."
[]
(filter #(.isFullscreenCapable ^DisplayMode %) (display-modes)))
(defn undecorate-display!
"All future display windows will be undecorated (i.e. no title bar)"
[]
(System/setProperty "org.lwjgl.opengl.Window.undecorated" "true"))
(defn decorate-display!
"All future display windows will be decorated (i.e. have a title bar)"
[]
(System/setProperty "org.lwjgl.opengl.Window.undecorated" "false"))
(defn active?
"Returns true if the shader display is currently running"
[]
(= :yes (:active @the-window-state)))
(defn inactive?
"Returns true if the shader display is completely done running."
[]
(= :no (:active @the-window-state)))
(defn stop
"Stop and destroy the shader display. Blocks until completed."
[]
(when (active?)
(swap! the-window-state assoc :active :stopping)
(while (not (inactive?))
(Thread/sleep 100)))
(remove-watch (:shader-str-atom @the-window-state) :shader-str-watch)
(stop-watcher @watcher-future))
(defn start-shader-display
"Start a new shader display with the specified mode. Prefer start or
start-fullscreen for simpler usage."
[mode shader-filename-or-str-atom textures title true-fullscreen?
user-data user-fn display-sync-hz]
(let [is-filename (not (instance? clojure.lang.Atom shader-filename-or-str-atom))
shader-filename (if is-filename
shader-filename-or-str-atom)
;; Fix for issue 15. Normalize the given shader-filename to the
;; path separators that the system will use. If user gives path/to/shader.glsl
;; and windows returns this as path\to\shader.glsl from .getPath, this
;; change should make comparison to path\to\shader.glsl work.
shader-filename (if (and is-filename (not (nil? shader-filename)))
(.getPath (File. ^String shader-filename)))
shader-str-atom (if-not is-filename
shader-filename-or-str-atom
(atom nil))
shader-str (if-not is-filename
@shader-str-atom)]
(when (sane-user-inputs mode shader-filename shader-str textures title true-fullscreen? user-fn)
;; stop the current shader
(stop)
;; start the watchers
(if is-filename
(when-not (nil? shader-filename)
(swap! watcher-future
(fn [x] (start-watcher shader-filename))))
(add-watch shader-str-atom :shader-str-watch watch-shader-str-atom))
;; set a global window-state instead of creating a new one
(reset! the-window-state default-state-values)
;; set user data
(reset! shader-user-data user-data)
;; start the requested shader
(.start (Thread.
(fn [] (run-thread the-window-state
mode
shader-filename
shader-str-atom
textures
title
true-fullscreen?
user-fn
display-sync-hz)))))))
(defn start
"Start a new shader display. Forces the display window to be
decorated (i.e. have a title bar)."
[shader-filename-or-str-atom
&{:keys [width height title display-sync-hz
textures user-data user-fn]
:or {width 600
height 600
title "shadertone"
display-sync-hz 60
textures []
user-data {}
user-fn shader-default-fn}}]
(let [mode (DisplayMode. width height)]
(decorate-display!)
(start-shader-display mode shader-filename-or-str-atom textures title false user-data user-fn display-sync-hz)))
(defn start-fullscreen
"Start a new shader display in pseudo fullscreen mode. This creates
a new borderless window which is the size of the current
resolution. There are therefore no OS controls for closing the
shader window. Use (stop) to close things manually."
[shader-filename-or-str-atom
&{:keys [display-sync-hz textures user-data user-fn]
:or {display-sync-hz 60
textures [nil]
user-data {}
user-fn shader-default-fn}}]
(let [mode (Display/getDisplayMode)]
(undecorate-display!)
(start-shader-display mode shader-filename-or-str-atom textures "" false user-data user-fn display-sync-hz)))
(defn throw-exceptions-on-gl-errors!
"When v is true, throw exceptions when glGetError() returns
non-zero. This is the default setting. When v is false, do not
throw the exception. Perhaps setting to false during a performance
will allow you to avoid over-agressive exceptions. Leave this true
otherwise." [v]
(reset! throw-on-gl-error v))
(defn pixel-read-enable!
"Enable reading a pixel each frame from location x,y. Be sure x,y
are valid or things may crash! Results are available via the
function (pixel) and via the atom @pixel-value"
[x y]
(swap! the-window-state assoc
:pixel-read-enable true
:pixel-read-pos-x x
:pixel-read-pos-y y)
nil)
(defn pixel-read-disable!
"Disable reading pixel values each frame."
[]
(swap! the-window-state assoc
:pixel-read-enable false)
nil)
(defn pixel
"Return the data that was read from the currently drawn frame at the
x,y location specified in the (pixel-read-enable! x y) call. When
enabled, a [red green blue] vector of floating point [0.0,1.0]
values is returned. Otherwise, [0.0 0.0 0.0] is returned."
[]
(if (:pixel-read-enable @the-window-state)
(get-pixel-value (:pixel-read-data @the-window-state))
[0.0 0.0 0.0]))
|
[
{
"context": " (let [user (ebay.models.user/map->User {:username username :password password})]\n (cond \n (ebay.",
"end": 315,
"score": 0.5401812195777893,
"start": 307,
"tag": "USERNAME",
"value": "username"
},
{
"context": " (let [user (ebay.models.user/map->User {:username username :password password})]\n (cond\n (not (e",
"end": 725,
"score": 0.5257887840270996,
"start": 717,
"tag": "USERNAME",
"value": "username"
},
{
"context": "odels.user/map->User {:username username :password password})]\n (cond\n (not (ebay.services.sniper",
"end": 744,
"score": 0.7283640503883362,
"start": 736,
"tag": "PASSWORD",
"value": "password"
}
] | src/ebay/routes/users.clj | bocuma/ebby-sniper-api | 2 | (ns ebay.routes.users
(:require
[ebay.models.user]
[ebay.services.sniper]
[compojure.core :refer [defroutes GET POST PUT DELETE]]
[ring.util.http-response :refer [ok]]))
(defroutes users-routes
(POST "/users" [username password]
(let [user (ebay.models.user/map->User {:username username :password password})]
(cond
(ebay.services.sniper/invalid? user) {:status 406}
(ebay.services.sniper/exists? user) {:status 200 :body (str "/users/" username)}
(ebay.services.sniper/save user) {:status 201 :body (str "/users/" username)}
:else {:status 500})))
(PUT "/users/:username" [username password]
(let [user (ebay.models.user/map->User {:username username :password password})]
(cond
(not (ebay.services.sniper/exists? user)) {:status 404}
(ebay.services.sniper/edit user) {:status 200}
:else {:status 406})))
(DELETE "/users/:username" [username]
(let [user (ebay.models.user/map->User {:username username})]
(cond
(not (ebay.services.sniper/exists? user)) {:status 404}
(ebay.services.sniper/delete user) {:status 200}))))
| 111206 | (ns ebay.routes.users
(:require
[ebay.models.user]
[ebay.services.sniper]
[compojure.core :refer [defroutes GET POST PUT DELETE]]
[ring.util.http-response :refer [ok]]))
(defroutes users-routes
(POST "/users" [username password]
(let [user (ebay.models.user/map->User {:username username :password password})]
(cond
(ebay.services.sniper/invalid? user) {:status 406}
(ebay.services.sniper/exists? user) {:status 200 :body (str "/users/" username)}
(ebay.services.sniper/save user) {:status 201 :body (str "/users/" username)}
:else {:status 500})))
(PUT "/users/:username" [username password]
(let [user (ebay.models.user/map->User {:username username :password <PASSWORD>})]
(cond
(not (ebay.services.sniper/exists? user)) {:status 404}
(ebay.services.sniper/edit user) {:status 200}
:else {:status 406})))
(DELETE "/users/:username" [username]
(let [user (ebay.models.user/map->User {:username username})]
(cond
(not (ebay.services.sniper/exists? user)) {:status 404}
(ebay.services.sniper/delete user) {:status 200}))))
| true | (ns ebay.routes.users
(:require
[ebay.models.user]
[ebay.services.sniper]
[compojure.core :refer [defroutes GET POST PUT DELETE]]
[ring.util.http-response :refer [ok]]))
(defroutes users-routes
(POST "/users" [username password]
(let [user (ebay.models.user/map->User {:username username :password password})]
(cond
(ebay.services.sniper/invalid? user) {:status 406}
(ebay.services.sniper/exists? user) {:status 200 :body (str "/users/" username)}
(ebay.services.sniper/save user) {:status 201 :body (str "/users/" username)}
:else {:status 500})))
(PUT "/users/:username" [username password]
(let [user (ebay.models.user/map->User {:username username :password PI:PASSWORD:<PASSWORD>END_PI})]
(cond
(not (ebay.services.sniper/exists? user)) {:status 404}
(ebay.services.sniper/edit user) {:status 200}
:else {:status 406})))
(DELETE "/users/:username" [username]
(let [user (ebay.models.user/map->User {:username username})]
(cond
(not (ebay.services.sniper/exists? user)) {:status 404}
(ebay.services.sniper/delete user) {:status 200}))))
|
[
{
"context": "u/6/kXX0KSvoOLSFQ==\"))\n\n(def cipher-key (map int \"YELLOW SUBMARINE\"))\n\n(def nonce (repeat 8 0))\n\n(def plaintext (map",
"end": 296,
"score": 0.9990279078483582,
"start": 280,
"tag": "KEY",
"value": "YELLOW SUBMARINE"
}
] | test/set3/decrypt_ctr_test.clj | milapsheth/Crypto-Challenges | 3 | (ns set3.decrypt-ctr-test
(:require [clojure.test :refer :all]
[util
[aes :as aes]
[tools :as u]]))
(def ciphertext (u/base64-to-byte' "L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=="))
(def cipher-key (map int "YELLOW SUBMARINE"))
(def nonce (repeat 8 0))
(def plaintext (map int "Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby "))
(deftest decrypt-ctr-test
(testing "Failed to decrypt AES under CTR mode"
(is (= plaintext
(aes/decrypt ciphertext cipher-key :ctr nonce)))))
| 106571 | (ns set3.decrypt-ctr-test
(:require [clojure.test :refer :all]
[util
[aes :as aes]
[tools :as u]]))
(def ciphertext (u/base64-to-byte' "L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=="))
(def cipher-key (map int "<KEY>"))
(def nonce (repeat 8 0))
(def plaintext (map int "Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby "))
(deftest decrypt-ctr-test
(testing "Failed to decrypt AES under CTR mode"
(is (= plaintext
(aes/decrypt ciphertext cipher-key :ctr nonce)))))
| true | (ns set3.decrypt-ctr-test
(:require [clojure.test :refer :all]
[util
[aes :as aes]
[tools :as u]]))
(def ciphertext (u/base64-to-byte' "L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=="))
(def cipher-key (map int "PI:KEY:<KEY>END_PI"))
(def nonce (repeat 8 0))
(def plaintext (map int "Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby "))
(deftest decrypt-ctr-test
(testing "Failed to decrypt AES under CTR mode"
(is (= plaintext
(aes/decrypt ciphertext cipher-key :ctr nonce)))))
|
[
{
"context": " (Associative Destructuring)\n(def a-name {:first \"Toto\" :last \"Mookey\" :salutation \"Mr.\"})\n\n(println a-n",
"end": 322,
"score": 0.9997808933258057,
"start": 318,
"tag": "NAME",
"value": "Toto"
},
{
"context": " Destructuring)\n(def a-name {:first \"Toto\" :last \"Mookey\" :salutation \"Mr.\"})\n\n(println a-name)\n\n(let [{fn",
"end": 337,
"score": 0.9997863173484802,
"start": 331,
"tag": "NAME",
"value": "Mookey"
}
] | session/01_languages/05-dps-2.clj | DhavalDalal/destructuring-and-pattern-matching | 2 | ; (def a-list [1 2 3 4])
;
; (println a-list)
; Destructuring a list
; Tuple can be represented using a List
; (let [[first second] a-list]
; (println [first second]))
;
; (let [[first second & rest] a-list]
; (println [first second rest]))
; Destructuring a map (Associative Destructuring)
(def a-name {:first "Toto" :last "Mookey" :salutation "Mr."})
(println a-name)
(let [{fname :first lname :last} a-name]
(println fname lname))
| 1999 | ; (def a-list [1 2 3 4])
;
; (println a-list)
; Destructuring a list
; Tuple can be represented using a List
; (let [[first second] a-list]
; (println [first second]))
;
; (let [[first second & rest] a-list]
; (println [first second rest]))
; Destructuring a map (Associative Destructuring)
(def a-name {:first "<NAME>" :last "<NAME>" :salutation "Mr."})
(println a-name)
(let [{fname :first lname :last} a-name]
(println fname lname))
| true | ; (def a-list [1 2 3 4])
;
; (println a-list)
; Destructuring a list
; Tuple can be represented using a List
; (let [[first second] a-list]
; (println [first second]))
;
; (let [[first second & rest] a-list]
; (println [first second rest]))
; Destructuring a map (Associative Destructuring)
(def a-name {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :salutation "Mr."})
(println a-name)
(let [{fname :first lname :last} a-name]
(println fname lname))
|
[
{
"context": "ase-id})\n (when next-token {\"x-nano-next\" (str next-token)}))\n :scheme scheme\n :se",
"end": 7363,
"score": 0.5886834859848022,
"start": 7354,
"tag": "KEY",
"value": "nano-next"
},
{
"context": "c/transactor-trust.jks\"\n;; :trust-store-password \"transactor\"\n\n(defn trust-store\n []\n (let [trust-store (Key",
"end": 9111,
"score": 0.9993457794189453,
"start": 9101,
"tag": "PASSWORD",
"value": "transactor"
},
{
"context": "client.cacertsPassword\")\n \"changeit\") ;; the Java-defined default\n pem-filenam",
"end": 9576,
"score": 0.959730863571167,
"start": 9568,
"tag": "PASSWORD",
"value": "changeit"
}
] | datomic/client/conn_impl.clj | rnewman/datomic-clj-client | 0 | ;; Copyright (c) Cognitect, Inc.
;; All rights reserved.
;; 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 ^:skip-wiki datomic.client.conn-impl
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as string]
[clojure.core.async :as async :refer [take! chan <!! put! go <! >! >!! go-loop promise-chan timeout]]
[cognitect.transit :as transit]
[cognitect.http-client :as http]
[cognitect.hmac-authn :as authn]
[datomic.client.impl.types :as types])
(:import [com.cognitect.transit ReadHandler]
[datomic.client.impl BytesOutputStream ByteBufferInputStream]
java.io.IOException
[java.nio ByteBuffer]
[java.security KeyStore]
[java.security.cert X509Certificate CertificateFactory]))
(set! *warn-on-reflection* true)
(defn result-chan
"Returns a chan with a result already on it."
[result]
(doto (promise-chan)
(>!! result)))
(defn error-result
"If x is an error, return a promise channel with it, else nil."
[x]
(when (:cognitect.anomalies/category x)
(result-chan x)))
(defn ^ByteBufferInputStream bbuf->is [bbuf]
(ByteBufferInputStream. bbuf))
(def read-handlers
{"datom" (reify ReadHandler
(fromRep [_ v] (apply types/datom v)))})
(def write-handlers
{})
(defn marshal
"Encodes val as Transit data in msgpack. Returns a map with keys:
:bytes - a Java byte array of the marshalled data
:length - the length in bytes of the marshalled data.
Note that for efficiency's sake the byte array may be longer than
the returned length."
[m]
(let [stm (BytesOutputStream.)
w (transit/writer stm :msgpack {:handlers write-handlers})]
(transit/write w m)
{:bytes (.internalBuffer stm)
:length (.length stm)}))
(defn unmarshal
"Given a byte array containing a Transit value encoded using the specified
decoder type and return the unmarshaled value. Defaults to :msgpack."
([stm]
(unmarshal stm :msgpack))
([stm type]
(let [r (transit/reader stm type {:handlers read-handlers})
res (transit/read r)]
res)))
(defn norm-headers
"Given request headers map, return a new request headers map with all
headers keys lowercased."
[headers]
(reduce-kv
(fn [acc ^String k v]
(assoc acc (.toLowerCase k) v))
{} headers))
(defn unmarshal-response
"Given a Ring response unmarshal the ByteBuffer :body of the Ring response
using the decoding as specified by the :content-type of the response.
Returns a response map with updated :body."
[{:keys [headers body] :as http-resp}]
(if body
(let [{:strs [content-type]} (norm-headers headers)
;;_ (prn ::unmarshal-body headers)
stm (bbuf->is body)
res (condp = content-type
"application/transit+msgpack"
(unmarshal stm :msgpack)
"application/transit+json"
(unmarshal stm :json)
"application/edn"
(edn/read (java.io.PushbackReader. (io/reader stm)))
"text/plain"
(slurp stm)
{:cognitect.anomalies/category :cognitect.anomalies/fault
:cognitect.anomalies/message (str "Cannot unmarshal content-type " content-type)})]
(assoc http-resp :body res))
http-resp))
(declare send-http-request)
(defn advance-t
[state new-state]
(if (> (:t new-state) (:t state))
new-state
state))
(defn update-db-state [{:keys [db-id state] :as conn-impl} {:keys [dbs] :as resp}]
(when-let [{:keys [t next-t]} (first dbs)]
(when (and t next-t)
(swap! state advance-t {:t t :next-t next-t}))))
(defn throwable->anomaly
[^Throwable t]
{:cognitect.anomalies/category :cognitect.anomalies/fault
:cognitect.anomalies/message (.getMessage t)})
(defn- http-status->anom-cat
"Return the anomaly kw for an http status."
[status]
(cond
(= status 403) :cognitect.anomalies/forbidden
(= status 503) :cognitect.anomalies/busy
(= status 504) :cognitect.anomalies/unvailable
(<= 400 status 499) :cognitect.anomalies/incorrect
(<= 500 status 599) :cognitect.anomalies/fault))
(defn- http-client-kw->anom-cat
"Return the anomaly kw for a :cognitect.http-client error"
[code]
(case code
::http/timeout :cognitect.anomalies/interrupted
::http/throttled :cognitect.anomalies/busy
::http/connect-failed :cognitect.anomalies/unavailable
::http/resolve-failed :cognitect.anomalies/not-found
:cognitect.anomalies/fault))
(defn- http-status-anomaly
"Returns an error based on http status if possible, or nil. This should only be
attempted after checking for better error info in the body."
[{:keys [status body]}]
(when-let [cat (http-status->anom-cat status)]
{:cognitect.anomalies/category cat
:datomic.client/http-error body}))
(defn- http-client-anomaly
"Returns an anomaly based on cognitect.http-client ::http/error codes in the body,
else nil."
[http-res]
(when-let [http-client-kw (::http/error http-res)]
(merge {:cognitect.anomalies/category (http-client-kw->anom-cat http-client-kw)}
(when-let [^Throwable t (::http/throwable http-res)]
{:cognitect.anomalies/message (str (.getName (.getClass t)) ": " (.getMessage t))}))))
(defn- http-body-anomaly
"If http body represents an anomaly, return it, else nil."
[http-res]
(if (:cognitect.anomalies/category (:body http-res))
(:body http-res)
(http-client-anomaly http-res)))
(defn on-completed
[conn-impl client-req http-res]
(let [{:keys [status body] :as http-res} (unmarshal-response http-res)]
(or (http-body-anomaly http-res)
(http-status-anomaly http-res)
(do
(update-db-state conn-impl body)
body))))
(defn catalog-op?
[op]
(= "datomic.catalog" (namespace op)))
(defn qualified-op [op]
(if (catalog-op? op)
(format "%s/%s" (namespace op) (name op))
(str "datomic.client.protocol/" (name op))))
(defn client-req->http-req
"Given a conn-impl and a Datomic client request return a Ring request where the
:body is a ByteBuffer."
[{:keys [scheme host port database-id] :as conn-impl}
{:keys [length bytes op next-token]
:or {length 0
bytes (.getBytes "")}
:as client-req}]
;;(prn ::client-req->http-reg account-id db-name)
(let [content-type "application/transit+msgpack"
qualified-op (qualified-op op)]
{:headers (merge {"host" host
"content-type" content-type
"accept" content-type
"x-nano-op" qualified-op}
(when-not (catalog-op? op) {"x-nano-target" database-id})
(when next-token {"x-nano-next" (str next-token)}))
:scheme scheme
:server-name host
:server-port port
:request-method :post
:uri "/"
:op qualified-op
:body (ByteBuffer/wrap ^bytes bytes 0 length)
:content-length length
:content-type content-type}))
(defn sign-http-req
"Given a conn-impl and a Ring compliant request, return a signed request as
specified by the AWS Signature 4 signing algorithm."
[{:keys [access-key service region secret] :as cfg} http-req]
;;(prn ::sign-http-req cfg http-req)
(let [auth-info {:access-key access-key
:secret secret
:service service
:region region}
signed (authn/sign http-req auth-info)
;; ch (chan 1)
;; _ (authn/verify signed auth-info ch)
;; verified (<!! ch)
]
;;(prn ::sign-http-req#raw http-req)
;;(prn ::sign-http-req#signed signed)
;;(prn ::sign-http-req#verified verified)
signed))
(defn send-request
"Given a conn-impl and an SPI request send the corresponding HTTP
request."
[{:keys [http-client] :as conn-impl}
{:keys [length bytes]
:or {length 0
bytes (.getBytes "")}
:as client-req}
timeout]
(let [timeout (or timeout (:timeout conn-impl))
retc (chan 1)
req (client-req->http-req conn-impl client-req)
signed (sign-http-req conn-impl req)
c (chan)
post (cond-> signed
timeout (assoc ::http/timeout-msec timeout))]
(http/submit http-client post c)
(go
(let [resp (<! c)]
(put! retc (on-completed conn-impl client-req resp))))
retc))
;; :trust-store-path "datomic/transactor-trust.jks"
;; :trust-store-password "transactor"
(defn trust-store
[]
(let [trust-store (KeyStore/getInstance (KeyStore/getDefaultType))
cacerts-filename (-> (System/getProperty "java.home")
(str "/lib/security/cacerts")
(string/replace "/" java.io.File/separator))
cacerts-file (io/make-input-stream cacerts-filename {})
cacerts-pwd (or (System/getProperty "datomic.client.cacertsPassword")
"changeit") ;; the Java-defined default
pem-filename (io/resource "transactor-trust.pem")
pem-file (io/make-input-stream pem-filename {})
cert-factory (CertificateFactory/getInstance "X.509")
pem-cert (.generateCertificate cert-factory pem-file)]
(.load trust-store cacerts-file (.toCharArray cacerts-pwd))
(.setCertificateEntry trust-store "datomic-client" pem-cert)
trust-store))
(defonce http-client
(delay
(http/create
{:trust-store (trust-store)})))
(def ^:private DEFAULT_HTTPS_PORT 443)
(defn- parse-endpoint
[s]
(when s
(let [[_ host _ port] (re-find #"^([^:]+)(:(\d+)?)?$" s)
port (if port (Long/parseLong port) DEFAULT_HTTPS_PORT)]
(if (and host port)
{:scheme "https" :host host :port port}
(throw (IllegalArgumentException. (str "Not a valid endpoint " s)))))))
(defn create
"Returns a new conn-impl object given a config map with the following
required keys:
:region - the AWS region
:service - the service
:account-id - the Datomic Cloud account id or constant for Pro peer-server
:access-key - a Datomic Cloud account access-key value or constant for Pro peer-server
:secret - a Datomic Cloud account secret value or secret configured when starting Pro peer-server
"
[config]
(merge config
(parse-endpoint (:endpoint config))
{:http-client @http-client}))
(defn with-retry
"Call req-fn, a function that wraps some operation and reutrns
a channel. Uses backoff to decide whether and how much to
backoff. When no more backoffs, puts result on result-chan."
[req-fn result-chan backoff]
(go-loop [msec nil]
(when msec (<! (timeout msec)))
(let [result (<! (req-fn))]
(if-let [msec (backoff result)]
(recur msec)
(>! result-chan result))))
result-chan)
(defn create-backoff
"Returns a backoff function suitable for with-retry. Initial backoff of
start msecs, increasing by multiplicative factor so long as <= max."
[pred start max factor]
(let [a (atom (/ start factor))]
#(when (pred %)
(let [backoff (long (swap! a * factor))]
(when (<= backoff max)
backoff)))))
(defn queue-request
"Accepts a Datomic request map and enqueues it on the HTTP conn-impl, returning
a channel which delivers the response."
[conn-impl req]
(let [timeout (:timeout req)
marshaled (marshal (dissoc req :timeout))
marshaled (merge marshaled (select-keys req [:op :next-token]))
result-ch (promise-chan)]
(with-retry
#(send-request conn-impl marshaled timeout)
result-ch
(create-backoff #(= :cognitect.anomalies/busy (:cognitect.anomalies/category %))
100 200 2))))
| 24980 | ;; Copyright (c) Cognitect, Inc.
;; All rights reserved.
;; 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 ^:skip-wiki datomic.client.conn-impl
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as string]
[clojure.core.async :as async :refer [take! chan <!! put! go <! >! >!! go-loop promise-chan timeout]]
[cognitect.transit :as transit]
[cognitect.http-client :as http]
[cognitect.hmac-authn :as authn]
[datomic.client.impl.types :as types])
(:import [com.cognitect.transit ReadHandler]
[datomic.client.impl BytesOutputStream ByteBufferInputStream]
java.io.IOException
[java.nio ByteBuffer]
[java.security KeyStore]
[java.security.cert X509Certificate CertificateFactory]))
(set! *warn-on-reflection* true)
(defn result-chan
"Returns a chan with a result already on it."
[result]
(doto (promise-chan)
(>!! result)))
(defn error-result
"If x is an error, return a promise channel with it, else nil."
[x]
(when (:cognitect.anomalies/category x)
(result-chan x)))
(defn ^ByteBufferInputStream bbuf->is [bbuf]
(ByteBufferInputStream. bbuf))
(def read-handlers
{"datom" (reify ReadHandler
(fromRep [_ v] (apply types/datom v)))})
(def write-handlers
{})
(defn marshal
"Encodes val as Transit data in msgpack. Returns a map with keys:
:bytes - a Java byte array of the marshalled data
:length - the length in bytes of the marshalled data.
Note that for efficiency's sake the byte array may be longer than
the returned length."
[m]
(let [stm (BytesOutputStream.)
w (transit/writer stm :msgpack {:handlers write-handlers})]
(transit/write w m)
{:bytes (.internalBuffer stm)
:length (.length stm)}))
(defn unmarshal
"Given a byte array containing a Transit value encoded using the specified
decoder type and return the unmarshaled value. Defaults to :msgpack."
([stm]
(unmarshal stm :msgpack))
([stm type]
(let [r (transit/reader stm type {:handlers read-handlers})
res (transit/read r)]
res)))
(defn norm-headers
"Given request headers map, return a new request headers map with all
headers keys lowercased."
[headers]
(reduce-kv
(fn [acc ^String k v]
(assoc acc (.toLowerCase k) v))
{} headers))
(defn unmarshal-response
"Given a Ring response unmarshal the ByteBuffer :body of the Ring response
using the decoding as specified by the :content-type of the response.
Returns a response map with updated :body."
[{:keys [headers body] :as http-resp}]
(if body
(let [{:strs [content-type]} (norm-headers headers)
;;_ (prn ::unmarshal-body headers)
stm (bbuf->is body)
res (condp = content-type
"application/transit+msgpack"
(unmarshal stm :msgpack)
"application/transit+json"
(unmarshal stm :json)
"application/edn"
(edn/read (java.io.PushbackReader. (io/reader stm)))
"text/plain"
(slurp stm)
{:cognitect.anomalies/category :cognitect.anomalies/fault
:cognitect.anomalies/message (str "Cannot unmarshal content-type " content-type)})]
(assoc http-resp :body res))
http-resp))
(declare send-http-request)
(defn advance-t
[state new-state]
(if (> (:t new-state) (:t state))
new-state
state))
(defn update-db-state [{:keys [db-id state] :as conn-impl} {:keys [dbs] :as resp}]
(when-let [{:keys [t next-t]} (first dbs)]
(when (and t next-t)
(swap! state advance-t {:t t :next-t next-t}))))
(defn throwable->anomaly
[^Throwable t]
{:cognitect.anomalies/category :cognitect.anomalies/fault
:cognitect.anomalies/message (.getMessage t)})
(defn- http-status->anom-cat
"Return the anomaly kw for an http status."
[status]
(cond
(= status 403) :cognitect.anomalies/forbidden
(= status 503) :cognitect.anomalies/busy
(= status 504) :cognitect.anomalies/unvailable
(<= 400 status 499) :cognitect.anomalies/incorrect
(<= 500 status 599) :cognitect.anomalies/fault))
(defn- http-client-kw->anom-cat
"Return the anomaly kw for a :cognitect.http-client error"
[code]
(case code
::http/timeout :cognitect.anomalies/interrupted
::http/throttled :cognitect.anomalies/busy
::http/connect-failed :cognitect.anomalies/unavailable
::http/resolve-failed :cognitect.anomalies/not-found
:cognitect.anomalies/fault))
(defn- http-status-anomaly
"Returns an error based on http status if possible, or nil. This should only be
attempted after checking for better error info in the body."
[{:keys [status body]}]
(when-let [cat (http-status->anom-cat status)]
{:cognitect.anomalies/category cat
:datomic.client/http-error body}))
(defn- http-client-anomaly
"Returns an anomaly based on cognitect.http-client ::http/error codes in the body,
else nil."
[http-res]
(when-let [http-client-kw (::http/error http-res)]
(merge {:cognitect.anomalies/category (http-client-kw->anom-cat http-client-kw)}
(when-let [^Throwable t (::http/throwable http-res)]
{:cognitect.anomalies/message (str (.getName (.getClass t)) ": " (.getMessage t))}))))
(defn- http-body-anomaly
"If http body represents an anomaly, return it, else nil."
[http-res]
(if (:cognitect.anomalies/category (:body http-res))
(:body http-res)
(http-client-anomaly http-res)))
(defn on-completed
[conn-impl client-req http-res]
(let [{:keys [status body] :as http-res} (unmarshal-response http-res)]
(or (http-body-anomaly http-res)
(http-status-anomaly http-res)
(do
(update-db-state conn-impl body)
body))))
(defn catalog-op?
[op]
(= "datomic.catalog" (namespace op)))
(defn qualified-op [op]
(if (catalog-op? op)
(format "%s/%s" (namespace op) (name op))
(str "datomic.client.protocol/" (name op))))
(defn client-req->http-req
"Given a conn-impl and a Datomic client request return a Ring request where the
:body is a ByteBuffer."
[{:keys [scheme host port database-id] :as conn-impl}
{:keys [length bytes op next-token]
:or {length 0
bytes (.getBytes "")}
:as client-req}]
;;(prn ::client-req->http-reg account-id db-name)
(let [content-type "application/transit+msgpack"
qualified-op (qualified-op op)]
{:headers (merge {"host" host
"content-type" content-type
"accept" content-type
"x-nano-op" qualified-op}
(when-not (catalog-op? op) {"x-nano-target" database-id})
(when next-token {"x-<KEY>" (str next-token)}))
:scheme scheme
:server-name host
:server-port port
:request-method :post
:uri "/"
:op qualified-op
:body (ByteBuffer/wrap ^bytes bytes 0 length)
:content-length length
:content-type content-type}))
(defn sign-http-req
"Given a conn-impl and a Ring compliant request, return a signed request as
specified by the AWS Signature 4 signing algorithm."
[{:keys [access-key service region secret] :as cfg} http-req]
;;(prn ::sign-http-req cfg http-req)
(let [auth-info {:access-key access-key
:secret secret
:service service
:region region}
signed (authn/sign http-req auth-info)
;; ch (chan 1)
;; _ (authn/verify signed auth-info ch)
;; verified (<!! ch)
]
;;(prn ::sign-http-req#raw http-req)
;;(prn ::sign-http-req#signed signed)
;;(prn ::sign-http-req#verified verified)
signed))
(defn send-request
"Given a conn-impl and an SPI request send the corresponding HTTP
request."
[{:keys [http-client] :as conn-impl}
{:keys [length bytes]
:or {length 0
bytes (.getBytes "")}
:as client-req}
timeout]
(let [timeout (or timeout (:timeout conn-impl))
retc (chan 1)
req (client-req->http-req conn-impl client-req)
signed (sign-http-req conn-impl req)
c (chan)
post (cond-> signed
timeout (assoc ::http/timeout-msec timeout))]
(http/submit http-client post c)
(go
(let [resp (<! c)]
(put! retc (on-completed conn-impl client-req resp))))
retc))
;; :trust-store-path "datomic/transactor-trust.jks"
;; :trust-store-password "<PASSWORD>"
(defn trust-store
[]
(let [trust-store (KeyStore/getInstance (KeyStore/getDefaultType))
cacerts-filename (-> (System/getProperty "java.home")
(str "/lib/security/cacerts")
(string/replace "/" java.io.File/separator))
cacerts-file (io/make-input-stream cacerts-filename {})
cacerts-pwd (or (System/getProperty "datomic.client.cacertsPassword")
"<PASSWORD>") ;; the Java-defined default
pem-filename (io/resource "transactor-trust.pem")
pem-file (io/make-input-stream pem-filename {})
cert-factory (CertificateFactory/getInstance "X.509")
pem-cert (.generateCertificate cert-factory pem-file)]
(.load trust-store cacerts-file (.toCharArray cacerts-pwd))
(.setCertificateEntry trust-store "datomic-client" pem-cert)
trust-store))
(defonce http-client
(delay
(http/create
{:trust-store (trust-store)})))
(def ^:private DEFAULT_HTTPS_PORT 443)
(defn- parse-endpoint
[s]
(when s
(let [[_ host _ port] (re-find #"^([^:]+)(:(\d+)?)?$" s)
port (if port (Long/parseLong port) DEFAULT_HTTPS_PORT)]
(if (and host port)
{:scheme "https" :host host :port port}
(throw (IllegalArgumentException. (str "Not a valid endpoint " s)))))))
(defn create
"Returns a new conn-impl object given a config map with the following
required keys:
:region - the AWS region
:service - the service
:account-id - the Datomic Cloud account id or constant for Pro peer-server
:access-key - a Datomic Cloud account access-key value or constant for Pro peer-server
:secret - a Datomic Cloud account secret value or secret configured when starting Pro peer-server
"
[config]
(merge config
(parse-endpoint (:endpoint config))
{:http-client @http-client}))
(defn with-retry
"Call req-fn, a function that wraps some operation and reutrns
a channel. Uses backoff to decide whether and how much to
backoff. When no more backoffs, puts result on result-chan."
[req-fn result-chan backoff]
(go-loop [msec nil]
(when msec (<! (timeout msec)))
(let [result (<! (req-fn))]
(if-let [msec (backoff result)]
(recur msec)
(>! result-chan result))))
result-chan)
(defn create-backoff
"Returns a backoff function suitable for with-retry. Initial backoff of
start msecs, increasing by multiplicative factor so long as <= max."
[pred start max factor]
(let [a (atom (/ start factor))]
#(when (pred %)
(let [backoff (long (swap! a * factor))]
(when (<= backoff max)
backoff)))))
(defn queue-request
"Accepts a Datomic request map and enqueues it on the HTTP conn-impl, returning
a channel which delivers the response."
[conn-impl req]
(let [timeout (:timeout req)
marshaled (marshal (dissoc req :timeout))
marshaled (merge marshaled (select-keys req [:op :next-token]))
result-ch (promise-chan)]
(with-retry
#(send-request conn-impl marshaled timeout)
result-ch
(create-backoff #(= :cognitect.anomalies/busy (:cognitect.anomalies/category %))
100 200 2))))
| true | ;; Copyright (c) Cognitect, Inc.
;; All rights reserved.
;; 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 ^:skip-wiki datomic.client.conn-impl
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as string]
[clojure.core.async :as async :refer [take! chan <!! put! go <! >! >!! go-loop promise-chan timeout]]
[cognitect.transit :as transit]
[cognitect.http-client :as http]
[cognitect.hmac-authn :as authn]
[datomic.client.impl.types :as types])
(:import [com.cognitect.transit ReadHandler]
[datomic.client.impl BytesOutputStream ByteBufferInputStream]
java.io.IOException
[java.nio ByteBuffer]
[java.security KeyStore]
[java.security.cert X509Certificate CertificateFactory]))
(set! *warn-on-reflection* true)
(defn result-chan
"Returns a chan with a result already on it."
[result]
(doto (promise-chan)
(>!! result)))
(defn error-result
"If x is an error, return a promise channel with it, else nil."
[x]
(when (:cognitect.anomalies/category x)
(result-chan x)))
(defn ^ByteBufferInputStream bbuf->is [bbuf]
(ByteBufferInputStream. bbuf))
(def read-handlers
{"datom" (reify ReadHandler
(fromRep [_ v] (apply types/datom v)))})
(def write-handlers
{})
(defn marshal
"Encodes val as Transit data in msgpack. Returns a map with keys:
:bytes - a Java byte array of the marshalled data
:length - the length in bytes of the marshalled data.
Note that for efficiency's sake the byte array may be longer than
the returned length."
[m]
(let [stm (BytesOutputStream.)
w (transit/writer stm :msgpack {:handlers write-handlers})]
(transit/write w m)
{:bytes (.internalBuffer stm)
:length (.length stm)}))
(defn unmarshal
"Given a byte array containing a Transit value encoded using the specified
decoder type and return the unmarshaled value. Defaults to :msgpack."
([stm]
(unmarshal stm :msgpack))
([stm type]
(let [r (transit/reader stm type {:handlers read-handlers})
res (transit/read r)]
res)))
(defn norm-headers
"Given request headers map, return a new request headers map with all
headers keys lowercased."
[headers]
(reduce-kv
(fn [acc ^String k v]
(assoc acc (.toLowerCase k) v))
{} headers))
(defn unmarshal-response
"Given a Ring response unmarshal the ByteBuffer :body of the Ring response
using the decoding as specified by the :content-type of the response.
Returns a response map with updated :body."
[{:keys [headers body] :as http-resp}]
(if body
(let [{:strs [content-type]} (norm-headers headers)
;;_ (prn ::unmarshal-body headers)
stm (bbuf->is body)
res (condp = content-type
"application/transit+msgpack"
(unmarshal stm :msgpack)
"application/transit+json"
(unmarshal stm :json)
"application/edn"
(edn/read (java.io.PushbackReader. (io/reader stm)))
"text/plain"
(slurp stm)
{:cognitect.anomalies/category :cognitect.anomalies/fault
:cognitect.anomalies/message (str "Cannot unmarshal content-type " content-type)})]
(assoc http-resp :body res))
http-resp))
(declare send-http-request)
(defn advance-t
[state new-state]
(if (> (:t new-state) (:t state))
new-state
state))
(defn update-db-state [{:keys [db-id state] :as conn-impl} {:keys [dbs] :as resp}]
(when-let [{:keys [t next-t]} (first dbs)]
(when (and t next-t)
(swap! state advance-t {:t t :next-t next-t}))))
(defn throwable->anomaly
[^Throwable t]
{:cognitect.anomalies/category :cognitect.anomalies/fault
:cognitect.anomalies/message (.getMessage t)})
(defn- http-status->anom-cat
"Return the anomaly kw for an http status."
[status]
(cond
(= status 403) :cognitect.anomalies/forbidden
(= status 503) :cognitect.anomalies/busy
(= status 504) :cognitect.anomalies/unvailable
(<= 400 status 499) :cognitect.anomalies/incorrect
(<= 500 status 599) :cognitect.anomalies/fault))
(defn- http-client-kw->anom-cat
"Return the anomaly kw for a :cognitect.http-client error"
[code]
(case code
::http/timeout :cognitect.anomalies/interrupted
::http/throttled :cognitect.anomalies/busy
::http/connect-failed :cognitect.anomalies/unavailable
::http/resolve-failed :cognitect.anomalies/not-found
:cognitect.anomalies/fault))
(defn- http-status-anomaly
"Returns an error based on http status if possible, or nil. This should only be
attempted after checking for better error info in the body."
[{:keys [status body]}]
(when-let [cat (http-status->anom-cat status)]
{:cognitect.anomalies/category cat
:datomic.client/http-error body}))
(defn- http-client-anomaly
"Returns an anomaly based on cognitect.http-client ::http/error codes in the body,
else nil."
[http-res]
(when-let [http-client-kw (::http/error http-res)]
(merge {:cognitect.anomalies/category (http-client-kw->anom-cat http-client-kw)}
(when-let [^Throwable t (::http/throwable http-res)]
{:cognitect.anomalies/message (str (.getName (.getClass t)) ": " (.getMessage t))}))))
(defn- http-body-anomaly
"If http body represents an anomaly, return it, else nil."
[http-res]
(if (:cognitect.anomalies/category (:body http-res))
(:body http-res)
(http-client-anomaly http-res)))
(defn on-completed
[conn-impl client-req http-res]
(let [{:keys [status body] :as http-res} (unmarshal-response http-res)]
(or (http-body-anomaly http-res)
(http-status-anomaly http-res)
(do
(update-db-state conn-impl body)
body))))
(defn catalog-op?
[op]
(= "datomic.catalog" (namespace op)))
(defn qualified-op [op]
(if (catalog-op? op)
(format "%s/%s" (namespace op) (name op))
(str "datomic.client.protocol/" (name op))))
(defn client-req->http-req
"Given a conn-impl and a Datomic client request return a Ring request where the
:body is a ByteBuffer."
[{:keys [scheme host port database-id] :as conn-impl}
{:keys [length bytes op next-token]
:or {length 0
bytes (.getBytes "")}
:as client-req}]
;;(prn ::client-req->http-reg account-id db-name)
(let [content-type "application/transit+msgpack"
qualified-op (qualified-op op)]
{:headers (merge {"host" host
"content-type" content-type
"accept" content-type
"x-nano-op" qualified-op}
(when-not (catalog-op? op) {"x-nano-target" database-id})
(when next-token {"x-PI:KEY:<KEY>END_PI" (str next-token)}))
:scheme scheme
:server-name host
:server-port port
:request-method :post
:uri "/"
:op qualified-op
:body (ByteBuffer/wrap ^bytes bytes 0 length)
:content-length length
:content-type content-type}))
(defn sign-http-req
"Given a conn-impl and a Ring compliant request, return a signed request as
specified by the AWS Signature 4 signing algorithm."
[{:keys [access-key service region secret] :as cfg} http-req]
;;(prn ::sign-http-req cfg http-req)
(let [auth-info {:access-key access-key
:secret secret
:service service
:region region}
signed (authn/sign http-req auth-info)
;; ch (chan 1)
;; _ (authn/verify signed auth-info ch)
;; verified (<!! ch)
]
;;(prn ::sign-http-req#raw http-req)
;;(prn ::sign-http-req#signed signed)
;;(prn ::sign-http-req#verified verified)
signed))
(defn send-request
"Given a conn-impl and an SPI request send the corresponding HTTP
request."
[{:keys [http-client] :as conn-impl}
{:keys [length bytes]
:or {length 0
bytes (.getBytes "")}
:as client-req}
timeout]
(let [timeout (or timeout (:timeout conn-impl))
retc (chan 1)
req (client-req->http-req conn-impl client-req)
signed (sign-http-req conn-impl req)
c (chan)
post (cond-> signed
timeout (assoc ::http/timeout-msec timeout))]
(http/submit http-client post c)
(go
(let [resp (<! c)]
(put! retc (on-completed conn-impl client-req resp))))
retc))
;; :trust-store-path "datomic/transactor-trust.jks"
;; :trust-store-password "PI:PASSWORD:<PASSWORD>END_PI"
(defn trust-store
[]
(let [trust-store (KeyStore/getInstance (KeyStore/getDefaultType))
cacerts-filename (-> (System/getProperty "java.home")
(str "/lib/security/cacerts")
(string/replace "/" java.io.File/separator))
cacerts-file (io/make-input-stream cacerts-filename {})
cacerts-pwd (or (System/getProperty "datomic.client.cacertsPassword")
"PI:PASSWORD:<PASSWORD>END_PI") ;; the Java-defined default
pem-filename (io/resource "transactor-trust.pem")
pem-file (io/make-input-stream pem-filename {})
cert-factory (CertificateFactory/getInstance "X.509")
pem-cert (.generateCertificate cert-factory pem-file)]
(.load trust-store cacerts-file (.toCharArray cacerts-pwd))
(.setCertificateEntry trust-store "datomic-client" pem-cert)
trust-store))
(defonce http-client
(delay
(http/create
{:trust-store (trust-store)})))
(def ^:private DEFAULT_HTTPS_PORT 443)
(defn- parse-endpoint
[s]
(when s
(let [[_ host _ port] (re-find #"^([^:]+)(:(\d+)?)?$" s)
port (if port (Long/parseLong port) DEFAULT_HTTPS_PORT)]
(if (and host port)
{:scheme "https" :host host :port port}
(throw (IllegalArgumentException. (str "Not a valid endpoint " s)))))))
(defn create
"Returns a new conn-impl object given a config map with the following
required keys:
:region - the AWS region
:service - the service
:account-id - the Datomic Cloud account id or constant for Pro peer-server
:access-key - a Datomic Cloud account access-key value or constant for Pro peer-server
:secret - a Datomic Cloud account secret value or secret configured when starting Pro peer-server
"
[config]
(merge config
(parse-endpoint (:endpoint config))
{:http-client @http-client}))
(defn with-retry
"Call req-fn, a function that wraps some operation and reutrns
a channel. Uses backoff to decide whether and how much to
backoff. When no more backoffs, puts result on result-chan."
[req-fn result-chan backoff]
(go-loop [msec nil]
(when msec (<! (timeout msec)))
(let [result (<! (req-fn))]
(if-let [msec (backoff result)]
(recur msec)
(>! result-chan result))))
result-chan)
(defn create-backoff
"Returns a backoff function suitable for with-retry. Initial backoff of
start msecs, increasing by multiplicative factor so long as <= max."
[pred start max factor]
(let [a (atom (/ start factor))]
#(when (pred %)
(let [backoff (long (swap! a * factor))]
(when (<= backoff max)
backoff)))))
(defn queue-request
"Accepts a Datomic request map and enqueues it on the HTTP conn-impl, returning
a channel which delivers the response."
[conn-impl req]
(let [timeout (:timeout req)
marshaled (marshal (dissoc req :timeout))
marshaled (merge marshaled (select-keys req [:op :next-token]))
result-ch (promise-chan)]
(with-retry
#(send-request conn-impl marshaled timeout)
result-ch
(create-backoff #(= :cognitect.anomalies/busy (:cognitect.anomalies/category %))
100 200 2))))
|
[
{
"context": "in-path (create-host-facts \"foo.com\" {\"password\" \"bar\"}))\n anon-output (tu/temp-file \"anon-fac",
"end": 599,
"score": 0.9990676641464233,
"start": 596,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": "in-path (create-host-facts \"foo.com\" {\"password\" \"foo\"\n ",
"end": 1090,
"score": 0.9987595081329346,
"start": 1087,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": "oo.com.json\" \"values\" k]))\n \"password\" \"foo\"\n \"reallysecret\" \"bar\"\n \"tota",
"end": 1752,
"score": 0.9984810948371887,
"start": 1749,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": "in-path (create-host-facts \"foo.com\" {\"password\" \"foo\"}))\n anon-output (tu/temp-file \"anon-fac",
"end": 2444,
"score": 0.9990900158882141,
"start": 2441,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": "oo.com.json\" \"values\" k]))\n \"password\" \"foo\"\n \"id\" \"foo\"\n \"ipaddress_lo0\"",
"end": 2927,
"score": 0.9993563294410706,
"start": 2924,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": " \"id\" \"foo\"\n \"ipaddress_lo0\" \"127.0.0.1\"\n \"operatingsystem\" \"Debian\")\n\n (i",
"end": 2988,
"score": 0.9977852702140808,
"start": 2979,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "in-path (create-host-facts \"foo.com\" {\"password\" \"foo\"}))\n anon-output (tu/temp-file \"anon-fac",
"end": 3742,
"score": 0.9995051622390747,
"start": 3739,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": " orig-facts [\"values\" k]))\n \"password\" \"foo\"\n \"id\" \"foo\"\n \"ipaddress_lo0\"",
"end": 4199,
"score": 0.9994297623634338,
"start": 4196,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": " \"id\" \"foo\"\n \"ipaddress_lo0\" \"127.0.0.1\"\n \"operatingsystem\" \"Debian\")\n\n (i",
"end": 4260,
"score": 0.9996054172515869,
"start": 4251,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | test/puppetlabs/puppetdb/cli/anonymize_test.clj | wkalt/puppetdb | 0 | (ns puppetlabs.puppetdb.cli.anonymize-test
(:require [clojure.test :refer :all]
[puppetlabs.puppetdb.cli.anonymize :refer :all]
[puppetlabs.puppetdb.testutils :as tu]
[clojure.string :as str]
[puppetlabs.puppetdb.testutils.tar :as tar]
[puppetlabs.puppetdb.testutils.facts :refer [spit-facts-tarball create-host-facts]]))
(deftest test-anonymize-facts
(testing "with profile none"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "bar"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "none")
orig-data (tar/tar->map in-path)
anon-data (tar/tar->map anon-output)]
(is (= (get orig-data "facts")
(get anon-data "facts")))))
(testing "with profile low"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "foo"
"reallysecret" "bar"
"totallyprivate" "baz"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "low")
orig-data (tar/tar->map in-path)
orig-facts (get-in orig-data ["facts" "foo.com.json"])
{host "certname" anon-env "environment" anon-facts "values"} (first (vals (get (tar/tar->map anon-output) "facts")))]
(are [k v] (= v (get-in orig-data ["facts" "foo.com.json" "values" k]))
"password" "foo"
"reallysecret" "bar"
"totallyprivate" "baz")
(is (not (str/blank? host)))
(is (not= host "foo.com"))
(is (contains? anon-facts "password"))
(is (contains? anon-facts "reallysecret"))
(is (contains? anon-facts "totallyprivate"))
(are [k] (not= (get orig-facts ["values" k]) (get anon-facts k))
"password"
"reallysecret"
"totallyprivate")
(is (= (get orig-facts "environment")
anon-env))))
(testing "with profile moderate"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "foo"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "moderate")
orig-data (tar/tar->map in-path)
orig-facts (get-in orig-data ["facts" "foo.com.json"])
{host "certname" anon-env "environment" anon-facts "values"} (first (vals (get (tar/tar->map anon-output) "facts")))]
(are [k v] (= v (get-in orig-data ["facts" "foo.com.json" "values" k]))
"password" "foo"
"id" "foo"
"ipaddress_lo0" "127.0.0.1"
"operatingsystem" "Debian")
(is (not (str/blank? host)))
(is (not= host "foo.com"))
(is (not (contains? anon-facts "password")))
(is (contains? anon-facts "id"))
(is (contains? anon-facts "operatingsystem"))
(are [op k] (op (get-in orig-facts ["values" k]) (get anon-facts k))
= "id"
not= "ipaddress_lo0"
= "operatingsystem")
(is (= (count (get orig-facts "values"))
(count anon-facts)))
(is (not= (get orig-data "environment")
anon-env))))
(testing "with profile full"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "foo"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "full")
orig-data (tar/tar->map in-path)
orig-facts (get-in orig-data ["facts" "foo.com.json"])
{host "certname" anon-env "environment" anon-facts "values"} (first (vals (get (tar/tar->map anon-output) "facts")))]
(are [k v] (= v (get-in orig-facts ["values" k]))
"password" "foo"
"id" "foo"
"ipaddress_lo0" "127.0.0.1"
"operatingsystem" "Debian")
(is (not-any? anon-facts (keys (get orig-facts "values"))))
(is (not-any? (set (vals anon-facts))
(vals (get orig-data "values"))))
(is (not= (get orig-data "environment")
anon-env)))))
| 116345 | (ns puppetlabs.puppetdb.cli.anonymize-test
(:require [clojure.test :refer :all]
[puppetlabs.puppetdb.cli.anonymize :refer :all]
[puppetlabs.puppetdb.testutils :as tu]
[clojure.string :as str]
[puppetlabs.puppetdb.testutils.tar :as tar]
[puppetlabs.puppetdb.testutils.facts :refer [spit-facts-tarball create-host-facts]]))
(deftest test-anonymize-facts
(testing "with profile none"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "<PASSWORD>"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "none")
orig-data (tar/tar->map in-path)
anon-data (tar/tar->map anon-output)]
(is (= (get orig-data "facts")
(get anon-data "facts")))))
(testing "with profile low"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "<PASSWORD>"
"reallysecret" "bar"
"totallyprivate" "baz"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "low")
orig-data (tar/tar->map in-path)
orig-facts (get-in orig-data ["facts" "foo.com.json"])
{host "certname" anon-env "environment" anon-facts "values"} (first (vals (get (tar/tar->map anon-output) "facts")))]
(are [k v] (= v (get-in orig-data ["facts" "foo.com.json" "values" k]))
"password" "<PASSWORD>"
"reallysecret" "bar"
"totallyprivate" "baz")
(is (not (str/blank? host)))
(is (not= host "foo.com"))
(is (contains? anon-facts "password"))
(is (contains? anon-facts "reallysecret"))
(is (contains? anon-facts "totallyprivate"))
(are [k] (not= (get orig-facts ["values" k]) (get anon-facts k))
"password"
"reallysecret"
"totallyprivate")
(is (= (get orig-facts "environment")
anon-env))))
(testing "with profile moderate"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "<PASSWORD>"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "moderate")
orig-data (tar/tar->map in-path)
orig-facts (get-in orig-data ["facts" "foo.com.json"])
{host "certname" anon-env "environment" anon-facts "values"} (first (vals (get (tar/tar->map anon-output) "facts")))]
(are [k v] (= v (get-in orig-data ["facts" "foo.com.json" "values" k]))
"password" "<PASSWORD>"
"id" "foo"
"ipaddress_lo0" "127.0.0.1"
"operatingsystem" "Debian")
(is (not (str/blank? host)))
(is (not= host "foo.com"))
(is (not (contains? anon-facts "password")))
(is (contains? anon-facts "id"))
(is (contains? anon-facts "operatingsystem"))
(are [op k] (op (get-in orig-facts ["values" k]) (get anon-facts k))
= "id"
not= "ipaddress_lo0"
= "operatingsystem")
(is (= (count (get orig-facts "values"))
(count anon-facts)))
(is (not= (get orig-data "environment")
anon-env))))
(testing "with profile full"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "<PASSWORD>"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "full")
orig-data (tar/tar->map in-path)
orig-facts (get-in orig-data ["facts" "foo.com.json"])
{host "certname" anon-env "environment" anon-facts "values"} (first (vals (get (tar/tar->map anon-output) "facts")))]
(are [k v] (= v (get-in orig-facts ["values" k]))
"password" "<PASSWORD>"
"id" "foo"
"ipaddress_lo0" "127.0.0.1"
"operatingsystem" "Debian")
(is (not-any? anon-facts (keys (get orig-facts "values"))))
(is (not-any? (set (vals anon-facts))
(vals (get orig-data "values"))))
(is (not= (get orig-data "environment")
anon-env)))))
| true | (ns puppetlabs.puppetdb.cli.anonymize-test
(:require [clojure.test :refer :all]
[puppetlabs.puppetdb.cli.anonymize :refer :all]
[puppetlabs.puppetdb.testutils :as tu]
[clojure.string :as str]
[puppetlabs.puppetdb.testutils.tar :as tar]
[puppetlabs.puppetdb.testutils.facts :refer [spit-facts-tarball create-host-facts]]))
(deftest test-anonymize-facts
(testing "with profile none"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "PI:PASSWORD:<PASSWORD>END_PI"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "none")
orig-data (tar/tar->map in-path)
anon-data (tar/tar->map anon-output)]
(is (= (get orig-data "facts")
(get anon-data "facts")))))
(testing "with profile low"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "PI:PASSWORD:<PASSWORD>END_PI"
"reallysecret" "bar"
"totallyprivate" "baz"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "low")
orig-data (tar/tar->map in-path)
orig-facts (get-in orig-data ["facts" "foo.com.json"])
{host "certname" anon-env "environment" anon-facts "values"} (first (vals (get (tar/tar->map anon-output) "facts")))]
(are [k v] (= v (get-in orig-data ["facts" "foo.com.json" "values" k]))
"password" "PI:PASSWORD:<PASSWORD>END_PI"
"reallysecret" "bar"
"totallyprivate" "baz")
(is (not (str/blank? host)))
(is (not= host "foo.com"))
(is (contains? anon-facts "password"))
(is (contains? anon-facts "reallysecret"))
(is (contains? anon-facts "totallyprivate"))
(are [k] (not= (get orig-facts ["values" k]) (get anon-facts k))
"password"
"reallysecret"
"totallyprivate")
(is (= (get orig-facts "environment")
anon-env))))
(testing "with profile moderate"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "PI:PASSWORD:<PASSWORD>END_PI"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "moderate")
orig-data (tar/tar->map in-path)
orig-facts (get-in orig-data ["facts" "foo.com.json"])
{host "certname" anon-env "environment" anon-facts "values"} (first (vals (get (tar/tar->map anon-output) "facts")))]
(are [k v] (= v (get-in orig-data ["facts" "foo.com.json" "values" k]))
"password" "PI:PASSWORD:<PASSWORD>END_PI"
"id" "foo"
"ipaddress_lo0" "127.0.0.1"
"operatingsystem" "Debian")
(is (not (str/blank? host)))
(is (not= host "foo.com"))
(is (not (contains? anon-facts "password")))
(is (contains? anon-facts "id"))
(is (contains? anon-facts "operatingsystem"))
(are [op k] (op (get-in orig-facts ["values" k]) (get anon-facts k))
= "id"
not= "ipaddress_lo0"
= "operatingsystem")
(is (= (count (get orig-facts "values"))
(count anon-facts)))
(is (not= (get orig-data "environment")
anon-env))))
(testing "with profile full"
(let [in-path (.getPath (tu/temp-file "input-facts" ".tar.gz"))
_ (spit-facts-tarball in-path (create-host-facts "foo.com" {"password" "PI:PASSWORD:<PASSWORD>END_PI"}))
anon-output (tu/temp-file "anon-facts" ".tar.gz")
_ (-main "-i" in-path "-o" (.getPath anon-output) "-p" "full")
orig-data (tar/tar->map in-path)
orig-facts (get-in orig-data ["facts" "foo.com.json"])
{host "certname" anon-env "environment" anon-facts "values"} (first (vals (get (tar/tar->map anon-output) "facts")))]
(are [k v] (= v (get-in orig-facts ["values" k]))
"password" "PI:PASSWORD:<PASSWORD>END_PI"
"id" "foo"
"ipaddress_lo0" "127.0.0.1"
"operatingsystem" "Debian")
(is (not-any? anon-facts (keys (get orig-facts "values"))))
(is (not-any? (set (vals anon-facts))
(vals (get orig-data "values"))))
(is (not= (get orig-data "environment")
anon-env)))))
|
[
{
"context": "encoding of natural numbers\n\n; Copyright (c) 2019 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu",
"end": 97,
"score": 0.9998618960380554,
"start": 83,
"tag": "NAME",
"value": "Burkhardt Renz"
},
{
"context": "tion of the predecessor combinator according to\n;; Sören Stenlund: Combinators, λ-Terms and Proof Theory Chap 3.2\n\n",
"end": 3035,
"score": 0.9988699555397034,
"start": 3021,
"tag": "NAME",
"value": "Sören Stenlund"
}
] | src/lwb/cl/examples/numerals.clj | esb-lwb/lwb | 22 | ; lwb Logic WorkBench -- Church encoding of natural numbers
; Copyright (c) 2019 Burkhardt Renz, THM. 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).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.cl.examples.numerals
(:require [lwb.cl :refer :all]))
(def-combinators-ski)
(def-combinator '[B a b c] '[a (b c)])
;; Definition of natural numbers ----------------------------------------------
;; We use the following encoding:
;; 0 = [K I]
;; 1 = [S B (K I)]
;; 2 = [S B (S B (K I))]
;; and so on
;; Zero
(def Zero '[K I])
;; Successor
(def Succ '[S B])
(defn succ
"The successor of the given numeral.
Pre: `term` is a numeral."
[term]
(comb-concat Succ term))
(defn Num
"Defines Church numeral for `i`."
[i]
(cond
(neg? i) nil
(>= i 0) (loop [current 0
result Zero]
(if (= current i)
result
(recur (inc current) (succ result))))))
(defn to-num
"The given term is transformed to numeral or nil if it's not a numeral."
[term]
(let [red (weak-reduce (conj term 'f 'x) {:limit 1000})
nof (count (filter #(= 'f %) (flatten red)))]
(when (= red (weak-reduce (conj (Num nof) 'f 'x)))
(list 'Num nof))))
(comment
(Num 0)
(Num 1)
(to-num '[I]) ; => (Num 1)
(Num 2)
(Num 7)
)
;; Definition of operators ----------------------------------------------------
;; Successor ------------------------------------------------------------------
;; see above
(comment
(to-num (succ (Num 4))) ; => (Num 5)
)
;; Predecessor ----------------------------------------------------------------
(def Pred* '[S (K (S I (K (K I))))
(S (S I (K (S (K (S (K (S (S I (K (K I))))) K))
(S (S (S I (K K)) (S I (K (K I))))
(S (K (S B)) (S I (K (K I))))))))
(K (S (S I (K K)) (K (K I)))))])
;; How to come up with such a term? Simple answer: Stack Exchange!!
;; see https://math.stackexchange.com/questions/1794537/can-all-computable-numeric-functions-on-church-numerals-in-ski-combinator-calcul
(comment
(time (weak-reduce (comb-concat Pred* (Num 0)))) ; => [K I] 2.7 secs
(time (weak-reduce (comb-concat Pred* (Num 0)) {:trace true})) ; => [K I] 2.7 secs 17 steps
(time (weak-reduce (comb-concat Pred* (Num 1)))) ; => [K I] 6.1 secs
(time (weak-reduce (comb-concat Pred* (Num 1)) {:trace true})) ; => [K I] 6.1 secs 47 steps
(time (weak-reduce (comb-concat Pred* (Num 2)) {:timeout 12000})) ; => [S B (K I)] 11.2 secs
;; extremely slow!!
)
;; A little bit of thinking may help to understands, what's going on here!
;; Here is how to deduce a predecessor term:
;; Derivation of the predecessor combinator according to
;; Sören Stenlund: Combinators, λ-Terms and Proof Theory Chap 3.2
;; D a paring combinator that detects (Num 0)
(def D (abstract '[x y z] '[z (K y) x]))
(comment
; D x y (Num 0) = x
(weak-reduce (comb-concat D '[x] '[y] (Num 0)))
; D x y (Num i) = y for i > 0
(weak-reduce (comb-concat D '[x] '[y] (Num 5)))
)
;; X_0
(def X_0 (abstract '[x] (comb-concat D '[S B (x (K I))] '[x (K I)])))
;; the predecessor combinator
(def Pred' (abstract '[y] (comb-concat '[y] X_0 '[K (K I)] (Num 1))))
(comment
(time (weak-reduce (comb-concat Pred' (Num 0)))) ; => [K I] 2.5 secs
(time (weak-reduce (comb-concat Pred' (Num 0)) {:trace true})) ; => [K I] 2.5 secs 8 steps
(time (weak-reduce (comb-concat Pred' (Num 1)) {:trace true})) ; => [K I] 210 secs 33 steps
(time (weak-reduce (comb-concat Pred' (Num 2)))) ; => [S B (K I)] 343 secs !!
)
;; The result of Pred' is a term that is literally equal to (Num i)
;; but we can use the derivation in another way - by defining improper combinators:
(def-combinator '[D x y z] '[z (K y) x])
(def-combinator '[X0 x] '[D (S B (x (K I))) (x (K I))])
(def Pred (abstract '[y] ['y 'X0 '(K (K I)) '(S B (K I))]))
; or
(def-combinator '[P n] '[n X0 (K (K I)) (S B (K I))])
(defn pred
"The predecessor of the given numeral."
[term]
(comb-concat '[P] term))
(defn pred'
[term]
(comb-concat Pred term))
(comment
(weak-reduce '[P (K I)]) ; => [K I]
(weak-reduce '[P (S B (K I))] {:trace true}) ; => [K I] 11 steps
(weak-reduce '[P (S B (S B (K I)))] {:trace true}) ; => [S B (K I)] 17 steps
(to-num (pred (Num 0)))
(weak-reduce (conj (pred (Num 1)) 'f 'x))
(weak-reduce (conj (pred (Num 1)) 'f 'x) {:trace true})
(weak-reduce (conj (pred (Num 4)) 'f 'x) {:trace true}) ; => 37 steps
(weak-reduce (conj (pred (Num 5)) 'f 'x) {:limit 1000 :trace true}) ; => [f (f (f (f x)))] 45 steps
(time (weak-reduce (conj (pred (Num 6)) 'f 'x) {:limit 1000 :trace true})) ; => 0.2 secs 53 steps
;; Interesting:
;; In the variant Pred* or Pred' we get not many steps, but huge terms
;; In the variant with the improper combinators, we get a lot of steps
;; - first increasing size of terms and then a fast reduction in the size of the terms
(to-num (pred (Num 1)))
(to-num (pred (Num 2)))
(to-num (pred (Num 3)))
(to-num (pred (Num 4)))
(time (to-num (pred (Num 4)))) ; => (Num 3) 0.03 secs
(time (to-num (pred (Num 5)))) ; => (Num 4) 0.05 secs
(to-num (pred' (Num 1)))
(to-num (pred' (Num 2)))
(to-num (pred' (Num 3)))
(to-num (pred' (Num 4)))
(time (to-num (pred' (Num 4)))) ; => (Num 3) 0.3 secs
(time (to-num (pred' (Num 5)))) ; => (Num 4) 0.6 secs
)
;; Addition -------------------------------------------------------------------
(def Add* '[S I (K (S B))])
(def Add '[B S (B B)])
(defn add
"Adds two numerals."
[term1 term2]
(comb-concat Add term1 term2))
(comment
;; The following examples show that
;; Add* gives an expression that reduces to the literal form of the numeral
;; Add is an expression does not reduce to the literal form of the numeral,
;; Add is much faster!
(weak-reduce (comb-concat Add* (Num 0) (Num 2))) ; => [S B (S B (K I))]
(to-num (comb-concat Add* (Num 0) (Num 2))) ; => (Num 2)
; but
(weak-reduce (comb-concat Add (Num 0) (Num 2))) ; => [S (B B (K I)) (S B (S B (K I)))]
(to-num (comb-concat Add (Num 0) (Num 2))) ; => (Num 2)
(time (to-num (comb-concat Add* (Num 6) (Num 6)))) ; => 0.4 secs
(time (to-num (comb-concat Add* (Num 7) (Num 6)))) ; => 0.8 secs
(time (to-num (comb-concat Add (Num 6) (Num 6)))) ; => 0.2 secs
(time (to-num (comb-concat Add (Num 7) (Num 6)))) ; => 0.4 secs
(time (to-num (comb-concat Add (Num 7) (Num 7)))) ; => 0.7 secs
)
;; Multiplication -------------------------------------------------------------
(def Mult* '[S (S (K S) (S (K (S I)) (S (K K) (S I (K (S B)))))) (K (K (K I)))])
(def Mult '[B])
(defn mult
"Multiplies two numerals."
[term1 term2]
(comb-concat Mult term1 term2))
(comment
;; Observe how multiplication works
(weak-reduce (comb-concat Mult* (Num 2) (Num 3) '[f] '[x]) {:trace true}) ; 71 steps
(weak-reduce (comb-concat Mult (Num 2) (Num 3) '[f] '[x]) {:trace true}) ; 23 steps
)
(comment
;; The following examples show that
;; Mult* gives an expression that reduces to the literal form of the numeral
;; Mult is an expression does not reduce to the literal form of the numeral,
;; Mult is much faster!
(weak-reduce (comb-concat Mult* '[S B (K I)] '[S B (K I)])) ; => [S B (K I)]
(to-num (comb-concat Mult* '[S B (K I)] '[S B (K I)])) ; => (Num 1)
; but
(weak-reduce (comb-concat Mult '[S B (K I)] '[S B (K I)])) ; => [B (S B (K I)) (S B (K I))]
(to-num (comb-concat Mult '[S B (K I)] '[S B (K I)])) ; => (Num 1)
(weak-reduce (comb-concat Mult* '[K I] '[K I])) ; => [K I]
(to-num (comb-concat Mult* '[K I] '[K I])) ; => (Num 0)
; but
(weak-reduce (comb-concat Mult '[K I] '[K I])) ; => [ B (K I) (K I)]
(to-num (comb-concat Mult '[K I] '[K I])) ; => (Num 0)
(weak-reduce (comb-concat Mult* (Num 2) (Num 3))) ; => [S B (S B (S B (S B (S B (S B (K I))))))]
(time (to-num (comb-concat Mult* (Num 2) (Num 3)))) ; => (Num 6) 204 msecs - slow
; but
(weak-reduce (comb-concat Mult (Num 2) (Num 3))) ; => [B (S B (S B (K I))) (S B (S B (S B (K I))))]
(time (to-num (comb-concat Mult (Num 2) (Num 3)))) ; => (Num 6) 17 msecs - fast
)
(comment
(to-num (mult (Num 0) (Num 2)))
(to-num (mult (Num 2) (Num 2)))
(to-num (mult (Num 2) (Num 3)))
(to-num (mult (Num 2) (Num 6)))
(time (to-num (mult (Num 2) (Num 7)))) ; => 1.2 secs
(time (to-num (mult (Num 2) (Num 8)))) ; => 3.3 secs
(time (to-num (mult (Num 2) (Num 9)))) ; => 11.7 secs
(time (to-num (mult (Num 2) (Num 10)))) ; => 47.7 secs
)
| 21758 | ; lwb Logic WorkBench -- Church encoding of natural numbers
; Copyright (c) 2019 <NAME>, THM. 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).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.cl.examples.numerals
(:require [lwb.cl :refer :all]))
(def-combinators-ski)
(def-combinator '[B a b c] '[a (b c)])
;; Definition of natural numbers ----------------------------------------------
;; We use the following encoding:
;; 0 = [K I]
;; 1 = [S B (K I)]
;; 2 = [S B (S B (K I))]
;; and so on
;; Zero
(def Zero '[K I])
;; Successor
(def Succ '[S B])
(defn succ
"The successor of the given numeral.
Pre: `term` is a numeral."
[term]
(comb-concat Succ term))
(defn Num
"Defines Church numeral for `i`."
[i]
(cond
(neg? i) nil
(>= i 0) (loop [current 0
result Zero]
(if (= current i)
result
(recur (inc current) (succ result))))))
(defn to-num
"The given term is transformed to numeral or nil if it's not a numeral."
[term]
(let [red (weak-reduce (conj term 'f 'x) {:limit 1000})
nof (count (filter #(= 'f %) (flatten red)))]
(when (= red (weak-reduce (conj (Num nof) 'f 'x)))
(list 'Num nof))))
(comment
(Num 0)
(Num 1)
(to-num '[I]) ; => (Num 1)
(Num 2)
(Num 7)
)
;; Definition of operators ----------------------------------------------------
;; Successor ------------------------------------------------------------------
;; see above
(comment
(to-num (succ (Num 4))) ; => (Num 5)
)
;; Predecessor ----------------------------------------------------------------
(def Pred* '[S (K (S I (K (K I))))
(S (S I (K (S (K (S (K (S (S I (K (K I))))) K))
(S (S (S I (K K)) (S I (K (K I))))
(S (K (S B)) (S I (K (K I))))))))
(K (S (S I (K K)) (K (K I)))))])
;; How to come up with such a term? Simple answer: Stack Exchange!!
;; see https://math.stackexchange.com/questions/1794537/can-all-computable-numeric-functions-on-church-numerals-in-ski-combinator-calcul
(comment
(time (weak-reduce (comb-concat Pred* (Num 0)))) ; => [K I] 2.7 secs
(time (weak-reduce (comb-concat Pred* (Num 0)) {:trace true})) ; => [K I] 2.7 secs 17 steps
(time (weak-reduce (comb-concat Pred* (Num 1)))) ; => [K I] 6.1 secs
(time (weak-reduce (comb-concat Pred* (Num 1)) {:trace true})) ; => [K I] 6.1 secs 47 steps
(time (weak-reduce (comb-concat Pred* (Num 2)) {:timeout 12000})) ; => [S B (K I)] 11.2 secs
;; extremely slow!!
)
;; A little bit of thinking may help to understands, what's going on here!
;; Here is how to deduce a predecessor term:
;; Derivation of the predecessor combinator according to
;; <NAME>: Combinators, λ-Terms and Proof Theory Chap 3.2
;; D a paring combinator that detects (Num 0)
(def D (abstract '[x y z] '[z (K y) x]))
(comment
; D x y (Num 0) = x
(weak-reduce (comb-concat D '[x] '[y] (Num 0)))
; D x y (Num i) = y for i > 0
(weak-reduce (comb-concat D '[x] '[y] (Num 5)))
)
;; X_0
(def X_0 (abstract '[x] (comb-concat D '[S B (x (K I))] '[x (K I)])))
;; the predecessor combinator
(def Pred' (abstract '[y] (comb-concat '[y] X_0 '[K (K I)] (Num 1))))
(comment
(time (weak-reduce (comb-concat Pred' (Num 0)))) ; => [K I] 2.5 secs
(time (weak-reduce (comb-concat Pred' (Num 0)) {:trace true})) ; => [K I] 2.5 secs 8 steps
(time (weak-reduce (comb-concat Pred' (Num 1)) {:trace true})) ; => [K I] 210 secs 33 steps
(time (weak-reduce (comb-concat Pred' (Num 2)))) ; => [S B (K I)] 343 secs !!
)
;; The result of Pred' is a term that is literally equal to (Num i)
;; but we can use the derivation in another way - by defining improper combinators:
(def-combinator '[D x y z] '[z (K y) x])
(def-combinator '[X0 x] '[D (S B (x (K I))) (x (K I))])
(def Pred (abstract '[y] ['y 'X0 '(K (K I)) '(S B (K I))]))
; or
(def-combinator '[P n] '[n X0 (K (K I)) (S B (K I))])
(defn pred
"The predecessor of the given numeral."
[term]
(comb-concat '[P] term))
(defn pred'
[term]
(comb-concat Pred term))
(comment
(weak-reduce '[P (K I)]) ; => [K I]
(weak-reduce '[P (S B (K I))] {:trace true}) ; => [K I] 11 steps
(weak-reduce '[P (S B (S B (K I)))] {:trace true}) ; => [S B (K I)] 17 steps
(to-num (pred (Num 0)))
(weak-reduce (conj (pred (Num 1)) 'f 'x))
(weak-reduce (conj (pred (Num 1)) 'f 'x) {:trace true})
(weak-reduce (conj (pred (Num 4)) 'f 'x) {:trace true}) ; => 37 steps
(weak-reduce (conj (pred (Num 5)) 'f 'x) {:limit 1000 :trace true}) ; => [f (f (f (f x)))] 45 steps
(time (weak-reduce (conj (pred (Num 6)) 'f 'x) {:limit 1000 :trace true})) ; => 0.2 secs 53 steps
;; Interesting:
;; In the variant Pred* or Pred' we get not many steps, but huge terms
;; In the variant with the improper combinators, we get a lot of steps
;; - first increasing size of terms and then a fast reduction in the size of the terms
(to-num (pred (Num 1)))
(to-num (pred (Num 2)))
(to-num (pred (Num 3)))
(to-num (pred (Num 4)))
(time (to-num (pred (Num 4)))) ; => (Num 3) 0.03 secs
(time (to-num (pred (Num 5)))) ; => (Num 4) 0.05 secs
(to-num (pred' (Num 1)))
(to-num (pred' (Num 2)))
(to-num (pred' (Num 3)))
(to-num (pred' (Num 4)))
(time (to-num (pred' (Num 4)))) ; => (Num 3) 0.3 secs
(time (to-num (pred' (Num 5)))) ; => (Num 4) 0.6 secs
)
;; Addition -------------------------------------------------------------------
(def Add* '[S I (K (S B))])
(def Add '[B S (B B)])
(defn add
"Adds two numerals."
[term1 term2]
(comb-concat Add term1 term2))
(comment
;; The following examples show that
;; Add* gives an expression that reduces to the literal form of the numeral
;; Add is an expression does not reduce to the literal form of the numeral,
;; Add is much faster!
(weak-reduce (comb-concat Add* (Num 0) (Num 2))) ; => [S B (S B (K I))]
(to-num (comb-concat Add* (Num 0) (Num 2))) ; => (Num 2)
; but
(weak-reduce (comb-concat Add (Num 0) (Num 2))) ; => [S (B B (K I)) (S B (S B (K I)))]
(to-num (comb-concat Add (Num 0) (Num 2))) ; => (Num 2)
(time (to-num (comb-concat Add* (Num 6) (Num 6)))) ; => 0.4 secs
(time (to-num (comb-concat Add* (Num 7) (Num 6)))) ; => 0.8 secs
(time (to-num (comb-concat Add (Num 6) (Num 6)))) ; => 0.2 secs
(time (to-num (comb-concat Add (Num 7) (Num 6)))) ; => 0.4 secs
(time (to-num (comb-concat Add (Num 7) (Num 7)))) ; => 0.7 secs
)
;; Multiplication -------------------------------------------------------------
(def Mult* '[S (S (K S) (S (K (S I)) (S (K K) (S I (K (S B)))))) (K (K (K I)))])
(def Mult '[B])
(defn mult
"Multiplies two numerals."
[term1 term2]
(comb-concat Mult term1 term2))
(comment
;; Observe how multiplication works
(weak-reduce (comb-concat Mult* (Num 2) (Num 3) '[f] '[x]) {:trace true}) ; 71 steps
(weak-reduce (comb-concat Mult (Num 2) (Num 3) '[f] '[x]) {:trace true}) ; 23 steps
)
(comment
;; The following examples show that
;; Mult* gives an expression that reduces to the literal form of the numeral
;; Mult is an expression does not reduce to the literal form of the numeral,
;; Mult is much faster!
(weak-reduce (comb-concat Mult* '[S B (K I)] '[S B (K I)])) ; => [S B (K I)]
(to-num (comb-concat Mult* '[S B (K I)] '[S B (K I)])) ; => (Num 1)
; but
(weak-reduce (comb-concat Mult '[S B (K I)] '[S B (K I)])) ; => [B (S B (K I)) (S B (K I))]
(to-num (comb-concat Mult '[S B (K I)] '[S B (K I)])) ; => (Num 1)
(weak-reduce (comb-concat Mult* '[K I] '[K I])) ; => [K I]
(to-num (comb-concat Mult* '[K I] '[K I])) ; => (Num 0)
; but
(weak-reduce (comb-concat Mult '[K I] '[K I])) ; => [ B (K I) (K I)]
(to-num (comb-concat Mult '[K I] '[K I])) ; => (Num 0)
(weak-reduce (comb-concat Mult* (Num 2) (Num 3))) ; => [S B (S B (S B (S B (S B (S B (K I))))))]
(time (to-num (comb-concat Mult* (Num 2) (Num 3)))) ; => (Num 6) 204 msecs - slow
; but
(weak-reduce (comb-concat Mult (Num 2) (Num 3))) ; => [B (S B (S B (K I))) (S B (S B (S B (K I))))]
(time (to-num (comb-concat Mult (Num 2) (Num 3)))) ; => (Num 6) 17 msecs - fast
)
(comment
(to-num (mult (Num 0) (Num 2)))
(to-num (mult (Num 2) (Num 2)))
(to-num (mult (Num 2) (Num 3)))
(to-num (mult (Num 2) (Num 6)))
(time (to-num (mult (Num 2) (Num 7)))) ; => 1.2 secs
(time (to-num (mult (Num 2) (Num 8)))) ; => 3.3 secs
(time (to-num (mult (Num 2) (Num 9)))) ; => 11.7 secs
(time (to-num (mult (Num 2) (Num 10)))) ; => 47.7 secs
)
| true | ; lwb Logic WorkBench -- Church encoding of natural numbers
; Copyright (c) 2019 PI:NAME:<NAME>END_PI, THM. 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).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.cl.examples.numerals
(:require [lwb.cl :refer :all]))
(def-combinators-ski)
(def-combinator '[B a b c] '[a (b c)])
;; Definition of natural numbers ----------------------------------------------
;; We use the following encoding:
;; 0 = [K I]
;; 1 = [S B (K I)]
;; 2 = [S B (S B (K I))]
;; and so on
;; Zero
(def Zero '[K I])
;; Successor
(def Succ '[S B])
(defn succ
"The successor of the given numeral.
Pre: `term` is a numeral."
[term]
(comb-concat Succ term))
(defn Num
"Defines Church numeral for `i`."
[i]
(cond
(neg? i) nil
(>= i 0) (loop [current 0
result Zero]
(if (= current i)
result
(recur (inc current) (succ result))))))
(defn to-num
"The given term is transformed to numeral or nil if it's not a numeral."
[term]
(let [red (weak-reduce (conj term 'f 'x) {:limit 1000})
nof (count (filter #(= 'f %) (flatten red)))]
(when (= red (weak-reduce (conj (Num nof) 'f 'x)))
(list 'Num nof))))
(comment
(Num 0)
(Num 1)
(to-num '[I]) ; => (Num 1)
(Num 2)
(Num 7)
)
;; Definition of operators ----------------------------------------------------
;; Successor ------------------------------------------------------------------
;; see above
(comment
(to-num (succ (Num 4))) ; => (Num 5)
)
;; Predecessor ----------------------------------------------------------------
(def Pred* '[S (K (S I (K (K I))))
(S (S I (K (S (K (S (K (S (S I (K (K I))))) K))
(S (S (S I (K K)) (S I (K (K I))))
(S (K (S B)) (S I (K (K I))))))))
(K (S (S I (K K)) (K (K I)))))])
;; How to come up with such a term? Simple answer: Stack Exchange!!
;; see https://math.stackexchange.com/questions/1794537/can-all-computable-numeric-functions-on-church-numerals-in-ski-combinator-calcul
(comment
(time (weak-reduce (comb-concat Pred* (Num 0)))) ; => [K I] 2.7 secs
(time (weak-reduce (comb-concat Pred* (Num 0)) {:trace true})) ; => [K I] 2.7 secs 17 steps
(time (weak-reduce (comb-concat Pred* (Num 1)))) ; => [K I] 6.1 secs
(time (weak-reduce (comb-concat Pred* (Num 1)) {:trace true})) ; => [K I] 6.1 secs 47 steps
(time (weak-reduce (comb-concat Pred* (Num 2)) {:timeout 12000})) ; => [S B (K I)] 11.2 secs
;; extremely slow!!
)
;; A little bit of thinking may help to understands, what's going on here!
;; Here is how to deduce a predecessor term:
;; Derivation of the predecessor combinator according to
;; PI:NAME:<NAME>END_PI: Combinators, λ-Terms and Proof Theory Chap 3.2
;; D a paring combinator that detects (Num 0)
(def D (abstract '[x y z] '[z (K y) x]))
(comment
; D x y (Num 0) = x
(weak-reduce (comb-concat D '[x] '[y] (Num 0)))
; D x y (Num i) = y for i > 0
(weak-reduce (comb-concat D '[x] '[y] (Num 5)))
)
;; X_0
(def X_0 (abstract '[x] (comb-concat D '[S B (x (K I))] '[x (K I)])))
;; the predecessor combinator
(def Pred' (abstract '[y] (comb-concat '[y] X_0 '[K (K I)] (Num 1))))
(comment
(time (weak-reduce (comb-concat Pred' (Num 0)))) ; => [K I] 2.5 secs
(time (weak-reduce (comb-concat Pred' (Num 0)) {:trace true})) ; => [K I] 2.5 secs 8 steps
(time (weak-reduce (comb-concat Pred' (Num 1)) {:trace true})) ; => [K I] 210 secs 33 steps
(time (weak-reduce (comb-concat Pred' (Num 2)))) ; => [S B (K I)] 343 secs !!
)
;; The result of Pred' is a term that is literally equal to (Num i)
;; but we can use the derivation in another way - by defining improper combinators:
(def-combinator '[D x y z] '[z (K y) x])
(def-combinator '[X0 x] '[D (S B (x (K I))) (x (K I))])
(def Pred (abstract '[y] ['y 'X0 '(K (K I)) '(S B (K I))]))
; or
(def-combinator '[P n] '[n X0 (K (K I)) (S B (K I))])
(defn pred
"The predecessor of the given numeral."
[term]
(comb-concat '[P] term))
(defn pred'
[term]
(comb-concat Pred term))
(comment
(weak-reduce '[P (K I)]) ; => [K I]
(weak-reduce '[P (S B (K I))] {:trace true}) ; => [K I] 11 steps
(weak-reduce '[P (S B (S B (K I)))] {:trace true}) ; => [S B (K I)] 17 steps
(to-num (pred (Num 0)))
(weak-reduce (conj (pred (Num 1)) 'f 'x))
(weak-reduce (conj (pred (Num 1)) 'f 'x) {:trace true})
(weak-reduce (conj (pred (Num 4)) 'f 'x) {:trace true}) ; => 37 steps
(weak-reduce (conj (pred (Num 5)) 'f 'x) {:limit 1000 :trace true}) ; => [f (f (f (f x)))] 45 steps
(time (weak-reduce (conj (pred (Num 6)) 'f 'x) {:limit 1000 :trace true})) ; => 0.2 secs 53 steps
;; Interesting:
;; In the variant Pred* or Pred' we get not many steps, but huge terms
;; In the variant with the improper combinators, we get a lot of steps
;; - first increasing size of terms and then a fast reduction in the size of the terms
(to-num (pred (Num 1)))
(to-num (pred (Num 2)))
(to-num (pred (Num 3)))
(to-num (pred (Num 4)))
(time (to-num (pred (Num 4)))) ; => (Num 3) 0.03 secs
(time (to-num (pred (Num 5)))) ; => (Num 4) 0.05 secs
(to-num (pred' (Num 1)))
(to-num (pred' (Num 2)))
(to-num (pred' (Num 3)))
(to-num (pred' (Num 4)))
(time (to-num (pred' (Num 4)))) ; => (Num 3) 0.3 secs
(time (to-num (pred' (Num 5)))) ; => (Num 4) 0.6 secs
)
;; Addition -------------------------------------------------------------------
(def Add* '[S I (K (S B))])
(def Add '[B S (B B)])
(defn add
"Adds two numerals."
[term1 term2]
(comb-concat Add term1 term2))
(comment
;; The following examples show that
;; Add* gives an expression that reduces to the literal form of the numeral
;; Add is an expression does not reduce to the literal form of the numeral,
;; Add is much faster!
(weak-reduce (comb-concat Add* (Num 0) (Num 2))) ; => [S B (S B (K I))]
(to-num (comb-concat Add* (Num 0) (Num 2))) ; => (Num 2)
; but
(weak-reduce (comb-concat Add (Num 0) (Num 2))) ; => [S (B B (K I)) (S B (S B (K I)))]
(to-num (comb-concat Add (Num 0) (Num 2))) ; => (Num 2)
(time (to-num (comb-concat Add* (Num 6) (Num 6)))) ; => 0.4 secs
(time (to-num (comb-concat Add* (Num 7) (Num 6)))) ; => 0.8 secs
(time (to-num (comb-concat Add (Num 6) (Num 6)))) ; => 0.2 secs
(time (to-num (comb-concat Add (Num 7) (Num 6)))) ; => 0.4 secs
(time (to-num (comb-concat Add (Num 7) (Num 7)))) ; => 0.7 secs
)
;; Multiplication -------------------------------------------------------------
(def Mult* '[S (S (K S) (S (K (S I)) (S (K K) (S I (K (S B)))))) (K (K (K I)))])
(def Mult '[B])
(defn mult
"Multiplies two numerals."
[term1 term2]
(comb-concat Mult term1 term2))
(comment
;; Observe how multiplication works
(weak-reduce (comb-concat Mult* (Num 2) (Num 3) '[f] '[x]) {:trace true}) ; 71 steps
(weak-reduce (comb-concat Mult (Num 2) (Num 3) '[f] '[x]) {:trace true}) ; 23 steps
)
(comment
;; The following examples show that
;; Mult* gives an expression that reduces to the literal form of the numeral
;; Mult is an expression does not reduce to the literal form of the numeral,
;; Mult is much faster!
(weak-reduce (comb-concat Mult* '[S B (K I)] '[S B (K I)])) ; => [S B (K I)]
(to-num (comb-concat Mult* '[S B (K I)] '[S B (K I)])) ; => (Num 1)
; but
(weak-reduce (comb-concat Mult '[S B (K I)] '[S B (K I)])) ; => [B (S B (K I)) (S B (K I))]
(to-num (comb-concat Mult '[S B (K I)] '[S B (K I)])) ; => (Num 1)
(weak-reduce (comb-concat Mult* '[K I] '[K I])) ; => [K I]
(to-num (comb-concat Mult* '[K I] '[K I])) ; => (Num 0)
; but
(weak-reduce (comb-concat Mult '[K I] '[K I])) ; => [ B (K I) (K I)]
(to-num (comb-concat Mult '[K I] '[K I])) ; => (Num 0)
(weak-reduce (comb-concat Mult* (Num 2) (Num 3))) ; => [S B (S B (S B (S B (S B (S B (K I))))))]
(time (to-num (comb-concat Mult* (Num 2) (Num 3)))) ; => (Num 6) 204 msecs - slow
; but
(weak-reduce (comb-concat Mult (Num 2) (Num 3))) ; => [B (S B (S B (K I))) (S B (S B (S B (K I))))]
(time (to-num (comb-concat Mult (Num 2) (Num 3)))) ; => (Num 6) 17 msecs - fast
)
(comment
(to-num (mult (Num 0) (Num 2)))
(to-num (mult (Num 2) (Num 2)))
(to-num (mult (Num 2) (Num 3)))
(to-num (mult (Num 2) (Num 6)))
(time (to-num (mult (Num 2) (Num 7)))) ; => 1.2 secs
(time (to-num (mult (Num 2) (Num 8)))) ; => 3.3 secs
(time (to-num (mult (Num 2) (Num 9)))) ; => 11.7 secs
(time (to-num (mult (Num 2) (Num 10)))) ; => 47.7 secs
)
|
[
{
"context": " :name \"1450 Denny's Favorite 50\"\n ",
"end": 18252,
"score": 0.853705883026123,
"start": 18247,
"tag": "NAME",
"value": "Denny"
},
{
"context": "is a mainstay of one of our local homebrewers, Mr. Denny Conn. It is unique in that it produces a big mouthfeel",
"end": 18851,
"score": 0.9979276657104492,
"start": 18841,
"tag": "NAME",
"value": "Denny Conn"
},
{
"context": " :name \"3068 Weihenstephan Weizen\"\n ",
"end": 37684,
"score": 0.9423889517784119,
"start": 37664,
"tag": "NAME",
"value": "Weihenstephan Weizen"
}
] | src/common_beer_format/data/yeasts/wyeast.cljc | Wall-Brew-Co/common-beer-format | 1 | (ns common-beer-format.data.yeasts.wyeast
"Data for yeasts cultivated by Wyeast"
(:require [common-beer-format.data.yeasts.yeasts :as yeasts]))
(def german-ale-1007
(yeasts/build-yeasts :german-ale-1007 {:min-temperature 12.78
:name "1007 German Ale"
:max-temperature 18.89
:type "Ale"
:best-for "German Ales, Alts, Kolsch, Dry Stout"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Crisp, dry finish with a mild flavor."
:flocculation "Low"
:form "Liquid"
:product-id "1007"}))
(def american-wheat-ale-1010
(yeasts/build-yeasts :american-wheat-ale-1010 {:min-temperature 14.44
:name "1010 American Wheat Ale"
:max-temperature 23.33
:type "Ale"
:best-for "American Wheat, Berlin Weiss, Hefeweizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry, Crisp, tart beer in the American Hefeweizen style. Low flocculation aids in producing desired chill haze."
:flocculation "Low"
:form "Liquid"
:product-id "1010"}))
(def british-cask-ale-1026
(yeasts/build-yeasts :british-cask-ale-1026 {:min-temperature 17.22
:name "1026 British Cask Ale"
:max-temperature 22.22
:type "Ale"
:best-for "British Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "A great choice for any cask conditioned British Ale. Produces nice malt profile with a hint of fruit. Finishes dry and slightly tart. "
:flocculation "Medium"
:form "Liquid"
:product-id "1026"}))
(def london-ale-yeast-1028
(yeasts/build-yeasts :london-ale-yeast-1028 {:min-temperature 15.56
:name "1028 London Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "English Ales, Bitters, IPAs, Brown Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry finish, bold, rich flavor, some fruit profile and a crisp finish."
:flocculation "Medium"
:form "Liquid"
:product-id "1028"}))
(def american-ale-1056
(yeasts/build-yeasts :american-ale-1056 {:min-temperature 15.56
:name "1056 American Ale"
:max-temperature 22.22
:type "Ale"
:best-for "American Pale Ale, Scottish Ale, Porters, Sweet Stout, Barley Wine, Alt"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Soft, smooth, clean finish. Very well balanced. Very versitile -- works well with many ale styles."
:flocculation "Medium"
:form "Liquid"
:product-id "1056"}))
(def irish-ale-1084
(yeasts/build-yeasts :irish-ale-1084 {:min-temperature 16.67
:name "1084 Irish Ale"
:max-temperature 22.22
:type "Ale"
:best-for "Irish Dry Stouts, Porter, Scottish Ale, Brown Ale, Imperial Stout, Barley Wine"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry diacetyl, fruity flavor characteristic of stouts. Full bodied, dry, clean flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "1084"}))
(def wyeast-ale-blend-1087
(yeasts/build-yeasts :wyeast-ale-blend-1087 {:min-temperature 17.78
:name "1087 Wyeast Ale Blend"
:max-temperature 22.22
:type "Ale"
:best-for "American and British Ale Styles."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Blend of ale strains designed to provide quick starts, good flavor, balance and flocculation. Balanced finish suitable for most American and British ale styles."
:flocculation "Medium"
:form "Liquid"
:product-id "1087"}))
(def british-ale-yeast-1098
(yeasts/build-yeasts :british-ale-yeast-1098 {:min-temperature 17.78
:name "1098 British Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "All British Ales, Pales, Bitters, English Strong Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Fruity, tart, dry crisp finish. Very well balanced."
:flocculation "Medium"
:form "Liquid"
:product-id "1098"}))
(def whitbread-ale-1099
(yeasts/build-yeasts :whitbread-ale-1099 {:min-temperature 17.78
:name "1099 Whitbread Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Whitbread Ale, British Ales, Pales, Bitters"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Slightly more fruity and malty than Wyeast's British Ale. Clear and highly flocculant."
:flocculation "High"
:form "Liquid"
:product-id "1099"}))
(def ringwood-ale-1187
(yeasts/build-yeasts :ringwood-ale-1187 {:min-temperature 17.78
:name "1187 Ringwood Ale"
:max-temperature 23.33
:type "Ale"
:best-for "Ringwood Ale, Brown Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "European ale yeast. Highly flocculant with complex, clear, but malty profile. Slightly fruity ester."
:flocculation "High"
:form "Liquid"
:product-id "1187"}))
(def belgian-ale-yeast-1214
(yeasts/build-yeasts :belgian-ale-yeast-1214 {:min-temperature 14.44
:name "1214 Belgian Ale Yeast"
:max-temperature 20.0
:type "Ale"
:best-for "Belgian Ales, Abbey Ales, Trappist Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Trappist style ale yeast. Complex estery flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "1214"}))
(def american-ale-ii-1272
(yeasts/build-yeasts :american-ale-ii-1272 {:min-temperature 15.56
:name "1272 American Ale II"
:max-temperature 22.22
:type "Ale"
:best-for "All American Ales, Brown Ales, Barley Wine"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Clean, tart, nutty flavor. More fruity than Wyeast American Ale yeast."
:flocculation "High"
:form "Liquid"
:product-id "1272"}))
(def gf-all-american-ale-1272
(yeasts/build-yeasts :gf-all-american-ale-1272 {:min-temperature 15.56
:name "1272 GF All American Ale"
:max-temperature 22.22
:type "Ale"
:best-for "American Amber, Brown, IPA, Pale ales and stouts. Blondes and fruit beers."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Popular all purpose American ale style now in a Gluten Free strain. Produces beers that are nutty, clean with a slight tart finish. Ferment warmer to accentuate hops and add fruitiness or ferment cold for clean light citrus character."
:flocculation "High"
:form "Liquid"
:product-id "1272"}))
(def thames-valley-ale-1275
(yeasts/build-yeasts :thames-valley-ale-1275 {:min-temperature 16.67
:name "1275 Thames Valley Ale"
:max-temperature 22.22
:type "Ale"
:best-for "British Bitters, ESB, India Pale Ale, English Strong Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Clean, complex flavor. Low in fruit, low in esters, rich in flavor. Hops come through well."
:flocculation "Medium"
:form "Liquid"
:product-id "1275"}))
(def london-ale-iii-1318
(yeasts/build-yeasts :london-ale-iii-1318 {:min-temperature 17.78
:name "1318 London Ale III"
:max-temperature 23.33
:type "Ale"
:best-for "British Ales, Bitters"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Light, fruity flavor. Balanced flavor with hint of sweetness."
:flocculation "High"
:form "Liquid"
:product-id "1318"}))
(def northwest-ale-1332
(yeasts/build-yeasts :northwest-ale-1332 {:min-temperature 18.33
:name "1332 Northwest Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Oregon Ales, All American Ale styles"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic Northwest US ale yeast. Slight fruit flavor, malty ale with good body and balance."
:flocculation "High"
:form "Liquid"
:product-id "1332"}))
(def british-ale-ii-1335
(yeasts/build-yeasts :british-ale-ii-1335 {:min-temperature 17.22
:name "1335 British Ale II"
:max-temperature 23.89
:type "Ale"
:best-for "British and Canadian Ales, English Bitters"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Malty, clean, crisp finish. Dry flavor."
:flocculation "High"
:form "Liquid"
:product-id "1335"}))
(def european-ale-yeast-1338
(yeasts/build-yeasts :european-ale-yeast-1338 {:min-temperature 16.67
:name "1338 European Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "European Ales, German Ales, Alts, Pale Ale, Brown Ale, Kolsch"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Very malty flavor characteristic of Bavarian/Munich Ales. Complex character."
:flocculation "High"
:form "Liquid"
:product-id "1338"}))
(def belgian-strong-ale-1388
(yeasts/build-yeasts :belgian-strong-ale-1388 {:min-temperature 18.33
:name "1388 Belgian Strong Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Ales, Scottish Strong Ale,Trappist Ales, Dubbels, Trippels"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry, tart, fruity flavor. High alcohol tolerance."
:flocculation "Low"
:form "Liquid"
:product-id "1388"}))
(def denny-s-favorite-50-1450
(yeasts/build-yeasts :denny-s-favorite-50-1450 {:min-temperature 15.56
:name "1450 Denny's Favorite 50"
:max-temperature 21.11
:type "Ale"
:best-for "almost any style"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This terrific all-round yeast can be used for almost any beer style, and is a mainstay of one of our local homebrewers, Mr. Denny Conn. It is unique in that it produces a big mouthfeel and accentuates the malt, caramel, or fruit character of a beer without being sweet or under-attenuated. "
:flocculation "Low"
:form "Liquid"
:product-id "1450"}))
(def scottish-ale-1728
(yeasts/build-yeasts :scottish-ale-1728 {:min-temperature 12.78
:name "1728 Scottish Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Scottish Ale, Scottish Strong Ales, Sweet Stout, Imperial Stout, Barley Wine"
:laboratory "Wyeast"
:attenuation 0.765
:notes "High alcohol tolerance."
:flocculation "High"
:form "Liquid"
:product-id "1728"}))
(def belgian-abbey-ii-1762
(yeasts/build-yeasts :belgian-abbey-ii-1762 {:min-temperature 18.33
:name "1762 Belgian Abbey II"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Ales, Trappist Ales, Abbey Ales, Grand Cru"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry flavor with slight fruitiness. High alcohol tolerance."
:flocculation "Medium"
:form "Liquid"
:product-id "1762"}))
(def london-esb-ale-1968
(yeasts/build-yeasts :london-esb-ale-1968 {:min-temperature 17.78
:name "1968 London ESB Ale"
:max-temperature 22.22
:type "Ale"
:best-for "English Bitters, IPA, Brown Ales, Mild Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Malty, balanced flavor. Fruity, rich finish. Excellent for cask conditioned ales and bitters."
:flocculation "High"
:form "Liquid"
:product-id "1968"}))
(def budvar-lager-2000
(yeasts/build-yeasts :budvar-lager-2000 {:min-temperature 7.78
:name "2000 Budvar Lager"
:max-temperature 13.33
:type "Lager"
:best-for "Bohemian Pilsner, Classic Pilsners, Dortmunder and Light Lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic pilsner lager yeast. Malty nose and subtle fruit. Rich malt profile, but dry crisp finish. Hop character accentuated by dry finish."
:flocculation "High"
:form "Liquid"
:product-id "2000"}))
(def urquell-lager-2001
(yeasts/build-yeasts :urquell-lager-2001 {:min-temperature 8.89
:name "2001 Urquell Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Bohemian Pilsner"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Pilsner Urquell yeast with mild fruit/floral aroma. Very dry and clean on palate with full mouth feel. Subtle malt character. Clean and neutral finish."
:flocculation "Medium"
:form "Liquid"
:product-id "2001"}))
(def pilsen-lager-2007
(yeasts/build-yeasts :pilsen-lager-2007 {:min-temperature 8.89
:name "2007 Pilsen Lager"
:max-temperature 13.33
:type "Lager"
:best-for "American Pilsner, Bohemian Pilsner, Light Lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic American pilsner strain. Smooth with a malty flavor. Dry and crisp fermentation."
:flocculation "Medium"
:form "Liquid"
:product-id "2007"}))
(def american-lager-2035
(yeasts/build-yeasts :american-lager-2035 {:min-temperature 8.89
:name "2035 American Lager"
:max-temperature 14.44
:type "Lager"
:best-for "American Lagers and Pilsners"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Bold, with a complex aroma. Good flavor depth characteristics for a wide variety of lager beers."
:flocculation "Medium"
:form "Liquid"
:product-id "2035"}))
(def danish-lager-2042
(yeasts/build-yeasts :danish-lager-2042 {:min-temperature 7.78
:name "2042 Danish Lager"
:max-temperature 13.33
:type "Lager"
:best-for "Dortmund/Export Lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Rich, Dortmund style, with a crisp, dry finish. Soft profile accentuates hop flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "2042"}))
(def california-lager-2112
(yeasts/build-yeasts :california-lager-2112 {:min-temperature 14.44
:name "2112 California Lager"
:max-temperature 20.0
:type "Lager"
:best-for "California common beers, Steam Beer"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Suited for 19th century California style beers. Lagers at high temperature and produces malty, clear beers."
:flocculation "High"
:form "Liquid"
:product-id "2112"}))
(def bohemian-lager-2124
(yeasts/build-yeasts :bohemian-lager-2124 {:min-temperature 8.89
:name "2124 Bohemian Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Bohemian Pilsners, Pilsners, German Helles, Bocks"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Ferments clean and malty, with rich malty flavor for full gravity pilsners."
:flocculation "Medium"
:form "Liquid"
:product-id "2124"}))
(def wyeast-lager-blend-2178
(yeasts/build-yeasts :wyeast-lager-blend-2178 {:min-temperature 8.89
:name "2178 Wyeast Lager Blend"
:max-temperature 14.44
:type "Lager"
:best-for "Classic Pilsners, Lagers, Bocks."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Blend of lager strains to produce a complex but clean lager flavor profile. Suitable for many common lager styles."
:flocculation "Medium"
:form "Liquid"
:product-id "2178"}))
(def bavarian-lager-2206
(yeasts/build-yeasts :bavarian-lager-2206 {:min-temperature 7.78
:name "2206 Bavarian Lager"
:max-temperature 14.44
:type "Lager"
:best-for "German Bocks, Vienna, Oktoberfest, Hells, Marzens, Dunkel"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Use by many German breweries. Produces a full-bodied, rich, malty beer."
:flocculation "Medium"
:form "Liquid"
:product-id "2206"}))
(def european-lager-ii-2247
(yeasts/build-yeasts :european-lager-ii-2247 {:min-temperature 7.78
:name "2247 European Lager II"
:max-temperature 13.33
:type "Lager"
:best-for "Bohemian Pilsner, American Pilsner, Helles, Dunkel"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Clean, dry flavor profile for aggressively hopped pilsners. Dry finish, mild aroma, slight sulfur production."
:flocculation "Low"
:form "Liquid"
:product-id "2247"}))
(def north-american-lager-2272
(yeasts/build-yeasts :north-american-lager-2272 {:min-temperature 8.89
:name "2272 North American Lager"
:max-temperature 13.33
:type "Lager"
:best-for "American Pilsner, California Common, Canadian Lager, Oktoberfest, Marzen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "American and Canadian lager yeast. Malty finish makes it suitable for Marzens/Oktoberfest as well."
:flocculation "High"
:form "Liquid"
:product-id "2272"}))
(def czech-pilsner-lager-2278
(yeasts/build-yeasts :czech-pilsner-lager-2278 {:min-temperature 10.0
:name "2278 Czech Pilsner Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Bohemian and American Pilsner, Bocks, Oktoberfest, Marzen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic Pilsner strain. Creates a dry but malty finish. Perfect for Pilsners and bocks. Some sulfur produced, but will fade with time."
:flocculation "Medium"
:form "Liquid"
:product-id "2278"}))
(def munich-lager-2308
(yeasts/build-yeasts :munich-lager-2308 {:min-temperature 8.89
:name "2308 Munich Lager"
:max-temperature 13.33
:type "Lager"
:best-for "Pilsners, Light Lagers, Dortmond/Export, Marzen/Oktoberfest, Dunkel"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Unique Pilsner strain. Very smooth, well-rounded and full bodied. Benefits from a diacetyl rest."
:flocculation "Medium"
:form "Liquid"
:product-id "2308"}))
(def kolsch-yeast-2565
(yeasts/build-yeasts :kolsch-yeast-2565 {:min-temperature 13.33
:name "2565 Kolsch Yeast"
:max-temperature 17.78
:type "Ale"
:best-for "Kolsch, European Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Very malty flavor with mix of lager and ale character. Crisp, clean finish."
:flocculation "Low"
:form "Liquid"
:product-id "2565"}))
(def octoberfest-lager-blend-2633
(yeasts/build-yeasts :octoberfest-lager-blend-2633 {:min-temperature 8.89
:name "2633 Octoberfest Lager Blend"
:max-temperature 14.44
:type "Lager"
:best-for "Octoberfest, Marzen, Bavarian lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This blend of lager strains is designed to produce a rich, malty, complex and full bodied Octoberfest style beer. It attenuates well while leaving plenty of malt character and mouthfeel. This strain is low in sulfur production. "
:flocculation "Low"
:form "Liquid"
:product-id "2633"}))
(def bavarian-wheat-yeast-3056
(yeasts/build-yeasts :bavarian-wheat-yeast-3056 {:min-temperature 17.78
:name "3056 Bavarian Wheat Yeast"
:max-temperature 23.33
:type "Wheat"
:best-for "Bavarian style wheat beers."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Blend of top-fermenting ale and wheat yeasts providing a mild ester and phenolic profile."
:flocculation "Medium"
:form "Liquid"
:product-id "3056"}))
(def weihenstephan-weizen-3068
(yeasts/build-yeasts :weihenstephan-weizen-3068 {:min-temperature 17.78
:name "3068 Weihenstephan Weizen"
:max-temperature 23.89
:type "Wheat"
:best-for "Bavarian Weizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Unique Bavarian wheat yeast that produces the spicy weizen clove and banana flavor. Best when fermented at around 68 deg F."
:flocculation "Low"
:form "Liquid"
:product-id "3068"}))
(def brettanomyces-bruxellensis-3112
(yeasts/build-yeasts :brettanomyces-bruxellensis-3112 {:min-temperature 15.56
:name "3112 Brettanomyces Bruxellensis"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Lambic, Gueze Lambic, and Sour Browns"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Wild yeast strain isolated from Brussels region of Belgium. Adds classic sweaty horse hair flavor as well as sourness and cherry-pie like flavor. Generally used in conjunction with S. Cerevisiae after the primary fermentation has begun. Requires 3-6 mo"
:flocculation "Medium"
:form "Liquid"
:product-id "3112"}))
(def belgian-lambic-blend-3278
(yeasts/build-yeasts :belgian-lambic-blend-3278 {:min-temperature 17.22
:name "3278 Belgian Lambic Blend"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Lambic"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lambic culture of Saccharomyces Cerevisiar and a mixture of yeasts and bacterias. Blend of organisms helps create lactic flavor of Belgian Lambics."
:flocculation "Low"
:form "Liquid"
:product-id "3278"}))
(def german-wheat-3333
(yeasts/build-yeasts :german-wheat-3333 {:min-temperature 17.22
:name "3333 German Wheat"
:max-temperature 23.89
:type "Wheat"
:best-for "Bavarian Weizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Subtle flavor profile. Sharp, fruity, crisp, sherry like flavor."
:flocculation "High"
:form "Liquid"
:product-id "3333"}))
(def forbidden-fruit-3463
(yeasts/build-yeasts :forbidden-fruit-3463 {:min-temperature 17.22
:name "3463 Forbidden Fruit"
:max-temperature 24.44
:type "Wheat"
:best-for "Belgian Wit, Grand Cru"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Phenolic profile with subdued fruitiness. Available seasonally."
:flocculation "Low"
:form "Liquid"
:product-id "3463"}))
(def belgian-ardennes-3522
(yeasts/build-yeasts :belgian-ardennes-3522 {:min-temperature 18.33
:name "3522 Belgian Ardennes"
:max-temperature 29.44
:type "Wheat"
:best-for "Belgian Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Phenolics develop at increased temperature. Mild fruitiness and complex spicy flavor."
:flocculation "High"
:form "Liquid"
:product-id "3522"}))
(def bavarian-wheat-3638
(yeasts/build-yeasts :bavarian-wheat-3638 {:min-temperature 17.78
:name "3638 Bavarian Wheat"
:max-temperature 23.89
:type "Wheat"
:best-for "Bavarian Weizen, Hefeweizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Hefeweizen yeast with complex flavor and aroma. Bubble gum, banana flavors with apple/plub ester profile. Malty flavor."
:flocculation "Low"
:form "Liquid"
:product-id "3638"}))
(def french-saison-3711
(yeasts/build-yeasts :french-saison-3711 {:min-temperature 18.33
:name "3711 French Saison"
:max-temperature 25.0
:type "Ale"
:best-for "French and Belgian Saison or Farmhouse ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "A very versatile strain that produces Saison or farmhouse style biers as well as other Belgian style beers that are highly aromatic (estery), peppery, spicy and citrusy. This strain enhances the use of spices and aroma hops, and is extremely attenuative b"
:flocculation "Medium"
:form "Liquid"
:product-id "3711"}))
(def belgian-saison-3724
(yeasts/build-yeasts :belgian-saison-3724 {:min-temperature 21.11
:name "3724 Belgian Saison"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian Saison beer"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic farmhouse ale yeast. Spicy, complex aromatics including bubble gum. Tart and dry on the palate with mild fruitiness. Finishes crisp and mildly acidic. Ferment at warm temperature. May have vigorous fermentation start."
:flocculation "Low"
:form "Liquid"
:product-id "3724"}))
(def roselare-belgian-blend-3763
(yeasts/build-yeasts :roselare-belgian-blend-3763 {:min-temperature 12.78
:name "3763 Roselare Belgian Blend"
:max-temperature 26.67
:type "Ale"
:best-for "Belgian sour brown and red beers."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Culture of Saccharomyces, Brettonomyces and Lactic Acid Bacteria. Complex aromas and flavors. May be used for primary fermentation. Primarily for sour brown and red Belgian styles."
:flocculation "Medium"
:form "Liquid"
:product-id "3763"}))
(def trappist-high-gravity-3787
(yeasts/build-yeasts :trappist-high-gravity-3787 {:min-temperature 17.78
:name "3787 Trappist High Gravity"
:max-temperature 25.56
:type "Wheat"
:best-for "Belgian Wit, Trappist Ale, High gravity ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Robust top cropping yeast. Phenolic character and alcohol tolerance up to 12%. Rich ester profile and malty flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "3787"}))
(def belgian-wheat-yeast-3942
(yeasts/build-yeasts :belgian-wheat-yeast-3942 {:min-temperature 17.78
:name "3942 Belgian Wheat Yeast"
:max-temperature 23.33
:type "Wheat"
:best-for "Belgian Wheat, Bavarian Weizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Estery lor phenol yeast. Plum and apple aroma with a dry finish."
:flocculation "Medium"
:form "Liquid"
:product-id "3942"}))
(def belgian-witbier-3944
(yeasts/build-yeasts :belgian-witbier-3944 {:min-temperature 16.67
:name "3944 Belgian Witbier"
:max-temperature 23.89
:type "Wheat"
:best-for "Belgian Wit, Grand Cru"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Tart, slightly phenolic character. For Wits and Grand Cru. Tolerates high gravity beers well."
:flocculation "Medium"
:form "Liquid"
:product-id "3944"}))
(def lactobacillus-delbrueckii-4335
(yeasts/build-yeasts :lactobacillus-delbrueckii-4335 {:min-temperature 15.56
:name "4335 Lactobacillus Delbrueckii"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian gueze, lambic, sour brown ales, and Berliner Weisse."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria isolated from Belgium. Produces mild acidity and sourness found in many types of Belgian beers. Always used in conjunction with S. Cerevisiae and wild yeasts."
:flocculation "Medium"
:form "Liquid"
:product-id "4335"}))
(def pediococcus-cerevisiae-4733
(yeasts/build-yeasts :pediococcus-cerevisiae-4733 {:min-temperature 15.56
:name "4733 Pediococcus Cerevisiae"
:max-temperature 35.0
:type "Ale"
:best-for "Gueze and other Belgian styles."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria isolated from Belgium. Creates a high level of lactic acidity over a long time. Often used with other yeasts, and it may take several months for flavor to fully develop."
:flocculation "Medium"
:form "Liquid"
:product-id "4733"}))
(def brettanomyces-bruxellensis-5112
(yeasts/build-yeasts :brettanomyces-bruxellensis-5112 {:min-temperature 15.56
:name "5112 Brettanomyces Bruxellensis"
:max-temperature 23.89
:type "Ale"
:best-for "Gueuze, Lambics and Sour Browns"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This strain of wild yeast was isolated from brewery cultures in the Brussels region of Belgium. It produces the classic sweaty horse blanket character and may form a pellicle in bottles or casks. The strain is generally used in conjunction with S. cerevis"
:flocculation "Medium"
:form "Liquid"
:product-id "5112"}))
(def lactobacillus-5335
(yeasts/build-yeasts :lactobacillus-5335 {:min-temperature 15.56
:name "5335 Lactobacillus"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian sout beers (secondary)"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria isolated from a Belgian brewery. This culture produces moderate levels of acidity and is commonly found in many types of beers including gueuze, lambics, sour brown ales and Berliner Weisse. It is always used in conjunction with S.cer"
:flocculation "Medium"
:form "Liquid"
:product-id "5335"}))
(def brettanomyces-lambucus-5526
(yeasts/build-yeasts :brettanomyces-lambucus-5526 {:min-temperature 15.56
:name "5526 Brettanomyces Lambucus"
:max-temperature 23.89
:type "Ale"
:best-for "Lambic"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This is a wild yeast strain isolated from Belgian lambic beers. It produces a pie cherry-like flavor and sourness with a distinct Brett character. A pellicle may form in bottles or casks. This strain works best in conjunction with other yeast and lactic b"
:flocculation "Very High"
:form "Liquid"
:product-id "5526"}))
(def pediococcus-5733
(yeasts/build-yeasts :pediococcus-5733 {:min-temperature 18.33
:name "5733 Pediococcus"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian sour ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria used in the production of Belgian style beers where additional acidity is desirable. Often found in gueuze and other Belgian style beer. Acid production will increase with storage time. It may also cause ropiness and produce low level"
:flocculation "Medium"
:form "Liquid"
:product-id "5733"}))
(def wyeast
(merge german-ale-1007 american-wheat-ale-1010 british-cask-ale-1026 london-ale-yeast-1028 american-ale-1056 irish-ale-1084 wyeast-ale-blend-1087
british-ale-yeast-1098 whitbread-ale-1099 ringwood-ale-1187 belgian-ale-yeast-1214 american-ale-ii-1272 gf-all-american-ale-1272 thames-valley-ale-1275
london-ale-iii-1318 northwest-ale-1332 british-ale-ii-1335 european-ale-yeast-1338 belgian-strong-ale-1388 denny-s-favorite-50-1450 scottish-ale-1728
belgian-abbey-ii-1762 london-esb-ale-1968 budvar-lager-2000 urquell-lager-2001 pilsen-lager-2007 american-lager-2035 danish-lager-2042 california-lager-2112
bohemian-lager-2124 wyeast-lager-blend-2178 bavarian-lager-2206 european-lager-ii-2247 north-american-lager-2272 czech-pilsner-lager-2278 munich-lager-2308
kolsch-yeast-2565 octoberfest-lager-blend-2633 bavarian-wheat-yeast-3056 weihenstephan-weizen-3068 brettanomyces-bruxellensis-3112 belgian-lambic-blend-3278
german-wheat-3333 forbidden-fruit-3463 belgian-ardennes-3522 bavarian-wheat-3638 french-saison-3711 belgian-saison-3724 roselare-belgian-blend-3763 trappist-high-gravity-3787
belgian-wheat-yeast-3942 belgian-witbier-3944 lactobacillus-delbrueckii-4335 pediococcus-cerevisiae-4733 brettanomyces-bruxellensis-5112 lactobacillus-5335 brettanomyces-lambucus-5526 pediococcus-5733))
| 119289 | (ns common-beer-format.data.yeasts.wyeast
"Data for yeasts cultivated by Wyeast"
(:require [common-beer-format.data.yeasts.yeasts :as yeasts]))
(def german-ale-1007
(yeasts/build-yeasts :german-ale-1007 {:min-temperature 12.78
:name "1007 German Ale"
:max-temperature 18.89
:type "Ale"
:best-for "German Ales, Alts, Kolsch, Dry Stout"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Crisp, dry finish with a mild flavor."
:flocculation "Low"
:form "Liquid"
:product-id "1007"}))
(def american-wheat-ale-1010
(yeasts/build-yeasts :american-wheat-ale-1010 {:min-temperature 14.44
:name "1010 American Wheat Ale"
:max-temperature 23.33
:type "Ale"
:best-for "American Wheat, Berlin Weiss, Hefeweizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry, Crisp, tart beer in the American Hefeweizen style. Low flocculation aids in producing desired chill haze."
:flocculation "Low"
:form "Liquid"
:product-id "1010"}))
(def british-cask-ale-1026
(yeasts/build-yeasts :british-cask-ale-1026 {:min-temperature 17.22
:name "1026 British Cask Ale"
:max-temperature 22.22
:type "Ale"
:best-for "British Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "A great choice for any cask conditioned British Ale. Produces nice malt profile with a hint of fruit. Finishes dry and slightly tart. "
:flocculation "Medium"
:form "Liquid"
:product-id "1026"}))
(def london-ale-yeast-1028
(yeasts/build-yeasts :london-ale-yeast-1028 {:min-temperature 15.56
:name "1028 London Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "English Ales, Bitters, IPAs, Brown Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry finish, bold, rich flavor, some fruit profile and a crisp finish."
:flocculation "Medium"
:form "Liquid"
:product-id "1028"}))
(def american-ale-1056
(yeasts/build-yeasts :american-ale-1056 {:min-temperature 15.56
:name "1056 American Ale"
:max-temperature 22.22
:type "Ale"
:best-for "American Pale Ale, Scottish Ale, Porters, Sweet Stout, Barley Wine, Alt"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Soft, smooth, clean finish. Very well balanced. Very versitile -- works well with many ale styles."
:flocculation "Medium"
:form "Liquid"
:product-id "1056"}))
(def irish-ale-1084
(yeasts/build-yeasts :irish-ale-1084 {:min-temperature 16.67
:name "1084 Irish Ale"
:max-temperature 22.22
:type "Ale"
:best-for "Irish Dry Stouts, Porter, Scottish Ale, Brown Ale, Imperial Stout, Barley Wine"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry diacetyl, fruity flavor characteristic of stouts. Full bodied, dry, clean flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "1084"}))
(def wyeast-ale-blend-1087
(yeasts/build-yeasts :wyeast-ale-blend-1087 {:min-temperature 17.78
:name "1087 Wyeast Ale Blend"
:max-temperature 22.22
:type "Ale"
:best-for "American and British Ale Styles."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Blend of ale strains designed to provide quick starts, good flavor, balance and flocculation. Balanced finish suitable for most American and British ale styles."
:flocculation "Medium"
:form "Liquid"
:product-id "1087"}))
(def british-ale-yeast-1098
(yeasts/build-yeasts :british-ale-yeast-1098 {:min-temperature 17.78
:name "1098 British Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "All British Ales, Pales, Bitters, English Strong Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Fruity, tart, dry crisp finish. Very well balanced."
:flocculation "Medium"
:form "Liquid"
:product-id "1098"}))
(def whitbread-ale-1099
(yeasts/build-yeasts :whitbread-ale-1099 {:min-temperature 17.78
:name "1099 Whitbread Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Whitbread Ale, British Ales, Pales, Bitters"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Slightly more fruity and malty than Wyeast's British Ale. Clear and highly flocculant."
:flocculation "High"
:form "Liquid"
:product-id "1099"}))
(def ringwood-ale-1187
(yeasts/build-yeasts :ringwood-ale-1187 {:min-temperature 17.78
:name "1187 Ringwood Ale"
:max-temperature 23.33
:type "Ale"
:best-for "Ringwood Ale, Brown Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "European ale yeast. Highly flocculant with complex, clear, but malty profile. Slightly fruity ester."
:flocculation "High"
:form "Liquid"
:product-id "1187"}))
(def belgian-ale-yeast-1214
(yeasts/build-yeasts :belgian-ale-yeast-1214 {:min-temperature 14.44
:name "1214 Belgian Ale Yeast"
:max-temperature 20.0
:type "Ale"
:best-for "Belgian Ales, Abbey Ales, Trappist Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Trappist style ale yeast. Complex estery flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "1214"}))
(def american-ale-ii-1272
(yeasts/build-yeasts :american-ale-ii-1272 {:min-temperature 15.56
:name "1272 American Ale II"
:max-temperature 22.22
:type "Ale"
:best-for "All American Ales, Brown Ales, Barley Wine"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Clean, tart, nutty flavor. More fruity than Wyeast American Ale yeast."
:flocculation "High"
:form "Liquid"
:product-id "1272"}))
(def gf-all-american-ale-1272
(yeasts/build-yeasts :gf-all-american-ale-1272 {:min-temperature 15.56
:name "1272 GF All American Ale"
:max-temperature 22.22
:type "Ale"
:best-for "American Amber, Brown, IPA, Pale ales and stouts. Blondes and fruit beers."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Popular all purpose American ale style now in a Gluten Free strain. Produces beers that are nutty, clean with a slight tart finish. Ferment warmer to accentuate hops and add fruitiness or ferment cold for clean light citrus character."
:flocculation "High"
:form "Liquid"
:product-id "1272"}))
(def thames-valley-ale-1275
(yeasts/build-yeasts :thames-valley-ale-1275 {:min-temperature 16.67
:name "1275 Thames Valley Ale"
:max-temperature 22.22
:type "Ale"
:best-for "British Bitters, ESB, India Pale Ale, English Strong Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Clean, complex flavor. Low in fruit, low in esters, rich in flavor. Hops come through well."
:flocculation "Medium"
:form "Liquid"
:product-id "1275"}))
(def london-ale-iii-1318
(yeasts/build-yeasts :london-ale-iii-1318 {:min-temperature 17.78
:name "1318 London Ale III"
:max-temperature 23.33
:type "Ale"
:best-for "British Ales, Bitters"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Light, fruity flavor. Balanced flavor with hint of sweetness."
:flocculation "High"
:form "Liquid"
:product-id "1318"}))
(def northwest-ale-1332
(yeasts/build-yeasts :northwest-ale-1332 {:min-temperature 18.33
:name "1332 Northwest Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Oregon Ales, All American Ale styles"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic Northwest US ale yeast. Slight fruit flavor, malty ale with good body and balance."
:flocculation "High"
:form "Liquid"
:product-id "1332"}))
(def british-ale-ii-1335
(yeasts/build-yeasts :british-ale-ii-1335 {:min-temperature 17.22
:name "1335 British Ale II"
:max-temperature 23.89
:type "Ale"
:best-for "British and Canadian Ales, English Bitters"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Malty, clean, crisp finish. Dry flavor."
:flocculation "High"
:form "Liquid"
:product-id "1335"}))
(def european-ale-yeast-1338
(yeasts/build-yeasts :european-ale-yeast-1338 {:min-temperature 16.67
:name "1338 European Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "European Ales, German Ales, Alts, Pale Ale, Brown Ale, Kolsch"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Very malty flavor characteristic of Bavarian/Munich Ales. Complex character."
:flocculation "High"
:form "Liquid"
:product-id "1338"}))
(def belgian-strong-ale-1388
(yeasts/build-yeasts :belgian-strong-ale-1388 {:min-temperature 18.33
:name "1388 Belgian Strong Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Ales, Scottish Strong Ale,Trappist Ales, Dubbels, Trippels"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry, tart, fruity flavor. High alcohol tolerance."
:flocculation "Low"
:form "Liquid"
:product-id "1388"}))
(def denny-s-favorite-50-1450
(yeasts/build-yeasts :denny-s-favorite-50-1450 {:min-temperature 15.56
:name "1450 <NAME>'s Favorite 50"
:max-temperature 21.11
:type "Ale"
:best-for "almost any style"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This terrific all-round yeast can be used for almost any beer style, and is a mainstay of one of our local homebrewers, Mr. <NAME>. It is unique in that it produces a big mouthfeel and accentuates the malt, caramel, or fruit character of a beer without being sweet or under-attenuated. "
:flocculation "Low"
:form "Liquid"
:product-id "1450"}))
(def scottish-ale-1728
(yeasts/build-yeasts :scottish-ale-1728 {:min-temperature 12.78
:name "1728 Scottish Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Scottish Ale, Scottish Strong Ales, Sweet Stout, Imperial Stout, Barley Wine"
:laboratory "Wyeast"
:attenuation 0.765
:notes "High alcohol tolerance."
:flocculation "High"
:form "Liquid"
:product-id "1728"}))
(def belgian-abbey-ii-1762
(yeasts/build-yeasts :belgian-abbey-ii-1762 {:min-temperature 18.33
:name "1762 Belgian Abbey II"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Ales, Trappist Ales, Abbey Ales, Grand Cru"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry flavor with slight fruitiness. High alcohol tolerance."
:flocculation "Medium"
:form "Liquid"
:product-id "1762"}))
(def london-esb-ale-1968
(yeasts/build-yeasts :london-esb-ale-1968 {:min-temperature 17.78
:name "1968 London ESB Ale"
:max-temperature 22.22
:type "Ale"
:best-for "English Bitters, IPA, Brown Ales, Mild Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Malty, balanced flavor. Fruity, rich finish. Excellent for cask conditioned ales and bitters."
:flocculation "High"
:form "Liquid"
:product-id "1968"}))
(def budvar-lager-2000
(yeasts/build-yeasts :budvar-lager-2000 {:min-temperature 7.78
:name "2000 Budvar Lager"
:max-temperature 13.33
:type "Lager"
:best-for "Bohemian Pilsner, Classic Pilsners, Dortmunder and Light Lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic pilsner lager yeast. Malty nose and subtle fruit. Rich malt profile, but dry crisp finish. Hop character accentuated by dry finish."
:flocculation "High"
:form "Liquid"
:product-id "2000"}))
(def urquell-lager-2001
(yeasts/build-yeasts :urquell-lager-2001 {:min-temperature 8.89
:name "2001 Urquell Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Bohemian Pilsner"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Pilsner Urquell yeast with mild fruit/floral aroma. Very dry and clean on palate with full mouth feel. Subtle malt character. Clean and neutral finish."
:flocculation "Medium"
:form "Liquid"
:product-id "2001"}))
(def pilsen-lager-2007
(yeasts/build-yeasts :pilsen-lager-2007 {:min-temperature 8.89
:name "2007 Pilsen Lager"
:max-temperature 13.33
:type "Lager"
:best-for "American Pilsner, Bohemian Pilsner, Light Lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic American pilsner strain. Smooth with a malty flavor. Dry and crisp fermentation."
:flocculation "Medium"
:form "Liquid"
:product-id "2007"}))
(def american-lager-2035
(yeasts/build-yeasts :american-lager-2035 {:min-temperature 8.89
:name "2035 American Lager"
:max-temperature 14.44
:type "Lager"
:best-for "American Lagers and Pilsners"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Bold, with a complex aroma. Good flavor depth characteristics for a wide variety of lager beers."
:flocculation "Medium"
:form "Liquid"
:product-id "2035"}))
(def danish-lager-2042
(yeasts/build-yeasts :danish-lager-2042 {:min-temperature 7.78
:name "2042 Danish Lager"
:max-temperature 13.33
:type "Lager"
:best-for "Dortmund/Export Lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Rich, Dortmund style, with a crisp, dry finish. Soft profile accentuates hop flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "2042"}))
(def california-lager-2112
(yeasts/build-yeasts :california-lager-2112 {:min-temperature 14.44
:name "2112 California Lager"
:max-temperature 20.0
:type "Lager"
:best-for "California common beers, Steam Beer"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Suited for 19th century California style beers. Lagers at high temperature and produces malty, clear beers."
:flocculation "High"
:form "Liquid"
:product-id "2112"}))
(def bohemian-lager-2124
(yeasts/build-yeasts :bohemian-lager-2124 {:min-temperature 8.89
:name "2124 Bohemian Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Bohemian Pilsners, Pilsners, German Helles, Bocks"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Ferments clean and malty, with rich malty flavor for full gravity pilsners."
:flocculation "Medium"
:form "Liquid"
:product-id "2124"}))
(def wyeast-lager-blend-2178
(yeasts/build-yeasts :wyeast-lager-blend-2178 {:min-temperature 8.89
:name "2178 Wyeast Lager Blend"
:max-temperature 14.44
:type "Lager"
:best-for "Classic Pilsners, Lagers, Bocks."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Blend of lager strains to produce a complex but clean lager flavor profile. Suitable for many common lager styles."
:flocculation "Medium"
:form "Liquid"
:product-id "2178"}))
(def bavarian-lager-2206
(yeasts/build-yeasts :bavarian-lager-2206 {:min-temperature 7.78
:name "2206 Bavarian Lager"
:max-temperature 14.44
:type "Lager"
:best-for "German Bocks, Vienna, Oktoberfest, Hells, Marzens, Dunkel"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Use by many German breweries. Produces a full-bodied, rich, malty beer."
:flocculation "Medium"
:form "Liquid"
:product-id "2206"}))
(def european-lager-ii-2247
(yeasts/build-yeasts :european-lager-ii-2247 {:min-temperature 7.78
:name "2247 European Lager II"
:max-temperature 13.33
:type "Lager"
:best-for "Bohemian Pilsner, American Pilsner, Helles, Dunkel"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Clean, dry flavor profile for aggressively hopped pilsners. Dry finish, mild aroma, slight sulfur production."
:flocculation "Low"
:form "Liquid"
:product-id "2247"}))
(def north-american-lager-2272
(yeasts/build-yeasts :north-american-lager-2272 {:min-temperature 8.89
:name "2272 North American Lager"
:max-temperature 13.33
:type "Lager"
:best-for "American Pilsner, California Common, Canadian Lager, Oktoberfest, Marzen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "American and Canadian lager yeast. Malty finish makes it suitable for Marzens/Oktoberfest as well."
:flocculation "High"
:form "Liquid"
:product-id "2272"}))
(def czech-pilsner-lager-2278
(yeasts/build-yeasts :czech-pilsner-lager-2278 {:min-temperature 10.0
:name "2278 Czech Pilsner Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Bohemian and American Pilsner, Bocks, Oktoberfest, Marzen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic Pilsner strain. Creates a dry but malty finish. Perfect for Pilsners and bocks. Some sulfur produced, but will fade with time."
:flocculation "Medium"
:form "Liquid"
:product-id "2278"}))
(def munich-lager-2308
(yeasts/build-yeasts :munich-lager-2308 {:min-temperature 8.89
:name "2308 Munich Lager"
:max-temperature 13.33
:type "Lager"
:best-for "Pilsners, Light Lagers, Dortmond/Export, Marzen/Oktoberfest, Dunkel"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Unique Pilsner strain. Very smooth, well-rounded and full bodied. Benefits from a diacetyl rest."
:flocculation "Medium"
:form "Liquid"
:product-id "2308"}))
(def kolsch-yeast-2565
(yeasts/build-yeasts :kolsch-yeast-2565 {:min-temperature 13.33
:name "2565 Kolsch Yeast"
:max-temperature 17.78
:type "Ale"
:best-for "Kolsch, European Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Very malty flavor with mix of lager and ale character. Crisp, clean finish."
:flocculation "Low"
:form "Liquid"
:product-id "2565"}))
(def octoberfest-lager-blend-2633
(yeasts/build-yeasts :octoberfest-lager-blend-2633 {:min-temperature 8.89
:name "2633 Octoberfest Lager Blend"
:max-temperature 14.44
:type "Lager"
:best-for "Octoberfest, Marzen, Bavarian lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This blend of lager strains is designed to produce a rich, malty, complex and full bodied Octoberfest style beer. It attenuates well while leaving plenty of malt character and mouthfeel. This strain is low in sulfur production. "
:flocculation "Low"
:form "Liquid"
:product-id "2633"}))
(def bavarian-wheat-yeast-3056
(yeasts/build-yeasts :bavarian-wheat-yeast-3056 {:min-temperature 17.78
:name "3056 Bavarian Wheat Yeast"
:max-temperature 23.33
:type "Wheat"
:best-for "Bavarian style wheat beers."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Blend of top-fermenting ale and wheat yeasts providing a mild ester and phenolic profile."
:flocculation "Medium"
:form "Liquid"
:product-id "3056"}))
(def weihenstephan-weizen-3068
(yeasts/build-yeasts :weihenstephan-weizen-3068 {:min-temperature 17.78
:name "3068 <NAME>"
:max-temperature 23.89
:type "Wheat"
:best-for "Bavarian Weizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Unique Bavarian wheat yeast that produces the spicy weizen clove and banana flavor. Best when fermented at around 68 deg F."
:flocculation "Low"
:form "Liquid"
:product-id "3068"}))
(def brettanomyces-bruxellensis-3112
(yeasts/build-yeasts :brettanomyces-bruxellensis-3112 {:min-temperature 15.56
:name "3112 Brettanomyces Bruxellensis"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Lambic, Gueze Lambic, and Sour Browns"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Wild yeast strain isolated from Brussels region of Belgium. Adds classic sweaty horse hair flavor as well as sourness and cherry-pie like flavor. Generally used in conjunction with S. Cerevisiae after the primary fermentation has begun. Requires 3-6 mo"
:flocculation "Medium"
:form "Liquid"
:product-id "3112"}))
(def belgian-lambic-blend-3278
(yeasts/build-yeasts :belgian-lambic-blend-3278 {:min-temperature 17.22
:name "3278 Belgian Lambic Blend"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Lambic"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lambic culture of Saccharomyces Cerevisiar and a mixture of yeasts and bacterias. Blend of organisms helps create lactic flavor of Belgian Lambics."
:flocculation "Low"
:form "Liquid"
:product-id "3278"}))
(def german-wheat-3333
(yeasts/build-yeasts :german-wheat-3333 {:min-temperature 17.22
:name "3333 German Wheat"
:max-temperature 23.89
:type "Wheat"
:best-for "Bavarian Weizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Subtle flavor profile. Sharp, fruity, crisp, sherry like flavor."
:flocculation "High"
:form "Liquid"
:product-id "3333"}))
(def forbidden-fruit-3463
(yeasts/build-yeasts :forbidden-fruit-3463 {:min-temperature 17.22
:name "3463 Forbidden Fruit"
:max-temperature 24.44
:type "Wheat"
:best-for "Belgian Wit, Grand Cru"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Phenolic profile with subdued fruitiness. Available seasonally."
:flocculation "Low"
:form "Liquid"
:product-id "3463"}))
(def belgian-ardennes-3522
(yeasts/build-yeasts :belgian-ardennes-3522 {:min-temperature 18.33
:name "3522 Belgian Ardennes"
:max-temperature 29.44
:type "Wheat"
:best-for "Belgian Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Phenolics develop at increased temperature. Mild fruitiness and complex spicy flavor."
:flocculation "High"
:form "Liquid"
:product-id "3522"}))
(def bavarian-wheat-3638
(yeasts/build-yeasts :bavarian-wheat-3638 {:min-temperature 17.78
:name "3638 Bavarian Wheat"
:max-temperature 23.89
:type "Wheat"
:best-for "Bavarian Weizen, Hefeweizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Hefeweizen yeast with complex flavor and aroma. Bubble gum, banana flavors with apple/plub ester profile. Malty flavor."
:flocculation "Low"
:form "Liquid"
:product-id "3638"}))
(def french-saison-3711
(yeasts/build-yeasts :french-saison-3711 {:min-temperature 18.33
:name "3711 French Saison"
:max-temperature 25.0
:type "Ale"
:best-for "French and Belgian Saison or Farmhouse ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "A very versatile strain that produces Saison or farmhouse style biers as well as other Belgian style beers that are highly aromatic (estery), peppery, spicy and citrusy. This strain enhances the use of spices and aroma hops, and is extremely attenuative b"
:flocculation "Medium"
:form "Liquid"
:product-id "3711"}))
(def belgian-saison-3724
(yeasts/build-yeasts :belgian-saison-3724 {:min-temperature 21.11
:name "3724 Belgian Saison"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian Saison beer"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic farmhouse ale yeast. Spicy, complex aromatics including bubble gum. Tart and dry on the palate with mild fruitiness. Finishes crisp and mildly acidic. Ferment at warm temperature. May have vigorous fermentation start."
:flocculation "Low"
:form "Liquid"
:product-id "3724"}))
(def roselare-belgian-blend-3763
(yeasts/build-yeasts :roselare-belgian-blend-3763 {:min-temperature 12.78
:name "3763 Roselare Belgian Blend"
:max-temperature 26.67
:type "Ale"
:best-for "Belgian sour brown and red beers."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Culture of Saccharomyces, Brettonomyces and Lactic Acid Bacteria. Complex aromas and flavors. May be used for primary fermentation. Primarily for sour brown and red Belgian styles."
:flocculation "Medium"
:form "Liquid"
:product-id "3763"}))
(def trappist-high-gravity-3787
(yeasts/build-yeasts :trappist-high-gravity-3787 {:min-temperature 17.78
:name "3787 Trappist High Gravity"
:max-temperature 25.56
:type "Wheat"
:best-for "Belgian Wit, Trappist Ale, High gravity ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Robust top cropping yeast. Phenolic character and alcohol tolerance up to 12%. Rich ester profile and malty flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "3787"}))
(def belgian-wheat-yeast-3942
(yeasts/build-yeasts :belgian-wheat-yeast-3942 {:min-temperature 17.78
:name "3942 Belgian Wheat Yeast"
:max-temperature 23.33
:type "Wheat"
:best-for "Belgian Wheat, Bavarian Weizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Estery lor phenol yeast. Plum and apple aroma with a dry finish."
:flocculation "Medium"
:form "Liquid"
:product-id "3942"}))
(def belgian-witbier-3944
(yeasts/build-yeasts :belgian-witbier-3944 {:min-temperature 16.67
:name "3944 Belgian Witbier"
:max-temperature 23.89
:type "Wheat"
:best-for "Belgian Wit, Grand Cru"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Tart, slightly phenolic character. For Wits and Grand Cru. Tolerates high gravity beers well."
:flocculation "Medium"
:form "Liquid"
:product-id "3944"}))
(def lactobacillus-delbrueckii-4335
(yeasts/build-yeasts :lactobacillus-delbrueckii-4335 {:min-temperature 15.56
:name "4335 Lactobacillus Delbrueckii"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian gueze, lambic, sour brown ales, and Berliner Weisse."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria isolated from Belgium. Produces mild acidity and sourness found in many types of Belgian beers. Always used in conjunction with S. Cerevisiae and wild yeasts."
:flocculation "Medium"
:form "Liquid"
:product-id "4335"}))
(def pediococcus-cerevisiae-4733
(yeasts/build-yeasts :pediococcus-cerevisiae-4733 {:min-temperature 15.56
:name "4733 Pediococcus Cerevisiae"
:max-temperature 35.0
:type "Ale"
:best-for "Gueze and other Belgian styles."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria isolated from Belgium. Creates a high level of lactic acidity over a long time. Often used with other yeasts, and it may take several months for flavor to fully develop."
:flocculation "Medium"
:form "Liquid"
:product-id "4733"}))
(def brettanomyces-bruxellensis-5112
(yeasts/build-yeasts :brettanomyces-bruxellensis-5112 {:min-temperature 15.56
:name "5112 Brettanomyces Bruxellensis"
:max-temperature 23.89
:type "Ale"
:best-for "Gueuze, Lambics and Sour Browns"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This strain of wild yeast was isolated from brewery cultures in the Brussels region of Belgium. It produces the classic sweaty horse blanket character and may form a pellicle in bottles or casks. The strain is generally used in conjunction with S. cerevis"
:flocculation "Medium"
:form "Liquid"
:product-id "5112"}))
(def lactobacillus-5335
(yeasts/build-yeasts :lactobacillus-5335 {:min-temperature 15.56
:name "5335 Lactobacillus"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian sout beers (secondary)"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria isolated from a Belgian brewery. This culture produces moderate levels of acidity and is commonly found in many types of beers including gueuze, lambics, sour brown ales and Berliner Weisse. It is always used in conjunction with S.cer"
:flocculation "Medium"
:form "Liquid"
:product-id "5335"}))
(def brettanomyces-lambucus-5526
(yeasts/build-yeasts :brettanomyces-lambucus-5526 {:min-temperature 15.56
:name "5526 Brettanomyces Lambucus"
:max-temperature 23.89
:type "Ale"
:best-for "Lambic"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This is a wild yeast strain isolated from Belgian lambic beers. It produces a pie cherry-like flavor and sourness with a distinct Brett character. A pellicle may form in bottles or casks. This strain works best in conjunction with other yeast and lactic b"
:flocculation "Very High"
:form "Liquid"
:product-id "5526"}))
(def pediococcus-5733
(yeasts/build-yeasts :pediococcus-5733 {:min-temperature 18.33
:name "5733 Pediococcus"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian sour ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria used in the production of Belgian style beers where additional acidity is desirable. Often found in gueuze and other Belgian style beer. Acid production will increase with storage time. It may also cause ropiness and produce low level"
:flocculation "Medium"
:form "Liquid"
:product-id "5733"}))
(def wyeast
(merge german-ale-1007 american-wheat-ale-1010 british-cask-ale-1026 london-ale-yeast-1028 american-ale-1056 irish-ale-1084 wyeast-ale-blend-1087
british-ale-yeast-1098 whitbread-ale-1099 ringwood-ale-1187 belgian-ale-yeast-1214 american-ale-ii-1272 gf-all-american-ale-1272 thames-valley-ale-1275
london-ale-iii-1318 northwest-ale-1332 british-ale-ii-1335 european-ale-yeast-1338 belgian-strong-ale-1388 denny-s-favorite-50-1450 scottish-ale-1728
belgian-abbey-ii-1762 london-esb-ale-1968 budvar-lager-2000 urquell-lager-2001 pilsen-lager-2007 american-lager-2035 danish-lager-2042 california-lager-2112
bohemian-lager-2124 wyeast-lager-blend-2178 bavarian-lager-2206 european-lager-ii-2247 north-american-lager-2272 czech-pilsner-lager-2278 munich-lager-2308
kolsch-yeast-2565 octoberfest-lager-blend-2633 bavarian-wheat-yeast-3056 weihenstephan-weizen-3068 brettanomyces-bruxellensis-3112 belgian-lambic-blend-3278
german-wheat-3333 forbidden-fruit-3463 belgian-ardennes-3522 bavarian-wheat-3638 french-saison-3711 belgian-saison-3724 roselare-belgian-blend-3763 trappist-high-gravity-3787
belgian-wheat-yeast-3942 belgian-witbier-3944 lactobacillus-delbrueckii-4335 pediococcus-cerevisiae-4733 brettanomyces-bruxellensis-5112 lactobacillus-5335 brettanomyces-lambucus-5526 pediococcus-5733))
| true | (ns common-beer-format.data.yeasts.wyeast
"Data for yeasts cultivated by Wyeast"
(:require [common-beer-format.data.yeasts.yeasts :as yeasts]))
(def german-ale-1007
(yeasts/build-yeasts :german-ale-1007 {:min-temperature 12.78
:name "1007 German Ale"
:max-temperature 18.89
:type "Ale"
:best-for "German Ales, Alts, Kolsch, Dry Stout"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Crisp, dry finish with a mild flavor."
:flocculation "Low"
:form "Liquid"
:product-id "1007"}))
(def american-wheat-ale-1010
(yeasts/build-yeasts :american-wheat-ale-1010 {:min-temperature 14.44
:name "1010 American Wheat Ale"
:max-temperature 23.33
:type "Ale"
:best-for "American Wheat, Berlin Weiss, Hefeweizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry, Crisp, tart beer in the American Hefeweizen style. Low flocculation aids in producing desired chill haze."
:flocculation "Low"
:form "Liquid"
:product-id "1010"}))
(def british-cask-ale-1026
(yeasts/build-yeasts :british-cask-ale-1026 {:min-temperature 17.22
:name "1026 British Cask Ale"
:max-temperature 22.22
:type "Ale"
:best-for "British Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "A great choice for any cask conditioned British Ale. Produces nice malt profile with a hint of fruit. Finishes dry and slightly tart. "
:flocculation "Medium"
:form "Liquid"
:product-id "1026"}))
(def london-ale-yeast-1028
(yeasts/build-yeasts :london-ale-yeast-1028 {:min-temperature 15.56
:name "1028 London Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "English Ales, Bitters, IPAs, Brown Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry finish, bold, rich flavor, some fruit profile and a crisp finish."
:flocculation "Medium"
:form "Liquid"
:product-id "1028"}))
(def american-ale-1056
(yeasts/build-yeasts :american-ale-1056 {:min-temperature 15.56
:name "1056 American Ale"
:max-temperature 22.22
:type "Ale"
:best-for "American Pale Ale, Scottish Ale, Porters, Sweet Stout, Barley Wine, Alt"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Soft, smooth, clean finish. Very well balanced. Very versitile -- works well with many ale styles."
:flocculation "Medium"
:form "Liquid"
:product-id "1056"}))
(def irish-ale-1084
(yeasts/build-yeasts :irish-ale-1084 {:min-temperature 16.67
:name "1084 Irish Ale"
:max-temperature 22.22
:type "Ale"
:best-for "Irish Dry Stouts, Porter, Scottish Ale, Brown Ale, Imperial Stout, Barley Wine"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry diacetyl, fruity flavor characteristic of stouts. Full bodied, dry, clean flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "1084"}))
(def wyeast-ale-blend-1087
(yeasts/build-yeasts :wyeast-ale-blend-1087 {:min-temperature 17.78
:name "1087 Wyeast Ale Blend"
:max-temperature 22.22
:type "Ale"
:best-for "American and British Ale Styles."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Blend of ale strains designed to provide quick starts, good flavor, balance and flocculation. Balanced finish suitable for most American and British ale styles."
:flocculation "Medium"
:form "Liquid"
:product-id "1087"}))
(def british-ale-yeast-1098
(yeasts/build-yeasts :british-ale-yeast-1098 {:min-temperature 17.78
:name "1098 British Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "All British Ales, Pales, Bitters, English Strong Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Fruity, tart, dry crisp finish. Very well balanced."
:flocculation "Medium"
:form "Liquid"
:product-id "1098"}))
(def whitbread-ale-1099
(yeasts/build-yeasts :whitbread-ale-1099 {:min-temperature 17.78
:name "1099 Whitbread Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Whitbread Ale, British Ales, Pales, Bitters"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Slightly more fruity and malty than Wyeast's British Ale. Clear and highly flocculant."
:flocculation "High"
:form "Liquid"
:product-id "1099"}))
(def ringwood-ale-1187
(yeasts/build-yeasts :ringwood-ale-1187 {:min-temperature 17.78
:name "1187 Ringwood Ale"
:max-temperature 23.33
:type "Ale"
:best-for "Ringwood Ale, Brown Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "European ale yeast. Highly flocculant with complex, clear, but malty profile. Slightly fruity ester."
:flocculation "High"
:form "Liquid"
:product-id "1187"}))
(def belgian-ale-yeast-1214
(yeasts/build-yeasts :belgian-ale-yeast-1214 {:min-temperature 14.44
:name "1214 Belgian Ale Yeast"
:max-temperature 20.0
:type "Ale"
:best-for "Belgian Ales, Abbey Ales, Trappist Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Trappist style ale yeast. Complex estery flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "1214"}))
(def american-ale-ii-1272
(yeasts/build-yeasts :american-ale-ii-1272 {:min-temperature 15.56
:name "1272 American Ale II"
:max-temperature 22.22
:type "Ale"
:best-for "All American Ales, Brown Ales, Barley Wine"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Clean, tart, nutty flavor. More fruity than Wyeast American Ale yeast."
:flocculation "High"
:form "Liquid"
:product-id "1272"}))
(def gf-all-american-ale-1272
(yeasts/build-yeasts :gf-all-american-ale-1272 {:min-temperature 15.56
:name "1272 GF All American Ale"
:max-temperature 22.22
:type "Ale"
:best-for "American Amber, Brown, IPA, Pale ales and stouts. Blondes and fruit beers."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Popular all purpose American ale style now in a Gluten Free strain. Produces beers that are nutty, clean with a slight tart finish. Ferment warmer to accentuate hops and add fruitiness or ferment cold for clean light citrus character."
:flocculation "High"
:form "Liquid"
:product-id "1272"}))
(def thames-valley-ale-1275
(yeasts/build-yeasts :thames-valley-ale-1275 {:min-temperature 16.67
:name "1275 Thames Valley Ale"
:max-temperature 22.22
:type "Ale"
:best-for "British Bitters, ESB, India Pale Ale, English Strong Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Clean, complex flavor. Low in fruit, low in esters, rich in flavor. Hops come through well."
:flocculation "Medium"
:form "Liquid"
:product-id "1275"}))
(def london-ale-iii-1318
(yeasts/build-yeasts :london-ale-iii-1318 {:min-temperature 17.78
:name "1318 London Ale III"
:max-temperature 23.33
:type "Ale"
:best-for "British Ales, Bitters"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Light, fruity flavor. Balanced flavor with hint of sweetness."
:flocculation "High"
:form "Liquid"
:product-id "1318"}))
(def northwest-ale-1332
(yeasts/build-yeasts :northwest-ale-1332 {:min-temperature 18.33
:name "1332 Northwest Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Oregon Ales, All American Ale styles"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic Northwest US ale yeast. Slight fruit flavor, malty ale with good body and balance."
:flocculation "High"
:form "Liquid"
:product-id "1332"}))
(def british-ale-ii-1335
(yeasts/build-yeasts :british-ale-ii-1335 {:min-temperature 17.22
:name "1335 British Ale II"
:max-temperature 23.89
:type "Ale"
:best-for "British and Canadian Ales, English Bitters"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Malty, clean, crisp finish. Dry flavor."
:flocculation "High"
:form "Liquid"
:product-id "1335"}))
(def european-ale-yeast-1338
(yeasts/build-yeasts :european-ale-yeast-1338 {:min-temperature 16.67
:name "1338 European Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "European Ales, German Ales, Alts, Pale Ale, Brown Ale, Kolsch"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Very malty flavor characteristic of Bavarian/Munich Ales. Complex character."
:flocculation "High"
:form "Liquid"
:product-id "1338"}))
(def belgian-strong-ale-1388
(yeasts/build-yeasts :belgian-strong-ale-1388 {:min-temperature 18.33
:name "1388 Belgian Strong Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Ales, Scottish Strong Ale,Trappist Ales, Dubbels, Trippels"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry, tart, fruity flavor. High alcohol tolerance."
:flocculation "Low"
:form "Liquid"
:product-id "1388"}))
(def denny-s-favorite-50-1450
(yeasts/build-yeasts :denny-s-favorite-50-1450 {:min-temperature 15.56
:name "1450 PI:NAME:<NAME>END_PI's Favorite 50"
:max-temperature 21.11
:type "Ale"
:best-for "almost any style"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This terrific all-round yeast can be used for almost any beer style, and is a mainstay of one of our local homebrewers, Mr. PI:NAME:<NAME>END_PI. It is unique in that it produces a big mouthfeel and accentuates the malt, caramel, or fruit character of a beer without being sweet or under-attenuated. "
:flocculation "Low"
:form "Liquid"
:product-id "1450"}))
(def scottish-ale-1728
(yeasts/build-yeasts :scottish-ale-1728 {:min-temperature 12.78
:name "1728 Scottish Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Scottish Ale, Scottish Strong Ales, Sweet Stout, Imperial Stout, Barley Wine"
:laboratory "Wyeast"
:attenuation 0.765
:notes "High alcohol tolerance."
:flocculation "High"
:form "Liquid"
:product-id "1728"}))
(def belgian-abbey-ii-1762
(yeasts/build-yeasts :belgian-abbey-ii-1762 {:min-temperature 18.33
:name "1762 Belgian Abbey II"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Ales, Trappist Ales, Abbey Ales, Grand Cru"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Dry flavor with slight fruitiness. High alcohol tolerance."
:flocculation "Medium"
:form "Liquid"
:product-id "1762"}))
(def london-esb-ale-1968
(yeasts/build-yeasts :london-esb-ale-1968 {:min-temperature 17.78
:name "1968 London ESB Ale"
:max-temperature 22.22
:type "Ale"
:best-for "English Bitters, IPA, Brown Ales, Mild Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Malty, balanced flavor. Fruity, rich finish. Excellent for cask conditioned ales and bitters."
:flocculation "High"
:form "Liquid"
:product-id "1968"}))
(def budvar-lager-2000
(yeasts/build-yeasts :budvar-lager-2000 {:min-temperature 7.78
:name "2000 Budvar Lager"
:max-temperature 13.33
:type "Lager"
:best-for "Bohemian Pilsner, Classic Pilsners, Dortmunder and Light Lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic pilsner lager yeast. Malty nose and subtle fruit. Rich malt profile, but dry crisp finish. Hop character accentuated by dry finish."
:flocculation "High"
:form "Liquid"
:product-id "2000"}))
(def urquell-lager-2001
(yeasts/build-yeasts :urquell-lager-2001 {:min-temperature 8.89
:name "2001 Urquell Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Bohemian Pilsner"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Pilsner Urquell yeast with mild fruit/floral aroma. Very dry and clean on palate with full mouth feel. Subtle malt character. Clean and neutral finish."
:flocculation "Medium"
:form "Liquid"
:product-id "2001"}))
(def pilsen-lager-2007
(yeasts/build-yeasts :pilsen-lager-2007 {:min-temperature 8.89
:name "2007 Pilsen Lager"
:max-temperature 13.33
:type "Lager"
:best-for "American Pilsner, Bohemian Pilsner, Light Lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic American pilsner strain. Smooth with a malty flavor. Dry and crisp fermentation."
:flocculation "Medium"
:form "Liquid"
:product-id "2007"}))
(def american-lager-2035
(yeasts/build-yeasts :american-lager-2035 {:min-temperature 8.89
:name "2035 American Lager"
:max-temperature 14.44
:type "Lager"
:best-for "American Lagers and Pilsners"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Bold, with a complex aroma. Good flavor depth characteristics for a wide variety of lager beers."
:flocculation "Medium"
:form "Liquid"
:product-id "2035"}))
(def danish-lager-2042
(yeasts/build-yeasts :danish-lager-2042 {:min-temperature 7.78
:name "2042 Danish Lager"
:max-temperature 13.33
:type "Lager"
:best-for "Dortmund/Export Lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Rich, Dortmund style, with a crisp, dry finish. Soft profile accentuates hop flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "2042"}))
(def california-lager-2112
(yeasts/build-yeasts :california-lager-2112 {:min-temperature 14.44
:name "2112 California Lager"
:max-temperature 20.0
:type "Lager"
:best-for "California common beers, Steam Beer"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Suited for 19th century California style beers. Lagers at high temperature and produces malty, clear beers."
:flocculation "High"
:form "Liquid"
:product-id "2112"}))
(def bohemian-lager-2124
(yeasts/build-yeasts :bohemian-lager-2124 {:min-temperature 8.89
:name "2124 Bohemian Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Bohemian Pilsners, Pilsners, German Helles, Bocks"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Ferments clean and malty, with rich malty flavor for full gravity pilsners."
:flocculation "Medium"
:form "Liquid"
:product-id "2124"}))
(def wyeast-lager-blend-2178
(yeasts/build-yeasts :wyeast-lager-blend-2178 {:min-temperature 8.89
:name "2178 Wyeast Lager Blend"
:max-temperature 14.44
:type "Lager"
:best-for "Classic Pilsners, Lagers, Bocks."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Blend of lager strains to produce a complex but clean lager flavor profile. Suitable for many common lager styles."
:flocculation "Medium"
:form "Liquid"
:product-id "2178"}))
(def bavarian-lager-2206
(yeasts/build-yeasts :bavarian-lager-2206 {:min-temperature 7.78
:name "2206 Bavarian Lager"
:max-temperature 14.44
:type "Lager"
:best-for "German Bocks, Vienna, Oktoberfest, Hells, Marzens, Dunkel"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Use by many German breweries. Produces a full-bodied, rich, malty beer."
:flocculation "Medium"
:form "Liquid"
:product-id "2206"}))
(def european-lager-ii-2247
(yeasts/build-yeasts :european-lager-ii-2247 {:min-temperature 7.78
:name "2247 European Lager II"
:max-temperature 13.33
:type "Lager"
:best-for "Bohemian Pilsner, American Pilsner, Helles, Dunkel"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Clean, dry flavor profile for aggressively hopped pilsners. Dry finish, mild aroma, slight sulfur production."
:flocculation "Low"
:form "Liquid"
:product-id "2247"}))
(def north-american-lager-2272
(yeasts/build-yeasts :north-american-lager-2272 {:min-temperature 8.89
:name "2272 North American Lager"
:max-temperature 13.33
:type "Lager"
:best-for "American Pilsner, California Common, Canadian Lager, Oktoberfest, Marzen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "American and Canadian lager yeast. Malty finish makes it suitable for Marzens/Oktoberfest as well."
:flocculation "High"
:form "Liquid"
:product-id "2272"}))
(def czech-pilsner-lager-2278
(yeasts/build-yeasts :czech-pilsner-lager-2278 {:min-temperature 10.0
:name "2278 Czech Pilsner Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Bohemian and American Pilsner, Bocks, Oktoberfest, Marzen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic Pilsner strain. Creates a dry but malty finish. Perfect for Pilsners and bocks. Some sulfur produced, but will fade with time."
:flocculation "Medium"
:form "Liquid"
:product-id "2278"}))
(def munich-lager-2308
(yeasts/build-yeasts :munich-lager-2308 {:min-temperature 8.89
:name "2308 Munich Lager"
:max-temperature 13.33
:type "Lager"
:best-for "Pilsners, Light Lagers, Dortmond/Export, Marzen/Oktoberfest, Dunkel"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Unique Pilsner strain. Very smooth, well-rounded and full bodied. Benefits from a diacetyl rest."
:flocculation "Medium"
:form "Liquid"
:product-id "2308"}))
(def kolsch-yeast-2565
(yeasts/build-yeasts :kolsch-yeast-2565 {:min-temperature 13.33
:name "2565 Kolsch Yeast"
:max-temperature 17.78
:type "Ale"
:best-for "Kolsch, European Ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Very malty flavor with mix of lager and ale character. Crisp, clean finish."
:flocculation "Low"
:form "Liquid"
:product-id "2565"}))
(def octoberfest-lager-blend-2633
(yeasts/build-yeasts :octoberfest-lager-blend-2633 {:min-temperature 8.89
:name "2633 Octoberfest Lager Blend"
:max-temperature 14.44
:type "Lager"
:best-for "Octoberfest, Marzen, Bavarian lagers"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This blend of lager strains is designed to produce a rich, malty, complex and full bodied Octoberfest style beer. It attenuates well while leaving plenty of malt character and mouthfeel. This strain is low in sulfur production. "
:flocculation "Low"
:form "Liquid"
:product-id "2633"}))
(def bavarian-wheat-yeast-3056
(yeasts/build-yeasts :bavarian-wheat-yeast-3056 {:min-temperature 17.78
:name "3056 Bavarian Wheat Yeast"
:max-temperature 23.33
:type "Wheat"
:best-for "Bavarian style wheat beers."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Blend of top-fermenting ale and wheat yeasts providing a mild ester and phenolic profile."
:flocculation "Medium"
:form "Liquid"
:product-id "3056"}))
(def weihenstephan-weizen-3068
(yeasts/build-yeasts :weihenstephan-weizen-3068 {:min-temperature 17.78
:name "3068 PI:NAME:<NAME>END_PI"
:max-temperature 23.89
:type "Wheat"
:best-for "Bavarian Weizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Unique Bavarian wheat yeast that produces the spicy weizen clove and banana flavor. Best when fermented at around 68 deg F."
:flocculation "Low"
:form "Liquid"
:product-id "3068"}))
(def brettanomyces-bruxellensis-3112
(yeasts/build-yeasts :brettanomyces-bruxellensis-3112 {:min-temperature 15.56
:name "3112 Brettanomyces Bruxellensis"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Lambic, Gueze Lambic, and Sour Browns"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Wild yeast strain isolated from Brussels region of Belgium. Adds classic sweaty horse hair flavor as well as sourness and cherry-pie like flavor. Generally used in conjunction with S. Cerevisiae after the primary fermentation has begun. Requires 3-6 mo"
:flocculation "Medium"
:form "Liquid"
:product-id "3112"}))
(def belgian-lambic-blend-3278
(yeasts/build-yeasts :belgian-lambic-blend-3278 {:min-temperature 17.22
:name "3278 Belgian Lambic Blend"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Lambic"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lambic culture of Saccharomyces Cerevisiar and a mixture of yeasts and bacterias. Blend of organisms helps create lactic flavor of Belgian Lambics."
:flocculation "Low"
:form "Liquid"
:product-id "3278"}))
(def german-wheat-3333
(yeasts/build-yeasts :german-wheat-3333 {:min-temperature 17.22
:name "3333 German Wheat"
:max-temperature 23.89
:type "Wheat"
:best-for "Bavarian Weizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Subtle flavor profile. Sharp, fruity, crisp, sherry like flavor."
:flocculation "High"
:form "Liquid"
:product-id "3333"}))
(def forbidden-fruit-3463
(yeasts/build-yeasts :forbidden-fruit-3463 {:min-temperature 17.22
:name "3463 Forbidden Fruit"
:max-temperature 24.44
:type "Wheat"
:best-for "Belgian Wit, Grand Cru"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Phenolic profile with subdued fruitiness. Available seasonally."
:flocculation "Low"
:form "Liquid"
:product-id "3463"}))
(def belgian-ardennes-3522
(yeasts/build-yeasts :belgian-ardennes-3522 {:min-temperature 18.33
:name "3522 Belgian Ardennes"
:max-temperature 29.44
:type "Wheat"
:best-for "Belgian Ale"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Phenolics develop at increased temperature. Mild fruitiness and complex spicy flavor."
:flocculation "High"
:form "Liquid"
:product-id "3522"}))
(def bavarian-wheat-3638
(yeasts/build-yeasts :bavarian-wheat-3638 {:min-temperature 17.78
:name "3638 Bavarian Wheat"
:max-temperature 23.89
:type "Wheat"
:best-for "Bavarian Weizen, Hefeweizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Hefeweizen yeast with complex flavor and aroma. Bubble gum, banana flavors with apple/plub ester profile. Malty flavor."
:flocculation "Low"
:form "Liquid"
:product-id "3638"}))
(def french-saison-3711
(yeasts/build-yeasts :french-saison-3711 {:min-temperature 18.33
:name "3711 French Saison"
:max-temperature 25.0
:type "Ale"
:best-for "French and Belgian Saison or Farmhouse ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "A very versatile strain that produces Saison or farmhouse style biers as well as other Belgian style beers that are highly aromatic (estery), peppery, spicy and citrusy. This strain enhances the use of spices and aroma hops, and is extremely attenuative b"
:flocculation "Medium"
:form "Liquid"
:product-id "3711"}))
(def belgian-saison-3724
(yeasts/build-yeasts :belgian-saison-3724 {:min-temperature 21.11
:name "3724 Belgian Saison"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian Saison beer"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Classic farmhouse ale yeast. Spicy, complex aromatics including bubble gum. Tart and dry on the palate with mild fruitiness. Finishes crisp and mildly acidic. Ferment at warm temperature. May have vigorous fermentation start."
:flocculation "Low"
:form "Liquid"
:product-id "3724"}))
(def roselare-belgian-blend-3763
(yeasts/build-yeasts :roselare-belgian-blend-3763 {:min-temperature 12.78
:name "3763 Roselare Belgian Blend"
:max-temperature 26.67
:type "Ale"
:best-for "Belgian sour brown and red beers."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Culture of Saccharomyces, Brettonomyces and Lactic Acid Bacteria. Complex aromas and flavors. May be used for primary fermentation. Primarily for sour brown and red Belgian styles."
:flocculation "Medium"
:form "Liquid"
:product-id "3763"}))
(def trappist-high-gravity-3787
(yeasts/build-yeasts :trappist-high-gravity-3787 {:min-temperature 17.78
:name "3787 Trappist High Gravity"
:max-temperature 25.56
:type "Wheat"
:best-for "Belgian Wit, Trappist Ale, High gravity ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Robust top cropping yeast. Phenolic character and alcohol tolerance up to 12%. Rich ester profile and malty flavor."
:flocculation "Medium"
:form "Liquid"
:product-id "3787"}))
(def belgian-wheat-yeast-3942
(yeasts/build-yeasts :belgian-wheat-yeast-3942 {:min-temperature 17.78
:name "3942 Belgian Wheat Yeast"
:max-temperature 23.33
:type "Wheat"
:best-for "Belgian Wheat, Bavarian Weizen"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Estery lor phenol yeast. Plum and apple aroma with a dry finish."
:flocculation "Medium"
:form "Liquid"
:product-id "3942"}))
(def belgian-witbier-3944
(yeasts/build-yeasts :belgian-witbier-3944 {:min-temperature 16.67
:name "3944 Belgian Witbier"
:max-temperature 23.89
:type "Wheat"
:best-for "Belgian Wit, Grand Cru"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Tart, slightly phenolic character. For Wits and Grand Cru. Tolerates high gravity beers well."
:flocculation "Medium"
:form "Liquid"
:product-id "3944"}))
(def lactobacillus-delbrueckii-4335
(yeasts/build-yeasts :lactobacillus-delbrueckii-4335 {:min-temperature 15.56
:name "4335 Lactobacillus Delbrueckii"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian gueze, lambic, sour brown ales, and Berliner Weisse."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria isolated from Belgium. Produces mild acidity and sourness found in many types of Belgian beers. Always used in conjunction with S. Cerevisiae and wild yeasts."
:flocculation "Medium"
:form "Liquid"
:product-id "4335"}))
(def pediococcus-cerevisiae-4733
(yeasts/build-yeasts :pediococcus-cerevisiae-4733 {:min-temperature 15.56
:name "4733 Pediococcus Cerevisiae"
:max-temperature 35.0
:type "Ale"
:best-for "Gueze and other Belgian styles."
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria isolated from Belgium. Creates a high level of lactic acidity over a long time. Often used with other yeasts, and it may take several months for flavor to fully develop."
:flocculation "Medium"
:form "Liquid"
:product-id "4733"}))
(def brettanomyces-bruxellensis-5112
(yeasts/build-yeasts :brettanomyces-bruxellensis-5112 {:min-temperature 15.56
:name "5112 Brettanomyces Bruxellensis"
:max-temperature 23.89
:type "Ale"
:best-for "Gueuze, Lambics and Sour Browns"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This strain of wild yeast was isolated from brewery cultures in the Brussels region of Belgium. It produces the classic sweaty horse blanket character and may form a pellicle in bottles or casks. The strain is generally used in conjunction with S. cerevis"
:flocculation "Medium"
:form "Liquid"
:product-id "5112"}))
(def lactobacillus-5335
(yeasts/build-yeasts :lactobacillus-5335 {:min-temperature 15.56
:name "5335 Lactobacillus"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian sout beers (secondary)"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria isolated from a Belgian brewery. This culture produces moderate levels of acidity and is commonly found in many types of beers including gueuze, lambics, sour brown ales and Berliner Weisse. It is always used in conjunction with S.cer"
:flocculation "Medium"
:form "Liquid"
:product-id "5335"}))
(def brettanomyces-lambucus-5526
(yeasts/build-yeasts :brettanomyces-lambucus-5526 {:min-temperature 15.56
:name "5526 Brettanomyces Lambucus"
:max-temperature 23.89
:type "Ale"
:best-for "Lambic"
:laboratory "Wyeast"
:attenuation 0.765
:notes "This is a wild yeast strain isolated from Belgian lambic beers. It produces a pie cherry-like flavor and sourness with a distinct Brett character. A pellicle may form in bottles or casks. This strain works best in conjunction with other yeast and lactic b"
:flocculation "Very High"
:form "Liquid"
:product-id "5526"}))
(def pediococcus-5733
(yeasts/build-yeasts :pediococcus-5733 {:min-temperature 18.33
:name "5733 Pediococcus"
:max-temperature 35.0
:type "Ale"
:best-for "Belgian sour ales"
:laboratory "Wyeast"
:attenuation 0.765
:notes "Lactic acid bacteria used in the production of Belgian style beers where additional acidity is desirable. Often found in gueuze and other Belgian style beer. Acid production will increase with storage time. It may also cause ropiness and produce low level"
:flocculation "Medium"
:form "Liquid"
:product-id "5733"}))
(def wyeast
(merge german-ale-1007 american-wheat-ale-1010 british-cask-ale-1026 london-ale-yeast-1028 american-ale-1056 irish-ale-1084 wyeast-ale-blend-1087
british-ale-yeast-1098 whitbread-ale-1099 ringwood-ale-1187 belgian-ale-yeast-1214 american-ale-ii-1272 gf-all-american-ale-1272 thames-valley-ale-1275
london-ale-iii-1318 northwest-ale-1332 british-ale-ii-1335 european-ale-yeast-1338 belgian-strong-ale-1388 denny-s-favorite-50-1450 scottish-ale-1728
belgian-abbey-ii-1762 london-esb-ale-1968 budvar-lager-2000 urquell-lager-2001 pilsen-lager-2007 american-lager-2035 danish-lager-2042 california-lager-2112
bohemian-lager-2124 wyeast-lager-blend-2178 bavarian-lager-2206 european-lager-ii-2247 north-american-lager-2272 czech-pilsner-lager-2278 munich-lager-2308
kolsch-yeast-2565 octoberfest-lager-blend-2633 bavarian-wheat-yeast-3056 weihenstephan-weizen-3068 brettanomyces-bruxellensis-3112 belgian-lambic-blend-3278
german-wheat-3333 forbidden-fruit-3463 belgian-ardennes-3522 bavarian-wheat-3638 french-saison-3711 belgian-saison-3724 roselare-belgian-blend-3763 trappist-high-gravity-3787
belgian-wheat-yeast-3942 belgian-witbier-3944 lactobacillus-delbrueckii-4335 pediococcus-cerevisiae-4733 brettanomyces-bruxellensis-5112 lactobacillus-5335 brettanomyces-lambucus-5526 pediococcus-5733))
|
[
{
"context": "e false})\n\n(def registration-data\n {:first_name \"Testing\"\n :last_name \"Registration\"\n :email \"test.reg",
"end": 293,
"score": 0.9998180270195007,
"start": 286,
"tag": "NAME",
"value": "Testing"
},
{
"context": "tion-data\n {:first_name \"Testing\"\n :last_name \"Registration\"\n :email \"test.registration@example.com\"\n :co",
"end": 322,
"score": 0.9997473359107971,
"start": 310,
"tag": "NAME",
"value": "Registration"
},
{
"context": "\"Testing\"\n :last_name \"Registration\"\n :email \"test.registration@example.com\"\n :country \"US\"\n :password \"123456\"\n :langu",
"end": 364,
"score": 0.9999298453330994,
"start": 335,
"tag": "EMAIL",
"value": "test.registration@example.com"
},
{
"context": "ation@example.com\"\n :country \"US\"\n :password \"123456\"\n :language \"fi\"\n :password_verify \"123456\"\n ",
"end": 403,
"score": 0.9993441104888916,
"start": 397,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "d \"123456\"\n :language \"fi\"\n :password_verify \"123456\"\n })\n\n\n\n(t/deftest-ctx main-test [ctx]\n (testi",
"end": 450,
"score": 0.9993658065795898,
"start": 444,
"tag": "PASSWORD",
"value": "123456"
}
] | test/clj/salava/user/db_test.clj | discendum/salava | 17 | (ns salava.user.db-test
(:require [salava.user.db :as db]
[clojure.test :refer :all]
[salava.core.migrator :as migrator]
[salava.core.test-utils :as t]))
(def test-user {:id 1 :role "user" :private false})
(def registration-data
{:first_name "Testing"
:last_name "Registration"
:email "test.registration@example.com"
:country "US"
:password "123456"
:language "fi"
:password_verify "123456"
})
(t/deftest-ctx main-test [ctx]
(testing "register user "
(testing "register user with correct data"
(let [connect (db/register-user ctx (:email registration-data) (:first_name registration-data) (:last_name registration-data) (:country registration-data) (:language registration-data) (:password registration-data) (:password_verify registration-data))]
(is (= "success" (:status connect)))
(is (= "" (:message connect)))
))
(testing "register user again with same data"
(let [connect (db/register-user ctx (:email registration-data) (:first_name registration-data) (:last_name registration-data) (:country registration-data) (:language registration-data) (:password registration-data) (:password_verify registration-data))]
(is (= "error" (:status connect)))
(is (= "user/Enteredaddressisalready" (:message connect)))
))
(testing "accept terms"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))
connect (db/insert-user-terms ctx (:id registered-user) "accepted")]
(is (= "success" (:status connect)))
(is (= "accepted" (:input connect)))
))
(testing "check if accepted terms"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))
connect (db/get-accepted-terms-by-id ctx (:id registered-user))]
(is (= "accepted" connect))
))
(testing "activate email"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))
connect (db/verify-email-address ctx (:verification_key registered-user) (:id registered-user) false)]
(is (= "success" connect))))
(testing " check if activated"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))]
(is (:verified registered-user)))))
(testing "delete user"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))]
(testing " delete created user"
(let [connect (db/delete-user ctx (:id registered-user) (:password registration-data))]
(is (= "success" (:status connect)))))
(testing " check can login with user"
(let [login (db/login-user ctx (:email registration-data) (:password registration-data))]
(is (= "error" (:status login)))
(is (= "user/Loginfailed" (:message login)))))
(testing " check can login with user"
(let [emails (db/email-addresses ctx (:id registered-user))]
(is (= nil (:email (first emails)))))))))
;(migrator/run-test-reset)
(migrator/reset-seeds (migrator/test-config))
| 37704 | (ns salava.user.db-test
(:require [salava.user.db :as db]
[clojure.test :refer :all]
[salava.core.migrator :as migrator]
[salava.core.test-utils :as t]))
(def test-user {:id 1 :role "user" :private false})
(def registration-data
{:first_name "<NAME>"
:last_name "<NAME>"
:email "<EMAIL>"
:country "US"
:password "<PASSWORD>"
:language "fi"
:password_verify "<PASSWORD>"
})
(t/deftest-ctx main-test [ctx]
(testing "register user "
(testing "register user with correct data"
(let [connect (db/register-user ctx (:email registration-data) (:first_name registration-data) (:last_name registration-data) (:country registration-data) (:language registration-data) (:password registration-data) (:password_verify registration-data))]
(is (= "success" (:status connect)))
(is (= "" (:message connect)))
))
(testing "register user again with same data"
(let [connect (db/register-user ctx (:email registration-data) (:first_name registration-data) (:last_name registration-data) (:country registration-data) (:language registration-data) (:password registration-data) (:password_verify registration-data))]
(is (= "error" (:status connect)))
(is (= "user/Enteredaddressisalready" (:message connect)))
))
(testing "accept terms"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))
connect (db/insert-user-terms ctx (:id registered-user) "accepted")]
(is (= "success" (:status connect)))
(is (= "accepted" (:input connect)))
))
(testing "check if accepted terms"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))
connect (db/get-accepted-terms-by-id ctx (:id registered-user))]
(is (= "accepted" connect))
))
(testing "activate email"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))
connect (db/verify-email-address ctx (:verification_key registered-user) (:id registered-user) false)]
(is (= "success" connect))))
(testing " check if activated"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))]
(is (:verified registered-user)))))
(testing "delete user"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))]
(testing " delete created user"
(let [connect (db/delete-user ctx (:id registered-user) (:password registration-data))]
(is (= "success" (:status connect)))))
(testing " check can login with user"
(let [login (db/login-user ctx (:email registration-data) (:password registration-data))]
(is (= "error" (:status login)))
(is (= "user/Loginfailed" (:message login)))))
(testing " check can login with user"
(let [emails (db/email-addresses ctx (:id registered-user))]
(is (= nil (:email (first emails)))))))))
;(migrator/run-test-reset)
(migrator/reset-seeds (migrator/test-config))
| true | (ns salava.user.db-test
(:require [salava.user.db :as db]
[clojure.test :refer :all]
[salava.core.migrator :as migrator]
[salava.core.test-utils :as t]))
(def test-user {:id 1 :role "user" :private false})
(def registration-data
{:first_name "PI:NAME:<NAME>END_PI"
:last_name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:country "US"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:language "fi"
:password_verify "PI:PASSWORD:<PASSWORD>END_PI"
})
(t/deftest-ctx main-test [ctx]
(testing "register user "
(testing "register user with correct data"
(let [connect (db/register-user ctx (:email registration-data) (:first_name registration-data) (:last_name registration-data) (:country registration-data) (:language registration-data) (:password registration-data) (:password_verify registration-data))]
(is (= "success" (:status connect)))
(is (= "" (:message connect)))
))
(testing "register user again with same data"
(let [connect (db/register-user ctx (:email registration-data) (:first_name registration-data) (:last_name registration-data) (:country registration-data) (:language registration-data) (:password registration-data) (:password_verify registration-data))]
(is (= "error" (:status connect)))
(is (= "user/Enteredaddressisalready" (:message connect)))
))
(testing "accept terms"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))
connect (db/insert-user-terms ctx (:id registered-user) "accepted")]
(is (= "success" (:status connect)))
(is (= "accepted" (:input connect)))
))
(testing "check if accepted terms"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))
connect (db/get-accepted-terms-by-id ctx (:id registered-user))]
(is (= "accepted" connect))
))
(testing "activate email"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))
connect (db/verify-email-address ctx (:verification_key registered-user) (:id registered-user) false)]
(is (= "success" connect))))
(testing " check if activated"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))]
(is (:verified registered-user)))))
(testing "delete user"
(let [registered-user (db/get-user-by-email ctx (:email registration-data))]
(testing " delete created user"
(let [connect (db/delete-user ctx (:id registered-user) (:password registration-data))]
(is (= "success" (:status connect)))))
(testing " check can login with user"
(let [login (db/login-user ctx (:email registration-data) (:password registration-data))]
(is (= "error" (:status login)))
(is (= "user/Loginfailed" (:message login)))))
(testing " check can login with user"
(let [emails (db/email-addresses ctx (:id registered-user))]
(is (= nil (:email (first emails)))))))))
;(migrator/run-test-reset)
(migrator/reset-seeds (migrator/test-config))
|
[
{
"context": "bionic\"\n :key-url \"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x20D0BB61B700CE29\"}))\n\n(defn insta",
"end": 2351,
"score": 0.7501125335693359,
"start": 2320,
"tag": "KEY",
"value": "keyserver.ubuntu.com/pks/lookup"
},
{
"context": "://keyserver.ubuntu.com/pks/lookup?op=get&search=0x20D0BB61B700CE29\"}))\n\n(defn install-pdftk\n [facility]\n (actions/",
"end": 2384,
"score": 0.8759579062461853,
"start": 2367,
"tag": "KEY",
"value": "x20D0BB61B700CE29"
}
] | main/src/dda/pallet/dda_managed_vm/infra/office.clj | DomainDrivenArchitecture/dda-managed-vm | 5 | ; 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-managed-vm.infra.office
(:require
[clojure.tools.logging :as logging]
[schema.core :as s]
[selmer.parser :as selmer]
[pallet.actions :as actions]
[dda.config.commons.user-home :as user-env]))
(def FakturamaConfig
"The configuration for managed vms crate."
{:app-download-url s/Str
:doc-download-url s/Str})
(def Settings
(hash-set :install-libreoffice
:install-spellchecking-de
:install-inkscape
;:install-pdf-chain
:install-audio
:install-redshift))
(defn install-libreoffice
[facility]
(actions/as-action
(logging/info (str facility "-install system: libreoffice")))
(actions/package "libreoffice"))
(defn install-spellchecking-de
[facility]
(actions/as-action
(logging/info (str facility "-install system: spellchecking-de")))
(actions/packages :aptitude ["hyphen-de" "hunspell" "hunspell-de-de"]))
(defn install-inkscape
[facility]
(actions/as-action
(logging/info (str facility "-install system: inkscape")))
(actions/package "inkscape"))
; only gprename and a2ps are existant on ubuntu 18.04
(defn init-pdftk
[facility]
(actions/as-action
(logging/info (str facility "-init system: pdf-chain")))
(actions/package-source "pdftk-java"
:aptitude
{:url "http://ppa.launchpad.net/malteworld/ppa/ubuntu"
:scopes ["main"]
:release "bionic"
:key-url "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x20D0BB61B700CE29"}))
(defn install-pdftk
[facility]
(actions/as-action
(logging/info (str facility "-install system: pdf-chain")))
(actions/package-manager :update)
(actions/package "pdftk-java"))
(defn install-audio
[facility]
(actions/as-action
(logging/info (str facility "-install system: install-audio")))
(actions/packages :aptitude ["ubuntu-restricted-extras" "uudeview"
"xine-ui" "icedax" "easytag" "id3tool"
"lame" "nautilus-script-audio-convert" "libmad0"
"mpg321" "libavcodec-extra" "libdvd-pkg"]))
(s/defn install-fakturama
"get and install fakturama"
[facility
fakturama-config :- FakturamaConfig]
(actions/as-action
(logging/info (str facility "-install system: fakturama")))
(actions/remote-file
"/tmp/installer_fakturama_linux_64Bit.deb"
:url (get-in fakturama-config [:app-download-url]))
(actions/exec-checked-script
"install fakturama"
("dpkg" "-i" "/tmp/installer_fakturama_linux_64Bit.deb"))
(actions/directory
"/opt/fakturama-doc"
:owner "root"
:group "users"
:mode "755")
(actions/remote-file
"/opt/fakturama-doc/handbuch.pdf"
:literal true
:owner "root"
:group "users"
:mode "755"
:url (get-in fakturama-config [:doc-download-url])))
(defn install-redshift
[facility]
(actions/as-action
(logging/info (str facility "-install system: install-redshift")))
(actions/packages :aptitude ["redshift" "redshift-gtk"])
(actions/remote-file
"/etc/geoclue/geoclue.conf"
:literal true
:owner "root"
:group "root"
:mode "644"
:content (selmer/render-file "geoclue.conf.templ" {})))
(s/defn configure-user-redshift
[facility :- s/Keyword
user-name :- s/Str]
(actions/as-action
(logging/info (str facility "-configure user: configure-user-redshift")))
(let [user-home (user-env/user-home-dir user-name)]
(actions/directory
(str user-home "/.config")
:owner user-name
:group user-name
:mode "755")
(actions/remote-file
(str user-home "/.config/redshift.conf")
:literal true
:owner user-name
:group user-name
:mode "644"
:content (selmer/render-file "redshift.conf.templ" {}))))
(s/defn init-system
"install common used packages for vm"
[facility settings]
(when (contains? settings :install-pdf-chain)
(init-pdftk facility))
)
(s/defn install-system
"install common used packages for vm"
[facility config]
(let [{:keys [settings fakturama]} config]
(when (contains? settings :install-spellchecking-de)
(install-spellchecking-de facility))
(when (contains? settings :install-libreoffice)
(install-libreoffice facility))
(when (contains? settings :install-inkscape)
(install-inkscape facility))
(when (contains? settings :install-pdf-chain)
(install-pdftk facility))
(when (contains? settings :install-audio)
(install-audio facility))
(when (contains? config :fakturama)
(install-fakturama facility (get-in config [:fakturama])))
(when (contains? config :install-redshift)
(install-redshift facility))))
(s/defn configure-user
[facility :- s/Keyword
user-name :- s/Str
config]
(when (contains? config :install-redshift)
(configure-user-redshift facility user-name)))
| 4862 | ; 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-managed-vm.infra.office
(:require
[clojure.tools.logging :as logging]
[schema.core :as s]
[selmer.parser :as selmer]
[pallet.actions :as actions]
[dda.config.commons.user-home :as user-env]))
(def FakturamaConfig
"The configuration for managed vms crate."
{:app-download-url s/Str
:doc-download-url s/Str})
(def Settings
(hash-set :install-libreoffice
:install-spellchecking-de
:install-inkscape
;:install-pdf-chain
:install-audio
:install-redshift))
(defn install-libreoffice
[facility]
(actions/as-action
(logging/info (str facility "-install system: libreoffice")))
(actions/package "libreoffice"))
(defn install-spellchecking-de
[facility]
(actions/as-action
(logging/info (str facility "-install system: spellchecking-de")))
(actions/packages :aptitude ["hyphen-de" "hunspell" "hunspell-de-de"]))
(defn install-inkscape
[facility]
(actions/as-action
(logging/info (str facility "-install system: inkscape")))
(actions/package "inkscape"))
; only gprename and a2ps are existant on ubuntu 18.04
(defn init-pdftk
[facility]
(actions/as-action
(logging/info (str facility "-init system: pdf-chain")))
(actions/package-source "pdftk-java"
:aptitude
{:url "http://ppa.launchpad.net/malteworld/ppa/ubuntu"
:scopes ["main"]
:release "bionic"
:key-url "https://<KEY>?op=get&search=0<KEY>"}))
(defn install-pdftk
[facility]
(actions/as-action
(logging/info (str facility "-install system: pdf-chain")))
(actions/package-manager :update)
(actions/package "pdftk-java"))
(defn install-audio
[facility]
(actions/as-action
(logging/info (str facility "-install system: install-audio")))
(actions/packages :aptitude ["ubuntu-restricted-extras" "uudeview"
"xine-ui" "icedax" "easytag" "id3tool"
"lame" "nautilus-script-audio-convert" "libmad0"
"mpg321" "libavcodec-extra" "libdvd-pkg"]))
(s/defn install-fakturama
"get and install fakturama"
[facility
fakturama-config :- FakturamaConfig]
(actions/as-action
(logging/info (str facility "-install system: fakturama")))
(actions/remote-file
"/tmp/installer_fakturama_linux_64Bit.deb"
:url (get-in fakturama-config [:app-download-url]))
(actions/exec-checked-script
"install fakturama"
("dpkg" "-i" "/tmp/installer_fakturama_linux_64Bit.deb"))
(actions/directory
"/opt/fakturama-doc"
:owner "root"
:group "users"
:mode "755")
(actions/remote-file
"/opt/fakturama-doc/handbuch.pdf"
:literal true
:owner "root"
:group "users"
:mode "755"
:url (get-in fakturama-config [:doc-download-url])))
(defn install-redshift
[facility]
(actions/as-action
(logging/info (str facility "-install system: install-redshift")))
(actions/packages :aptitude ["redshift" "redshift-gtk"])
(actions/remote-file
"/etc/geoclue/geoclue.conf"
:literal true
:owner "root"
:group "root"
:mode "644"
:content (selmer/render-file "geoclue.conf.templ" {})))
(s/defn configure-user-redshift
[facility :- s/Keyword
user-name :- s/Str]
(actions/as-action
(logging/info (str facility "-configure user: configure-user-redshift")))
(let [user-home (user-env/user-home-dir user-name)]
(actions/directory
(str user-home "/.config")
:owner user-name
:group user-name
:mode "755")
(actions/remote-file
(str user-home "/.config/redshift.conf")
:literal true
:owner user-name
:group user-name
:mode "644"
:content (selmer/render-file "redshift.conf.templ" {}))))
(s/defn init-system
"install common used packages for vm"
[facility settings]
(when (contains? settings :install-pdf-chain)
(init-pdftk facility))
)
(s/defn install-system
"install common used packages for vm"
[facility config]
(let [{:keys [settings fakturama]} config]
(when (contains? settings :install-spellchecking-de)
(install-spellchecking-de facility))
(when (contains? settings :install-libreoffice)
(install-libreoffice facility))
(when (contains? settings :install-inkscape)
(install-inkscape facility))
(when (contains? settings :install-pdf-chain)
(install-pdftk facility))
(when (contains? settings :install-audio)
(install-audio facility))
(when (contains? config :fakturama)
(install-fakturama facility (get-in config [:fakturama])))
(when (contains? config :install-redshift)
(install-redshift facility))))
(s/defn configure-user
[facility :- s/Keyword
user-name :- s/Str
config]
(when (contains? config :install-redshift)
(configure-user-redshift facility user-name)))
| 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-managed-vm.infra.office
(:require
[clojure.tools.logging :as logging]
[schema.core :as s]
[selmer.parser :as selmer]
[pallet.actions :as actions]
[dda.config.commons.user-home :as user-env]))
(def FakturamaConfig
"The configuration for managed vms crate."
{:app-download-url s/Str
:doc-download-url s/Str})
(def Settings
(hash-set :install-libreoffice
:install-spellchecking-de
:install-inkscape
;:install-pdf-chain
:install-audio
:install-redshift))
(defn install-libreoffice
[facility]
(actions/as-action
(logging/info (str facility "-install system: libreoffice")))
(actions/package "libreoffice"))
(defn install-spellchecking-de
[facility]
(actions/as-action
(logging/info (str facility "-install system: spellchecking-de")))
(actions/packages :aptitude ["hyphen-de" "hunspell" "hunspell-de-de"]))
(defn install-inkscape
[facility]
(actions/as-action
(logging/info (str facility "-install system: inkscape")))
(actions/package "inkscape"))
; only gprename and a2ps are existant on ubuntu 18.04
(defn init-pdftk
[facility]
(actions/as-action
(logging/info (str facility "-init system: pdf-chain")))
(actions/package-source "pdftk-java"
:aptitude
{:url "http://ppa.launchpad.net/malteworld/ppa/ubuntu"
:scopes ["main"]
:release "bionic"
:key-url "https://PI:KEY:<KEY>END_PI?op=get&search=0PI:KEY:<KEY>END_PI"}))
(defn install-pdftk
[facility]
(actions/as-action
(logging/info (str facility "-install system: pdf-chain")))
(actions/package-manager :update)
(actions/package "pdftk-java"))
(defn install-audio
[facility]
(actions/as-action
(logging/info (str facility "-install system: install-audio")))
(actions/packages :aptitude ["ubuntu-restricted-extras" "uudeview"
"xine-ui" "icedax" "easytag" "id3tool"
"lame" "nautilus-script-audio-convert" "libmad0"
"mpg321" "libavcodec-extra" "libdvd-pkg"]))
(s/defn install-fakturama
"get and install fakturama"
[facility
fakturama-config :- FakturamaConfig]
(actions/as-action
(logging/info (str facility "-install system: fakturama")))
(actions/remote-file
"/tmp/installer_fakturama_linux_64Bit.deb"
:url (get-in fakturama-config [:app-download-url]))
(actions/exec-checked-script
"install fakturama"
("dpkg" "-i" "/tmp/installer_fakturama_linux_64Bit.deb"))
(actions/directory
"/opt/fakturama-doc"
:owner "root"
:group "users"
:mode "755")
(actions/remote-file
"/opt/fakturama-doc/handbuch.pdf"
:literal true
:owner "root"
:group "users"
:mode "755"
:url (get-in fakturama-config [:doc-download-url])))
(defn install-redshift
[facility]
(actions/as-action
(logging/info (str facility "-install system: install-redshift")))
(actions/packages :aptitude ["redshift" "redshift-gtk"])
(actions/remote-file
"/etc/geoclue/geoclue.conf"
:literal true
:owner "root"
:group "root"
:mode "644"
:content (selmer/render-file "geoclue.conf.templ" {})))
(s/defn configure-user-redshift
[facility :- s/Keyword
user-name :- s/Str]
(actions/as-action
(logging/info (str facility "-configure user: configure-user-redshift")))
(let [user-home (user-env/user-home-dir user-name)]
(actions/directory
(str user-home "/.config")
:owner user-name
:group user-name
:mode "755")
(actions/remote-file
(str user-home "/.config/redshift.conf")
:literal true
:owner user-name
:group user-name
:mode "644"
:content (selmer/render-file "redshift.conf.templ" {}))))
(s/defn init-system
"install common used packages for vm"
[facility settings]
(when (contains? settings :install-pdf-chain)
(init-pdftk facility))
)
(s/defn install-system
"install common used packages for vm"
[facility config]
(let [{:keys [settings fakturama]} config]
(when (contains? settings :install-spellchecking-de)
(install-spellchecking-de facility))
(when (contains? settings :install-libreoffice)
(install-libreoffice facility))
(when (contains? settings :install-inkscape)
(install-inkscape facility))
(when (contains? settings :install-pdf-chain)
(install-pdftk facility))
(when (contains? settings :install-audio)
(install-audio facility))
(when (contains? config :fakturama)
(install-fakturama facility (get-in config [:fakturama])))
(when (contains? config :install-redshift)
(install-redshift facility))))
(s/defn configure-user
[facility :- s/Keyword
user-name :- s/Str
config]
(when (contains? config :install-redshift)
(configure-user-redshift facility user-name)))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998193979263306,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
}
] | ext/clojure-clojurescript-bef56a7/samples/twitterbuzz/src/twitterbuzz/layout.cljs | yokolet/clementine | 35 | ; 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 twitterbuzz.layout
(:require [twitterbuzz.anneal :as ann]
[twitterbuzz.radial :as rad]
[goog.math :as math]))
(defn random-loc []
{:x (ann/random) :y (ann/random)})
(defn sqr [x]
(* x x))
(defn sqrt [x]
(js/Math.sqrt x))
(defn dist [{x1 :x y1 :y} {x2 :x y2 :y}]
(sqrt (+ (sqr (- x2 x1)) (sqr (- y2 y1)))))
(defn init-state [mentions-data]
(let [connected (reduce (fn [ret [k {:keys [mentions]}]]
(if (pos? (count mentions))
(into (conj ret k) (keys mentions))
ret))
#{} mentions-data)
mentions-data (select-keys mentions-data connected)]
{:locs (zipmap connected (repeatedly #(random-loc)))
:mentions mentions-data}))
(defn roots [mentions-data]
(let [parents (reduce (fn [ret [k {:keys [mentions]}]]
(if (pos? (count mentions))
(conj ret k)
ret))
#{} mentions-data)]
(reduce disj parents (mapcat #(keys (:mentions %)) (vals mentions-data)))))
(defn radial
[mentions-data]
(let [mentions #(rad/get-mentions mentions-data %)
weights (rad/weights
(into (set (roots mentions-data)) (mapcat mentions (keys mentions-data)))
mentions)]
{:mentions mentions-data
:locs (-> (rad/layout (roots mentions-data) weights mentions)
(rad/polar->cartesian 3))}))
(defn score [{:keys [locs mentions]}]
(let [metric (fn [d w] (sqr (- 1 (* d w))))
score-user (fn [[k {:keys [mentions]}]]
(if (zero? (count mentions))
0
(let [loc (locs k)]
(reduce (fn [score [ok w]]
(+ score (metric (dist loc (locs ok)) w)))
0
mentions))))]
(reduce + (map score-user mentions))))
(defn permute-swap [{:keys [locs mentions]} t]
;;first cut - swap
(let [xys (vec (vals locs))
swap1 (math/randomInt (count xys))
swap2 (math/randomInt (count xys))
temp (xys swap1)
xys (assoc xys swap1 (xys swap2))
xys (assoc xys swap2 temp)]
{:locs (zipmap (keys locs) xys)
:mentions mentions}))
(defn permute-move [{:keys [locs mentions]} t]
(let [adj #(min 1.0 (max 0 (+ % (- (* (ann/random) 0.1) 0.05))))
move (fn [{:keys [x y] :as loc}]
(if true ;;(> (ann/random) 0.8)
{:x (adj x)
:y (adj y)}
loc))
xys (vec (vals locs))]
{:locs (zipmap (keys locs) (map move (vals locs)))
:mentions mentions}))
(comment
(def test-data {})
(def init (init-state test-data))
(map (fn [x] {:best-score (:best-score x) :t (:t x)})
(take 10 (take-nth 100
(ann/anneal score
(ann/linear-cooling 1000)
permute-move
ann/standard-prob
init))))
)
| 116530 | ; 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 twitterbuzz.layout
(:require [twitterbuzz.anneal :as ann]
[twitterbuzz.radial :as rad]
[goog.math :as math]))
(defn random-loc []
{:x (ann/random) :y (ann/random)})
(defn sqr [x]
(* x x))
(defn sqrt [x]
(js/Math.sqrt x))
(defn dist [{x1 :x y1 :y} {x2 :x y2 :y}]
(sqrt (+ (sqr (- x2 x1)) (sqr (- y2 y1)))))
(defn init-state [mentions-data]
(let [connected (reduce (fn [ret [k {:keys [mentions]}]]
(if (pos? (count mentions))
(into (conj ret k) (keys mentions))
ret))
#{} mentions-data)
mentions-data (select-keys mentions-data connected)]
{:locs (zipmap connected (repeatedly #(random-loc)))
:mentions mentions-data}))
(defn roots [mentions-data]
(let [parents (reduce (fn [ret [k {:keys [mentions]}]]
(if (pos? (count mentions))
(conj ret k)
ret))
#{} mentions-data)]
(reduce disj parents (mapcat #(keys (:mentions %)) (vals mentions-data)))))
(defn radial
[mentions-data]
(let [mentions #(rad/get-mentions mentions-data %)
weights (rad/weights
(into (set (roots mentions-data)) (mapcat mentions (keys mentions-data)))
mentions)]
{:mentions mentions-data
:locs (-> (rad/layout (roots mentions-data) weights mentions)
(rad/polar->cartesian 3))}))
(defn score [{:keys [locs mentions]}]
(let [metric (fn [d w] (sqr (- 1 (* d w))))
score-user (fn [[k {:keys [mentions]}]]
(if (zero? (count mentions))
0
(let [loc (locs k)]
(reduce (fn [score [ok w]]
(+ score (metric (dist loc (locs ok)) w)))
0
mentions))))]
(reduce + (map score-user mentions))))
(defn permute-swap [{:keys [locs mentions]} t]
;;first cut - swap
(let [xys (vec (vals locs))
swap1 (math/randomInt (count xys))
swap2 (math/randomInt (count xys))
temp (xys swap1)
xys (assoc xys swap1 (xys swap2))
xys (assoc xys swap2 temp)]
{:locs (zipmap (keys locs) xys)
:mentions mentions}))
(defn permute-move [{:keys [locs mentions]} t]
(let [adj #(min 1.0 (max 0 (+ % (- (* (ann/random) 0.1) 0.05))))
move (fn [{:keys [x y] :as loc}]
(if true ;;(> (ann/random) 0.8)
{:x (adj x)
:y (adj y)}
loc))
xys (vec (vals locs))]
{:locs (zipmap (keys locs) (map move (vals locs)))
:mentions mentions}))
(comment
(def test-data {})
(def init (init-state test-data))
(map (fn [x] {:best-score (:best-score x) :t (:t x)})
(take 10 (take-nth 100
(ann/anneal score
(ann/linear-cooling 1000)
permute-move
ann/standard-prob
init))))
)
| 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 twitterbuzz.layout
(:require [twitterbuzz.anneal :as ann]
[twitterbuzz.radial :as rad]
[goog.math :as math]))
(defn random-loc []
{:x (ann/random) :y (ann/random)})
(defn sqr [x]
(* x x))
(defn sqrt [x]
(js/Math.sqrt x))
(defn dist [{x1 :x y1 :y} {x2 :x y2 :y}]
(sqrt (+ (sqr (- x2 x1)) (sqr (- y2 y1)))))
(defn init-state [mentions-data]
(let [connected (reduce (fn [ret [k {:keys [mentions]}]]
(if (pos? (count mentions))
(into (conj ret k) (keys mentions))
ret))
#{} mentions-data)
mentions-data (select-keys mentions-data connected)]
{:locs (zipmap connected (repeatedly #(random-loc)))
:mentions mentions-data}))
(defn roots [mentions-data]
(let [parents (reduce (fn [ret [k {:keys [mentions]}]]
(if (pos? (count mentions))
(conj ret k)
ret))
#{} mentions-data)]
(reduce disj parents (mapcat #(keys (:mentions %)) (vals mentions-data)))))
(defn radial
[mentions-data]
(let [mentions #(rad/get-mentions mentions-data %)
weights (rad/weights
(into (set (roots mentions-data)) (mapcat mentions (keys mentions-data)))
mentions)]
{:mentions mentions-data
:locs (-> (rad/layout (roots mentions-data) weights mentions)
(rad/polar->cartesian 3))}))
(defn score [{:keys [locs mentions]}]
(let [metric (fn [d w] (sqr (- 1 (* d w))))
score-user (fn [[k {:keys [mentions]}]]
(if (zero? (count mentions))
0
(let [loc (locs k)]
(reduce (fn [score [ok w]]
(+ score (metric (dist loc (locs ok)) w)))
0
mentions))))]
(reduce + (map score-user mentions))))
(defn permute-swap [{:keys [locs mentions]} t]
;;first cut - swap
(let [xys (vec (vals locs))
swap1 (math/randomInt (count xys))
swap2 (math/randomInt (count xys))
temp (xys swap1)
xys (assoc xys swap1 (xys swap2))
xys (assoc xys swap2 temp)]
{:locs (zipmap (keys locs) xys)
:mentions mentions}))
(defn permute-move [{:keys [locs mentions]} t]
(let [adj #(min 1.0 (max 0 (+ % (- (* (ann/random) 0.1) 0.05))))
move (fn [{:keys [x y] :as loc}]
(if true ;;(> (ann/random) 0.8)
{:x (adj x)
:y (adj y)}
loc))
xys (vec (vals locs))]
{:locs (zipmap (keys locs) (map move (vals locs)))
:mentions mentions}))
(comment
(def test-data {})
(def init (init-state test-data))
(map (fn [x] {:best-score (:best-score x) :t (:t x)})
(take 10 (take-nth 100
(ann/anneal score
(ann/linear-cooling 1000)
permute-move
ann/standard-prob
init))))
)
|
[
{
"context": "build-up database connection source \n;; \n;; Autor: Christian Meichsner\r\n\r\n(ns org.lambdaroyal.util.db.dbconfig\n (:requi",
"end": 106,
"score": 0.9998174905776978,
"start": 87,
"tag": "NAME",
"value": "Christian Meichsner"
}
] | src/main/clojure/org/lambdaroyal/util/db/dbconfig.clj | gixxi/clojure-util | 1 | ;; Aspect Read DB configuration and build-up database connection source
;;
;; Autor: Christian Meichsner
(ns org.lambdaroyal.util.db.dbconfig
(:require [clojure.java.io :as io])
(:import [java.io PushbackReader])
(:gen-class))
(defn conf [file]
"Liesst ein Konfigurationsfile ein, welches einer Assoziativen Liste entspricht"
(binding [*read-eval* false]
(with-open [r (io/reader file)]
(read (PushbackReader. r)))))
(defn datasource [file]
"Liesst ein Konfigurationsfile ein, und erstellt anhand dieses eine gepoolte JDBC Datasource"
(let
[config (conf file) ds (new org.apache.tomcat.jdbc.pool.DataSource) pp (new org.apache.tomcat.jdbc.pool.PoolProperties)]
(do
(println (str "setup datasource using " config))
(.setDriverClassName pp (:classname config))
(.setUrl pp (:subname config))
(.setUsername pp (:user config))
(.setPassword pp (:password config))
(.setTestOnBorrow pp true)
(.setValidationQuery pp "SELECT 1")
(.setMaxActive pp 5)
(.setInitialSize pp 1)
(.setMaxWait pp 10000)
(.setPoolProperties ds pp)
(identity ds))))
(defn datasource-from-filename [filename]
(datasource (clojure.java.io/as-file filename)))
| 42238 | ;; Aspect Read DB configuration and build-up database connection source
;;
;; Autor: <NAME>
(ns org.lambdaroyal.util.db.dbconfig
(:require [clojure.java.io :as io])
(:import [java.io PushbackReader])
(:gen-class))
(defn conf [file]
"Liesst ein Konfigurationsfile ein, welches einer Assoziativen Liste entspricht"
(binding [*read-eval* false]
(with-open [r (io/reader file)]
(read (PushbackReader. r)))))
(defn datasource [file]
"Liesst ein Konfigurationsfile ein, und erstellt anhand dieses eine gepoolte JDBC Datasource"
(let
[config (conf file) ds (new org.apache.tomcat.jdbc.pool.DataSource) pp (new org.apache.tomcat.jdbc.pool.PoolProperties)]
(do
(println (str "setup datasource using " config))
(.setDriverClassName pp (:classname config))
(.setUrl pp (:subname config))
(.setUsername pp (:user config))
(.setPassword pp (:password config))
(.setTestOnBorrow pp true)
(.setValidationQuery pp "SELECT 1")
(.setMaxActive pp 5)
(.setInitialSize pp 1)
(.setMaxWait pp 10000)
(.setPoolProperties ds pp)
(identity ds))))
(defn datasource-from-filename [filename]
(datasource (clojure.java.io/as-file filename)))
| true | ;; Aspect Read DB configuration and build-up database connection source
;;
;; Autor: PI:NAME:<NAME>END_PI
(ns org.lambdaroyal.util.db.dbconfig
(:require [clojure.java.io :as io])
(:import [java.io PushbackReader])
(:gen-class))
(defn conf [file]
"Liesst ein Konfigurationsfile ein, welches einer Assoziativen Liste entspricht"
(binding [*read-eval* false]
(with-open [r (io/reader file)]
(read (PushbackReader. r)))))
(defn datasource [file]
"Liesst ein Konfigurationsfile ein, und erstellt anhand dieses eine gepoolte JDBC Datasource"
(let
[config (conf file) ds (new org.apache.tomcat.jdbc.pool.DataSource) pp (new org.apache.tomcat.jdbc.pool.PoolProperties)]
(do
(println (str "setup datasource using " config))
(.setDriverClassName pp (:classname config))
(.setUrl pp (:subname config))
(.setUsername pp (:user config))
(.setPassword pp (:password config))
(.setTestOnBorrow pp true)
(.setValidationQuery pp "SELECT 1")
(.setMaxActive pp 5)
(.setInitialSize pp 1)
(.setMaxWait pp 10000)
(.setPoolProperties ds pp)
(identity ds))))
(defn datasource-from-filename [filename]
(datasource (clojure.java.io/as-file filename)))
|
[
{
"context": "\n (.setPassword password)\n (.signUp)))]",
"end": 1652,
"score": 0.981672465801239,
"start": 1644,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "d\" \"createdAt\" \"sessionToken\" \"objectId\" \"email\" \"username\" \"updatedAt\" \"webpointer\")\n (assoc \"succes",
"end": 4225,
"score": 0.9995284080505371,
"start": 4217,
"tag": "USERNAME",
"value": "username"
}
] | src/main/clojure/core/sign_up.clj | MSC-XDU/Home-Backend | 2 | (ns core.sign-up
(:use leanengine.base
leanengine.query
leanengine.file
leanengine.object
clojure.tools.logging
[clojure.data.json :only [write-str read-str]]
[ring.util.codec :only (url-encode)]
[medley.core :only (map-keys)])
(:require [clj-http.client :as client])
(:import [com.avos.avoscloud AVUser AVException AVFile AVObject]))
(defmacro ^:private wrap-try
[& body]
`(try
~@body
(catch AVException e#
(error (.getCode e#))
{:success? false :error (.getMessage e#)})))
(defn user-exist?
"给定邮箱查看用户是否存在"
[username]
(try
{:success? true
:exist? (-> (client/get "https://api.leancloud.cn/1.1/users"
{:headers {"X-LC-Id" (System/getenv "LEANCLOUD_APP_ID")
"X-LC-Sign" (get-sign :master)}
:as :json
:content-type :json
:accept :json
:query-params {"where" (write-str {:username username})
"limit" 1}})
(:body)
(:results)
(#(or (empty? %) (nil? %)))
(not))}
(catch Exception e
{:success? false})))
(defn sign-up
[^String e-mail ^String password]
(wrap-try
(let [token (.getSessionToken (doto (AVUser.)
(.setUsername e-mail)
(.setEmail e-mail)
(.setPassword password)
(.signUp)))]
{:success? true :token token})))
(defn log-in
[^String e-mail ^String password]
(wrap-try
{:success? true :token (.getSessionToken (AVUser/logIn e-mail password))}))
(defn set-phone
[^String phone]
(wrap-try
(let [user (AVUser/getCurrentUser)]
(if-not (.getBoolean (.fetch user) "mobilePhoneVerified")
(do
(.setMobilePhoneNumber user phone)
(.save user)))
{:success? true})))
(defn request-phone-verify
[^String phone]
(wrap-try
(AVUser/requestMobilePhoneVerify phone)
{:success? true}))
(defn verify-phone
[^String code]
(wrap-try
(AVUser/verifyMobilePhone code)
{:success? true}))
(defn set-base-info
[info ^AVUser user]
(wrap-try
(let [phone (info :phone)
info (dissoc info :phone)]
(-> user
(put-object info)
(save-object))
(set-phone phone)
{:success? true})))
(defn set-sign-up-info
[info ^AVUser user]
(wrap-try
(let [form (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-first))]
(if-not (nil? form)
(do
(-> (put-object form info)
(save-object))
{:success? true})
(do
(-> (avos-object "SignUp")
(put-object info)
(put-object ["user" user])
(save-object))
{:success? true :files []})))))
(defn get-sign-up-info
[^AVUser user]
(wrap-try
(try
(let [info ^AVObject (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-include "files")
(query-first))
files (:files (get-slot info ["files" :seq]))
files (map (fn [file] {:name (file "originalName")
:url (file "url")
:id (file "objectId")
:loading false}) files)]
(-> (.toJSONObject info)
(.toString)
(read-str)
(assoc "files" files)
(assoc "success?" true)
(dissoc "className" "createdAt" "objectId" "updatedAt" "user")))
(catch NullPointerException e
{:success? true}))))
(defn get-base-info
[^AVUser user]
(wrap-try
(-> user
(.toJSONObject)
(.toString)
(read-str)
(dissoc "className" "emailVerified" "createdAt" "sessionToken" "objectId" "email" "username" "updatedAt" "webpointer")
(assoc "success?" true))))
(defn save-file
[file ^AVUser user]
(wrap-try
(let [name (:filename file)
file ^AVFile (save-file-bytes name (:bytes file))
info (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-first))
info (if (nil? info) (-> (avos-object "SignUp")
(put-object ["user" user])
(save-object))
info)]
(.add info "files" file)
(save-object info)
{:success? true
:name name
:id (.getObjectId file)
:url (.getUrl file)})))
(defn delete-file
[^String id ^AVUser user]
(wrap-try
(let [file ^AVFile (-> (avos-query "_File")
(.get id))
user (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-first))]
(.removeAll user "files" [file])
(save-object user)
{:success? true})))
| 119483 | (ns core.sign-up
(:use leanengine.base
leanengine.query
leanengine.file
leanengine.object
clojure.tools.logging
[clojure.data.json :only [write-str read-str]]
[ring.util.codec :only (url-encode)]
[medley.core :only (map-keys)])
(:require [clj-http.client :as client])
(:import [com.avos.avoscloud AVUser AVException AVFile AVObject]))
(defmacro ^:private wrap-try
[& body]
`(try
~@body
(catch AVException e#
(error (.getCode e#))
{:success? false :error (.getMessage e#)})))
(defn user-exist?
"给定邮箱查看用户是否存在"
[username]
(try
{:success? true
:exist? (-> (client/get "https://api.leancloud.cn/1.1/users"
{:headers {"X-LC-Id" (System/getenv "LEANCLOUD_APP_ID")
"X-LC-Sign" (get-sign :master)}
:as :json
:content-type :json
:accept :json
:query-params {"where" (write-str {:username username})
"limit" 1}})
(:body)
(:results)
(#(or (empty? %) (nil? %)))
(not))}
(catch Exception e
{:success? false})))
(defn sign-up
[^String e-mail ^String password]
(wrap-try
(let [token (.getSessionToken (doto (AVUser.)
(.setUsername e-mail)
(.setEmail e-mail)
(.setPassword <PASSWORD>)
(.signUp)))]
{:success? true :token token})))
(defn log-in
[^String e-mail ^String password]
(wrap-try
{:success? true :token (.getSessionToken (AVUser/logIn e-mail password))}))
(defn set-phone
[^String phone]
(wrap-try
(let [user (AVUser/getCurrentUser)]
(if-not (.getBoolean (.fetch user) "mobilePhoneVerified")
(do
(.setMobilePhoneNumber user phone)
(.save user)))
{:success? true})))
(defn request-phone-verify
[^String phone]
(wrap-try
(AVUser/requestMobilePhoneVerify phone)
{:success? true}))
(defn verify-phone
[^String code]
(wrap-try
(AVUser/verifyMobilePhone code)
{:success? true}))
(defn set-base-info
[info ^AVUser user]
(wrap-try
(let [phone (info :phone)
info (dissoc info :phone)]
(-> user
(put-object info)
(save-object))
(set-phone phone)
{:success? true})))
(defn set-sign-up-info
[info ^AVUser user]
(wrap-try
(let [form (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-first))]
(if-not (nil? form)
(do
(-> (put-object form info)
(save-object))
{:success? true})
(do
(-> (avos-object "SignUp")
(put-object info)
(put-object ["user" user])
(save-object))
{:success? true :files []})))))
(defn get-sign-up-info
[^AVUser user]
(wrap-try
(try
(let [info ^AVObject (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-include "files")
(query-first))
files (:files (get-slot info ["files" :seq]))
files (map (fn [file] {:name (file "originalName")
:url (file "url")
:id (file "objectId")
:loading false}) files)]
(-> (.toJSONObject info)
(.toString)
(read-str)
(assoc "files" files)
(assoc "success?" true)
(dissoc "className" "createdAt" "objectId" "updatedAt" "user")))
(catch NullPointerException e
{:success? true}))))
(defn get-base-info
[^AVUser user]
(wrap-try
(-> user
(.toJSONObject)
(.toString)
(read-str)
(dissoc "className" "emailVerified" "createdAt" "sessionToken" "objectId" "email" "username" "updatedAt" "webpointer")
(assoc "success?" true))))
(defn save-file
[file ^AVUser user]
(wrap-try
(let [name (:filename file)
file ^AVFile (save-file-bytes name (:bytes file))
info (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-first))
info (if (nil? info) (-> (avos-object "SignUp")
(put-object ["user" user])
(save-object))
info)]
(.add info "files" file)
(save-object info)
{:success? true
:name name
:id (.getObjectId file)
:url (.getUrl file)})))
(defn delete-file
[^String id ^AVUser user]
(wrap-try
(let [file ^AVFile (-> (avos-query "_File")
(.get id))
user (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-first))]
(.removeAll user "files" [file])
(save-object user)
{:success? true})))
| true | (ns core.sign-up
(:use leanengine.base
leanengine.query
leanengine.file
leanengine.object
clojure.tools.logging
[clojure.data.json :only [write-str read-str]]
[ring.util.codec :only (url-encode)]
[medley.core :only (map-keys)])
(:require [clj-http.client :as client])
(:import [com.avos.avoscloud AVUser AVException AVFile AVObject]))
(defmacro ^:private wrap-try
[& body]
`(try
~@body
(catch AVException e#
(error (.getCode e#))
{:success? false :error (.getMessage e#)})))
(defn user-exist?
"给定邮箱查看用户是否存在"
[username]
(try
{:success? true
:exist? (-> (client/get "https://api.leancloud.cn/1.1/users"
{:headers {"X-LC-Id" (System/getenv "LEANCLOUD_APP_ID")
"X-LC-Sign" (get-sign :master)}
:as :json
:content-type :json
:accept :json
:query-params {"where" (write-str {:username username})
"limit" 1}})
(:body)
(:results)
(#(or (empty? %) (nil? %)))
(not))}
(catch Exception e
{:success? false})))
(defn sign-up
[^String e-mail ^String password]
(wrap-try
(let [token (.getSessionToken (doto (AVUser.)
(.setUsername e-mail)
(.setEmail e-mail)
(.setPassword PI:PASSWORD:<PASSWORD>END_PI)
(.signUp)))]
{:success? true :token token})))
(defn log-in
[^String e-mail ^String password]
(wrap-try
{:success? true :token (.getSessionToken (AVUser/logIn e-mail password))}))
(defn set-phone
[^String phone]
(wrap-try
(let [user (AVUser/getCurrentUser)]
(if-not (.getBoolean (.fetch user) "mobilePhoneVerified")
(do
(.setMobilePhoneNumber user phone)
(.save user)))
{:success? true})))
(defn request-phone-verify
[^String phone]
(wrap-try
(AVUser/requestMobilePhoneVerify phone)
{:success? true}))
(defn verify-phone
[^String code]
(wrap-try
(AVUser/verifyMobilePhone code)
{:success? true}))
(defn set-base-info
[info ^AVUser user]
(wrap-try
(let [phone (info :phone)
info (dissoc info :phone)]
(-> user
(put-object info)
(save-object))
(set-phone phone)
{:success? true})))
(defn set-sign-up-info
[info ^AVUser user]
(wrap-try
(let [form (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-first))]
(if-not (nil? form)
(do
(-> (put-object form info)
(save-object))
{:success? true})
(do
(-> (avos-object "SignUp")
(put-object info)
(put-object ["user" user])
(save-object))
{:success? true :files []})))))
(defn get-sign-up-info
[^AVUser user]
(wrap-try
(try
(let [info ^AVObject (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-include "files")
(query-first))
files (:files (get-slot info ["files" :seq]))
files (map (fn [file] {:name (file "originalName")
:url (file "url")
:id (file "objectId")
:loading false}) files)]
(-> (.toJSONObject info)
(.toString)
(read-str)
(assoc "files" files)
(assoc "success?" true)
(dissoc "className" "createdAt" "objectId" "updatedAt" "user")))
(catch NullPointerException e
{:success? true}))))
(defn get-base-info
[^AVUser user]
(wrap-try
(-> user
(.toJSONObject)
(.toString)
(read-str)
(dissoc "className" "emailVerified" "createdAt" "sessionToken" "objectId" "email" "username" "updatedAt" "webpointer")
(assoc "success?" true))))
(defn save-file
[file ^AVUser user]
(wrap-try
(let [name (:filename file)
file ^AVFile (save-file-bytes name (:bytes file))
info (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-first))
info (if (nil? info) (-> (avos-object "SignUp")
(put-object ["user" user])
(save-object))
info)]
(.add info "files" file)
(save-object info)
{:success? true
:name name
:id (.getObjectId file)
:url (.getUrl file)})))
(defn delete-file
[^String id ^AVUser user]
(wrap-try
(let [file ^AVFile (-> (avos-query "_File")
(.get id))
user (-> (avos-query "SignUp")
(query-object ["user" := user])
(query-first))]
(.removeAll user "files" [file])
(save-object user)
{:success? true})))
|
[
{
"context": "\"Benchmarks for sums of double[].\"\n \n {:author \"palisades dot lakes at gmail dot com\"\n :since \"2017-04-06\"\n :version \"2017-05-29\"}",
"end": 290,
"score": 0.9636661410331726,
"start": 254,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] | src/scripts/clojure/palisades/lakes/elements/scripts/numbers/sum/algorithms.clj | palisades-lakes/les-elemens | 0 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.elements.scripts.numbers.sum.algorithms
"Benchmarks for sums of double[]."
{:author "palisades dot lakes at gmail dot com"
:since "2017-04-06"
:version "2017-05-29"}
(:require [clojure.set :as set]
[clojure.string :as s]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[palisades.lakes.elements.api :as mc]
[palisades.lakes.elements.scripts.defs :as defs]
[palisades.lakes.elements.scripts.numbers.sum.bench :as bench]))
;;----------------------------------------------------------------
(defn fname [generator n ext]
(str "algorithms."
(mc/fn-name generator)
"." n
"." (java.time.LocalDate/now) "." ext))
;;----------------------------------------------------------------
(time
(doseq [generator [#_mc/random-doubles-nonnegative
#_mc/random-doubles
#_mc/random-doubles-minus-mean
mc/random-doubles-zero-sum]]
(doseq [n (take 1 (bench/data-sizes))]
(println (mc/fn-name generator)
n
(.toString (java.time.LocalDateTime/now)))
(time
(with-open [w (io/writer
(defs/log-file
*ns* (fname generator n "txt")))]
(binding [*out* w]
(let [data-map (bench/data generator n)]
(reduce
(fn [records record]
(if record
(let [records (conj records record)]
(mc/write-tsv
records
(defs/data-file *ns* (fname generator n "tsv")))
records)
records))
[]
(for [f [#_mc/sum-zhu-hayes-exact
mc/sum-zhu-hayes-branch
mc/sum-zhu-hayes-nobranch
#_mc/sum-ifast
#_mc/sum-naive
#_mc/sum-naive-accumulator
mc/sum-pairwise
#_mc/sum-kahan
#_mc/sum-kahan-accumulator]]
(bench/bench f identity data-map))))))))))
;;----------------------------------------------------------------
| 98188 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.elements.scripts.numbers.sum.algorithms
"Benchmarks for sums of double[]."
{:author "<EMAIL>"
:since "2017-04-06"
:version "2017-05-29"}
(:require [clojure.set :as set]
[clojure.string :as s]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[palisades.lakes.elements.api :as mc]
[palisades.lakes.elements.scripts.defs :as defs]
[palisades.lakes.elements.scripts.numbers.sum.bench :as bench]))
;;----------------------------------------------------------------
(defn fname [generator n ext]
(str "algorithms."
(mc/fn-name generator)
"." n
"." (java.time.LocalDate/now) "." ext))
;;----------------------------------------------------------------
(time
(doseq [generator [#_mc/random-doubles-nonnegative
#_mc/random-doubles
#_mc/random-doubles-minus-mean
mc/random-doubles-zero-sum]]
(doseq [n (take 1 (bench/data-sizes))]
(println (mc/fn-name generator)
n
(.toString (java.time.LocalDateTime/now)))
(time
(with-open [w (io/writer
(defs/log-file
*ns* (fname generator n "txt")))]
(binding [*out* w]
(let [data-map (bench/data generator n)]
(reduce
(fn [records record]
(if record
(let [records (conj records record)]
(mc/write-tsv
records
(defs/data-file *ns* (fname generator n "tsv")))
records)
records))
[]
(for [f [#_mc/sum-zhu-hayes-exact
mc/sum-zhu-hayes-branch
mc/sum-zhu-hayes-nobranch
#_mc/sum-ifast
#_mc/sum-naive
#_mc/sum-naive-accumulator
mc/sum-pairwise
#_mc/sum-kahan
#_mc/sum-kahan-accumulator]]
(bench/bench f identity data-map))))))))))
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.elements.scripts.numbers.sum.algorithms
"Benchmarks for sums of double[]."
{:author "PI:EMAIL:<EMAIL>END_PI"
:since "2017-04-06"
:version "2017-05-29"}
(:require [clojure.set :as set]
[clojure.string :as s]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[palisades.lakes.elements.api :as mc]
[palisades.lakes.elements.scripts.defs :as defs]
[palisades.lakes.elements.scripts.numbers.sum.bench :as bench]))
;;----------------------------------------------------------------
(defn fname [generator n ext]
(str "algorithms."
(mc/fn-name generator)
"." n
"." (java.time.LocalDate/now) "." ext))
;;----------------------------------------------------------------
(time
(doseq [generator [#_mc/random-doubles-nonnegative
#_mc/random-doubles
#_mc/random-doubles-minus-mean
mc/random-doubles-zero-sum]]
(doseq [n (take 1 (bench/data-sizes))]
(println (mc/fn-name generator)
n
(.toString (java.time.LocalDateTime/now)))
(time
(with-open [w (io/writer
(defs/log-file
*ns* (fname generator n "txt")))]
(binding [*out* w]
(let [data-map (bench/data generator n)]
(reduce
(fn [records record]
(if record
(let [records (conj records record)]
(mc/write-tsv
records
(defs/data-file *ns* (fname generator n "tsv")))
records)
records))
[]
(for [f [#_mc/sum-zhu-hayes-exact
mc/sum-zhu-hayes-branch
mc/sum-zhu-hayes-nobranch
#_mc/sum-ifast
#_mc/sum-naive
#_mc/sum-naive-accumulator
mc/sum-pairwise
#_mc/sum-kahan
#_mc/sum-kahan-accumulator]]
(bench/bench f identity data-map))))))))))
;;----------------------------------------------------------------
|
[
{
"context": "ile is part of tempest-cljs\n;; Copyright (c) 2012, Trevor Bentley\n;; All rights reserved.\n;; See LICENSE file for d",
"end": 77,
"score": 0.9998579025268555,
"start": 63,
"tag": "NAME",
"value": "Trevor Bentley"
}
] | tempest/tempest/core.cljs | mrmekon/tempest-cljs | 5 | ;;
;; This file is part of tempest-cljs
;; Copyright (c) 2012, Trevor Bentley
;; All rights reserved.
;; See LICENSE file for details.
;;
(ns ^{:doc "
Functions related to the game of tempest, and game state.
Functions in this module create the game state, and modify it based on
player actions or time. This includes management of entities such as
the player's ship, enemies, and projectiles.
Enemy types:
* **Flipper** -- Moves quickly up level, flips randomly to adjacent segments,
and shoots. When a flipper reaches the outer edge, he flips endlessly
back and forth along the perimeter. If he touches the player, he carries
the player down the level and the player is dead.
* **Tanker** -- Moves slowly, shoots, and never leaves his segment. If a
tanker is shot or reaches the outer edge, it is destroyed and two
flippers flip out of it in opposite directions.
* **Spiker** -- Moves quickly, shoots, and lays a spike on the level where it
travels. Spikers cannot change segments. The spiker turns around when it
reaches a random point on the level and goes back down, and disappears if
it reaches the inner edge. The spike it lays remains, and can be shot.
If the player kills all the enemies, he must fly down the level and avoid
hitting any spikes, or he will be killed.
"}
tempest.core
(:require [tempest.levels :as levels]
[tempest.util :as util]
[tempest.draw :as draw]
[tempest.path :as path]
[goog.dom :as dom]
[goog.events :as events]
[goog.events.KeyCodes :as key-codes]
[clojure.browser.repl :as repl])
(:require-macros [tempest.macros :as macros]))
;;(repl/connect "http://localhost:9000/repl")
;; ---
(defn next-game-state
"**Main logic loop**
Given the current game-state, threads it through a series of functions that
calculate the next game-state. This is the most fundamental call in the
game; it applies all of the logic.
The last call, schedule-next-frame, schedules this function to be called
again by the browser sometime in the future with the update game-state
after passing through all the other functions. This implements the game loop.
This function actualy dispatches to one of multiple other functions, starting
with the 'game-logic-' prefix, that actually do the function threading. This
is because the game's main loop logic changes based on a few possible states:
* Normal, active gameplay is handled by game-logic-playable. This is the
longest path, and has to handle all of the gameplay logic, collision
detection, etc.
* Animation of levels zooming in and out, when first loading or after the
player dies, are handled by game-logic-non-playable. Most of the game
logic is disabled during this stage, as it is primarily displaying a
non-interactive animation.
* 'Shooping' is what I call the end-of-level gameplay, after all enemies are
defeated, when the player's ship travels down the level and must destroy
or avoid any spikes remaining. All of the game logic regarding enemies is
disabled in this path, but moving and shooting still works.
* The 'Paused' state is an extremely reduced state that only listens for the
unpause key.
"
[game-state]
(cond
(:paused? game-state) (game-logic-paused game-state)
(:player-zooming? game-state)
(game-logic-player-shooping-down-level game-state)
(and (:is-zooming? game-state))
(game-logic-non-playable game-state)
:else (game-logic-playable game-state)))
(defn game-logic-paused
"Called by next-game-state when game is paused. Just listens for keypress
to unpause game."
[game-state]
(->> game-state
dequeue-keypresses-while-paused
schedule-next-frame))
(defn game-logic-player-shooping-down-level
"That's right, I named it that. This is the game logic path that handles
the player 'shooping' down the level, traveling into it, after all enemies
have been defeated. The player can still move and shoot, and can kill or
be killed by spikes remaining on the level."
[game-state]
(->> game-state
clear-player-segment
dequeue-keypresses
highlight-player-segment
clear-frame
draw-board
render-frame
remove-spiked-bullets
update-projectile-locations
animate-player-shooping
mark-player-if-spiked
maybe-change-level
update-frame-count
maybe-render-fps-display
schedule-next-frame
))
(defn game-logic-playable
"Called by next-game-state when game and player are active. This logic path
handles all the good stuff: drawing the player, drawing the board, enemies,
bullets, spikes, movement, player capture, player death, etc."
[game-state]
(let [gs1 (->> game-state
clear-player-segment
dequeue-keypresses
highlight-player-segment
maybe-change-level
clear-frame
draw-board
render-frame)
gs2 (->> gs1
remove-spiked-bullets
remove-collided-entities
remove-collided-bullets
update-projectile-locations
update-enemy-locations
update-enemy-directions
maybe-split-tankers
handle-dead-enemies
handle-exiting-spikers
maybe-enemies-shoot)
gs3 (->> gs2
handle-spike-laying
maybe-make-enemy
check-if-enemies-remain
check-if-player-captured
update-player-if-shot
update-entity-is-flipping
update-entity-flippyness
animate-player-capture
update-frame-count
maybe-render-fps-display)]
(->> gs3 schedule-next-frame)))
(defn game-logic-non-playable
"Called by next-game-state for non-playable animations. This is used when
the level is quickly zoomed in or out between stages or after the player
dies. Most of the game logic is disabled during this animation."
[game-state]
(->> game-state
dequeue-keypresses-while-paused
clear-frame
draw-board
render-frame
update-frame-count
maybe-render-fps-display
schedule-next-frame))
;; ---
(def ^{:doc
"Global queue for storing player's keypresses. The browser
sticks keypresses in this queue via callback, and keys are
later pulled out and applied to the game state during the
game logic loop."}
*key-event-queue* (atom '()))
(defn build-game-state
"Returns an empty game-state map."
[]
{:enemy-list '()
:projectile-list '()
:player '()
:spikes []
:context nil
:bgcontext nil
:anim-fn identity
:dims {:width 0 :height 0}
:level-idx 0
:level nil
:frame-count 0
:frame-time 0
:paused? false
:is-zooming? true
:zoom-in? true
:zoom 0.0
:level-done? false
:player-zooming? false
})
(defn check-if-enemies-remain
"If no enemies are left on the level, and no enemies remain to be launched
mark level as zooming out."
[game-state]
(let [level (:level game-state)
player (:player game-state)
on-board (count (:enemy-list game-state))
unlaunched (apply + (vals (:remaining level)))
remaining (+ on-board unlaunched)]
(if (zero? remaining)
(assoc game-state
:player (assoc player :stride -2)
:player-zooming? true)
game-state)))
(defn change-level
"Changes current level of game."
[game-state level-idx]
(let [level (get levels/*levels* level-idx)]
(assoc game-state
:level-idx level-idx
:level level
:player (build-player level 0)
:zoom 0.0
:zoom-in? true
:is-zooming? true
:level-done? false
:player-zooming? false
:projectile-list '()
:enemy-list '()
:spikes (vec (take (count (:segments level)) (repeat 0))))))
(defn maybe-change-level
"Reloads or moves to the next level if player is dead, or if all enemies are
dead."
[game-state]
(let [player (:player game-state)
level (:level game-state)]
(cond
(and (:is-dead? player) (:level-done? game-state))
(change-level game-state (:level-idx game-state))
(and (not (:is-dead? player)) (:level-done? game-state))
(change-level game-state (inc (:level-idx game-state)))
:else game-state)))
(defn build-projectile
"Returns a dictionary describing a projectile (bullet) on the given level,
in the given segment, with a given stride (steps per update to move, with
negative meaning in and positive meaning out), and given step to start on."
[level seg-idx stride & {:keys [step from-enemy?]
:or {step 0 from-enemy? false}}]
{:step step
:stride stride
:segment seg-idx
:damage-segment seg-idx
:level level
:path-fn path/projectile-path-on-level
:from-enemy? from-enemy?
})
(def ^{:doc "Enumeration of directions a flipper can be flipping."}
DirectionEnum {"NONE" 0 "CW" 1 "CCW" 2})
(def ^{:doc "Enumeration of types of enemies."}
EnemyEnum {"NONE" 0 "FLIPPER" 1 "TANKER" 2
"SPIKER" 3 "FUSEBALL" 4 "PULSAR" 5})
(defn direction-string-from-value
"Given a value from DirectionEnum, return the corresponding string."
[val]
(first (first (filter #(= 1 (peek %)) (into [] maptest)))))
(defn build-enemy
"Returns a dictionary describing an enemy on the given level and segment,
and starting on the given step. Step defaults to 0 (innermost step of
level) if not specified."
[level seg-idx & {:keys [step] :or {step 0}}]
{:step step
:stride 1
:segment seg-idx
:damage-segment seg-idx
:level level
:hits-remaining 1
:path-fn #([])
:flip-dir (DirectionEnum "NONE")
:flip-point [0 0]
:flip-stride 1
:flip-max-angle 0
:flip-cur-angle 0
:flip-probability 0
:can-flip false
:shoot-probability 0
:type (EnemyEnum "NONE")
})
(defn build-tanker
"Returns a new tanker enemy. Tankers move slowly and do not shoot or flip."
[level seg-idx & {:keys [step] :or {step 0}}]
(assoc (build-enemy level seg-idx :step step)
:type (EnemyEnum "TANKER")
:path-fn path/tanker-path-on-level
:can-flip false
:stride 0.2
:shoot-probability 0.0
))
(defn build-spiker
"Returns a new spiker enemy. Spiker cannot change segments, travels quickly,
and turns around on a random step, where 20 <= step <= max_step - 20.
Spikers can shoot, and they lay spikes behind them as they move."
[level seg-idx & {:keys [step] :or {step 0}}]
(assoc (build-enemy level seg-idx :step step)
:type (EnemyEnum "SPIKER")
:path-fn path/spiker-path-on-level
:can-flip false
:stride 1
:shoot-probability 0.001
:max-step (+ (rand-int (- (:steps level) 40)) 20)
))
(defn build-flipper
"A more specific form of build-enemy for initializing a flipper."
[level seg-idx & {:keys [step] :or {step 0}}]
(assoc (build-enemy level seg-idx :step step)
:type (EnemyEnum "FLIPPER")
:path-fn path/flipper-path-on-level
:flip-dir (DirectionEnum "NONE")
:flip-point [0 0]
:flip-stride 1
:flip-step-count 20
:flip-max-angle 0
:flip-cur-angle 0
:flip-permanent-dir nil
:flip-probability 0.015
:can-flip true
:shoot-probability 0.004
))
(defn projectiles-after-shooting
"Returns a new list of active projectiles after randomly adding shots from
enemies."
[enemy-list projectile-list]
(loop [[enemy & enemies] enemy-list
projectiles projectile-list]
(if (nil? enemy) projectiles
(if (and (<= (rand) (:shoot-probability enemy))
(not= (:step enemy) (:steps (:level enemy)))
(pos? (:stride enemy)))
(recur enemies (add-enemy-projectile projectiles enemy))
(recur enemies projectiles)))))
(defn maybe-enemies-shoot
"Randomly adds new projectiles coming from enemies based on the enemies'
shoot-probability field. See projectiles-after-shooting."
[game-state]
(let [enemies (:enemy-list game-state)
projectiles (:projectile-list game-state)]
(assoc game-state
:projectile-list (projectiles-after-shooting enemies projectiles))))
(defn maybe-make-enemy
"Randomly create new enemies if the level needs more. Each level has a total
count and probability of arrival for each type of enemy. When a new enemy
is added by this function, the total count for that type is decremented.
If zero enemies are on the board, probability of placing one is increased
two-fold to avoid long gaps with nothing to do."
[game-state]
(let [flipper-fn (macros/random-enemy-fn flipper)
tanker-fn (macros/random-enemy-fn tanker)
spiker-fn (macros/random-enemy-fn spiker)]
(->> game-state
flipper-fn
tanker-fn
spiker-fn)))
(defn flip-angle-stride
"Returns the angle stride of a flipper, which is how many radians to
increment his current flip angle by to be completely flipped onto his
destination segment (angle of max-angle) on 'steps' number of increments,
going clockwise if cw? is true, or counter-clockwise otherwise.
### Implementation details:
There are three known possibilities for determining the stride such that the
flipper appears to flip 'inside' the level:
* max-angle/steps -- If flipper is going clockwise and max-angle is less
than zero, or if flipper is going counter-clockwise and max-angle is
greater than zero.
* (max-angle - 2PI)/steps -- If flipper is going clockwise and max-angle
is greater than zero.
* (max-angle + 2PI)/steps -- If flipper is going counter-clockwise and
max-angle is less than zero.
"
[max-angle steps cw?]
(let [dir0 (/ max-angle steps)
dir1 (/ (- max-angle 6.2831853) steps)
dir2 (/ (+ max-angle 6.2831853) steps)]
(cond
(<= max-angle 0) (if cw? dir0 dir2)
:else (if cw? dir1 dir0))))
(defn mark-flipper-for-flipping
"Updates a flipper's map to indicate that it is currently flipping in the
given direction, to the given segment index. cw? should be true if
flipping clockwise, false for counter-clockwise."
[flipper direction seg-idx cw?]
(let [point (path/flip-point-between-segments
(:level flipper)
(:segment flipper)
seg-idx
(:step flipper)
cw?)
max-angle (path/flip-angle-between-segments
(:level flipper)
(:segment flipper)
seg-idx
cw?)
step-count (:flip-step-count flipper)
stride (flip-angle-stride max-angle step-count cw?)
permanent (if (= (:steps (:level flipper))
(:step flipper)) direction nil)]
(assoc flipper
:stride 0
:old-stride (:stride flipper)
:flip-dir direction
:flip-cur-angle 0
:flip-to-segment seg-idx
:flip-point point
:flip-max-angle max-angle
:flip-stride stride
:flip-steps-remaining step-count
:flip-permanent-dir permanent)))
(defn update-entity-stop-flipping
"Updates an entity and marks it as not currently flipping."
[flipper]
(assoc flipper
:stride (:old-stride flipper)
:flip-dir (DirectionEnum "NONE")
:flip-cur-angle 0
:segment (:flip-to-segment flipper)))
(defn random-direction
"Returns a random direction from DirectionEnum (not 'NONE')"
[]
(condp = (rand-int 2)
0 (DirectionEnum "CW")
(DirectionEnum "CCW")))
(defn segment-for-flip-direction
"Returns the segment that the given flipper would flip into if it flipped
in direction flip-dir. If the flipper can't flip that way, it will
return the flipper's current segment."
[flipper flip-dir]
(condp = flip-dir
(DirectionEnum "CW") (segment-entity-cw flipper)
(segment-entity-ccw flipper)))
(defn swap-flipper-permanent-dir
"Given a flipper with its 'permanent direction' set, this swaps the
permanent direction to be opposite. A flipper's permanent direction is
the direction it flips constantly along the outermost edge of the level
until it hits a boundary."
[flipper]
(let [cur-dir (:flip-permanent-dir flipper)
new-dir (if (= (DirectionEnum "CW") cur-dir)
(DirectionEnum "CCW")
(DirectionEnum "CW"))]
(assoc flipper :flip-permanent-dir new-dir)))
(defn engage-flipping
"Mark flipper as flipping in given direction, unless no segment is in
that direction."
[flipper flip-dir]
(let [flip-seg-idx (segment-for-flip-direction flipper flip-dir)
cw? (= flip-dir (DirectionEnum "CW"))]
(if (not= flip-seg-idx (:segment flipper))
(mark-flipper-for-flipping flipper flip-dir
flip-seg-idx cw?)
flipper)))
(defn maybe-engage-flipping
"Given a flipper, returns the flipper possibly modified to be in a state
of flipping to another segment. This will always be true if the flipper
is on the outermost edge of the level, and will randomly be true if it
has not reached the edge."
[flipper]
(let [should-flip (and
(true? (:can-flip flipper))
(= (:flip-dir flipper) (DirectionEnum "NONE"))
(or (<= (rand) (:flip-probability flipper))
(= (:step flipper) (:steps (:level flipper)))))
permanent-dir (:flip-permanent-dir flipper)
flip-dir (or permanent-dir (random-direction))
flip-seg-idx (segment-for-flip-direction flipper flip-dir)
cw? (= flip-dir (DirectionEnum "CW"))]
(cond
(false? should-flip) flipper
(not= flip-seg-idx (:segment flipper)) (mark-flipper-for-flipping
flipper flip-dir
flip-seg-idx cw?)
(not (nil? permanent-dir)) (swap-flipper-permanent-dir flipper)
:else flipper)))
(defn mark-player-captured
"Marks player as being captured."
[player]
(assoc player
:captured? true
:stride -4))
(defn mark-enemy-capturing
"Marks enemy as having captured the player."
[enemy]
(assoc enemy
:capturing true
:can-flip false
:step (- (:step enemy) 10) ;; looks better if enemy leads player
:stride -4))
(defn enemy-is-on-player?
"Returns true if given enemy and player are on top of each other."
[player enemy]
(and (= (:segment player) (:segment enemy))
(= (:step player) (:step enemy))
(= (DirectionEnum "NONE") (:flip-dir enemy))))
(defn player-and-enemies-if-captured
"Given player and current list of enemies, returns an updated player
and updated enemy list if an enemy is capturing the player in vector
[player enemy-list]. Returns nil if no capture occurred."
[player enemy-list]
(let [{colliders true missers false}
(group-by (partial enemy-is-on-player? player) enemy-list)]
(when-let [[enemy & rest] colliders]
[(mark-player-captured player)
(cons (mark-enemy-capturing enemy) (concat missers rest))])))
(defn check-if-player-captured
"If player is not already captured, checks all enemies to see if they
are now capturing the player. See player-and-enemies-if-captured.
If capture is in progress, returns game-state with player and enemy-list
updated."
[game-state]
(if (:captured? (:player game-state))
game-state
(if-let [[player enemy-list] (player-and-enemies-if-captured
(:player game-state)
(:enemy-list game-state))]
(assoc game-state :enemy-list enemy-list :player player)
game-state)))
(defn update-entity-is-flipping
"Decide if an enemy should start flipping for every enemy on the level."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (map maybe-engage-flipping enemy-list))))
(defn update-entity-flippyness
"Update the position of any actively flipping enemy for every enemy on the
level."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (map update-flip-angle enemy-list))))
(defn update-flip-angle
"Given a flipper in the state of flipping, updates its current angle. If
the update would cause it to 'land' on its new segment, the flipper is
updated and returned as a no-longer-flipping. If the given enemy is
not flipping, returns it unchanged."
[flipper]
(let [new-angle (+ (:flip-stride flipper) (:flip-cur-angle flipper))
remaining (dec (:flip-steps-remaining flipper))
new-seg (if (<= remaining (/ (:flip-step-count flipper) 2))
(:flip-to-segment flipper)
(:segment flipper))]
(if (not= (:flip-dir flipper) (DirectionEnum "NONE"))
(if (< remaining 0)
(update-entity-stop-flipping flipper)
(assoc flipper
:damage-segment new-seg
:flip-cur-angle new-angle
:flip-steps-remaining remaining))
flipper)))
(defn build-player
"Returns a dictionary describing a player on the given level and segment."
[level seg-idx]
{:segment seg-idx
:level level
:captured? false
:step (:steps level)
:bullet-stride -5
:stride 0
:path path/*player-path*
:is-dead? false
})
(defn entity-next-step
"Returns the next step position of given entity, taking into account
minimum and maximum positions of the level."
[entity]
(let [stride (:stride entity)
maxstep (:steps (:level entity))
newstep (+ stride (:step entity))]
(cond
(> newstep maxstep) maxstep
(< newstep 0) 0
:else newstep)))
(defn update-entity-position!
"Return entity updated with a new position based on its current location and
stride. Won't go lower than 0, or higher than the maximum steps of the
level."
[entity]
(assoc entity :step (entity-next-step entity)))
(defn update-entity-list-positions
"Call update-entity-position! on all entities in list."
[entity-list]
(map update-entity-position! entity-list))
(defn update-entity-direction!
"Updates an enemy to travel in the opposite direction if he has reached
his maximum allowable step. This is used for Spikers, which travel
back down the level after laying spikes."
[entity]
(let [{:keys [step max-step stride]} entity
newstride (if (>= step max-step) (- stride) stride)]
(assoc entity :stride newstride)))
(defn update-entity-list-directions
"Apply update-entity-direction! to all enemies in the given list that have
a maximum step."
[entity-list]
(let [{spikers true others false}
(group-by #(contains? % :max-step) entity-list)]
(concat others (map update-entity-direction! spikers))))
(defn entity-between-steps
"Returns true of entity is on seg-idx, and between steps step0 and step1,
inclusive."
[seg-idx step0 step1 entity]
(let [min (min step0 step1)
max (max step0 step1)]
(and
(= (:damage-segment entity) seg-idx)
(>= (:step entity) min)
(<= (:step entity) max))))
(defn projectiles-after-collision
"Given an entity and a list of projectiles, returns the entity and updated
list of projectiles after collisions. The entity's hits-remaining counter
is decremented on a collision, and the projectile is removed. Small amount
of fudge factor (1 step += actual projectile location) to avoid narrow
misses in the collision algorithm."
[entity projectile-list]
((fn [entity projectiles-in projectiles-out was-hit?]
(if (empty? projectiles-in)
{:entity entity :projectiles projectiles-out :was-hit? was-hit?}
(let [bullet (first projectiles-in)
collision? (entity-between-steps
(:segment bullet)
(inc (:step bullet))
(dec (entity-next-step bullet))
entity)]
(if (and (not (:from-enemy? bullet)) collision?)
(recur (decrement-enemy-hits entity)
nil
(concat projectiles-out (rest projectiles-in))
true)
(recur entity
(rest projectiles-in)
(cons bullet projectiles-out)
was-hit?)))))
entity projectile-list '() false))
(defn entities-after-collisions
"Given a list of entities and a list of projectiles, returns the lists
with entity hit counts updated, entities removed if they have no hits
remaining, and collided projectiles removed.
See projectiles-after-collision, which is called for each entity in
entity-list."
[entity-list projectile-list]
((fn [entities-in entities-out projectiles-in]
(if (empty? entities-in)
{:entities entities-out :projectiles projectiles-in}
(let [{entity :entity projectiles :projectiles was-hit? :was-hit?}
(projectiles-after-collision (first entities-in)
projectiles-in)]
(recur (rest entities-in)
(cons entity entities-out)
projectiles))))
entity-list '() projectile-list))
(defn new-flippers-from-tanker
"Spawns two new flippers from one tanker. These flippers are automatically
set to be flipping to the segments surround the tanker, unless one of the
directions is blocked, in which case that flipper just stays on the tanker's
segment."
[enemy]
(let [{:keys [segment level step]} enemy]
(list
(engage-flipping
(build-flipper level segment :step step)
(DirectionEnum "CW"))
(engage-flipping
(build-flipper level segment :step step)
(DirectionEnum "CCW")))))
(defn enemy-list-after-deaths
"Returns the enemy list updated for deaths. This means removing enemies
that died, and possibly adding new enemies for those that spawn children
on death."
[enemy-list]
(let [{live-enemies false dead-enemies true}
(group-by #(zero? (:hits-remaining %)) enemy-list)]
(loop [[enemy & enemies] dead-enemies
enemies-out '()]
(cond
(nil? enemy) (concat live-enemies enemies-out)
(= (:type enemy) (EnemyEnum "TANKER"))
(recur enemies (concat (new-flippers-from-tanker enemy) enemies-out))
:else (recur enemies enemies-out)))))
(defn handle-dead-enemies
"Return game state after handling dead enemies, by removing them and possibly
replacing them with children."
[game-state]
(let [enemy-list (:enemy-list game-state)]
(assoc game-state :enemy-list (enemy-list-after-deaths enemy-list))))
(defn enemy-list-after-exiting-spikers
"Returns an updated copy of the given list of enemies with spikers removed
if they have returned to the innermost edge of the level. Spikers travel
out towards the player a random distance, then turn around and go back in.
They disappear when they are all the way in."
[enemy-list]
(let [{spikers true others false}
(group-by #(= (:type %) (EnemyEnum "SPIKER")) enemy-list)]
(loop [[enemy & enemies] spikers
enemies-out '()]
(cond
(nil? enemy) (concat others enemies-out)
(and (neg? (:stride enemy)) (zero? (:step enemy)))
(recur enemies enemies-out)
:else
(recur enemies (cons enemy enemies-out))))))
(defn handle-exiting-spikers
"Apply enemy-list-after-exiting-spikers to the enemy list and update game
state. This removes any spikers that are ready to disappear."
[game-state]
(let [enemy-list (:enemy-list game-state)]
(assoc game-state
:enemy-list (enemy-list-after-exiting-spikers enemy-list))))
(defn spikes-after-spike-laying
"Given a list of spikers and the current length of spikes on each segment,
this updates the spike lengths to be longer if a spiker has traveled past
the edge of an existing spike. Returns [enemy-list spikes]"
[enemy-list spikes]
(loop [[enemy & enemies] enemy-list
spikes-out spikes]
(let [{:keys [step segment]} enemy
spike-step (nth spikes-out segment)]
(cond
(nil? enemy) spikes-out
(>= step spike-step) (recur enemies (assoc spikes-out segment step))
:else (recur enemies spikes-out)))))
(defn handle-spike-laying
"Updates the length of spikes on the level. See spikes-after-spike-laying."
[game-state]
(let [enemy-list (:enemy-list game-state)
spikes (:spikes game-state)
spiker-list (filter #(= (:type %) (EnemyEnum "SPIKER")) enemy-list)]
(assoc game-state :spikes (spikes-after-spike-laying spiker-list spikes))))
(defn kill-tanker-at-top
"If the given tanker is at the top of a level, mark it as dead. Tankers
die when they reach the player, and split into two flippers."
[tanker]
(let [step (:step tanker)
maxstep (:steps (:level tanker))]
(if (= step maxstep)
(assoc tanker :hits-remaining 0)
tanker)))
(defn maybe-split-tankers
"Marks tankers at the top of the level as ready to split into flippers."
[game-state]
(let [enemy-list (:enemy-list game-state)
{tankers true others false}
(group-by #(= (:type %) (EnemyEnum "TANKER")) enemy-list)]
(assoc game-state
:enemy-list (concat (map kill-tanker-at-top tankers) others))))
(defn mark-player-if-spiked
"Marks the player as dead and sets up the animation flags to trigger a
level reload if the player has impacted a spike while traveling down the
level."
[game-state]
(let [{:keys [spikes player]} game-state step (:step player)
;; TODO: (nth) caused an error here once, spikes was length 0.
segment (:segment player) spike-len (nth spikes segment)]
(cond
(zero? spike-len) game-state
(<= step spike-len)
(assoc game-state
:player (assoc player :is-dead? true)
:is-zooming? true
:zoom-in? false
:player-zooming? false)
:else game-state)))
(defn animate-player-shooping
"Updates the player's position as he travels ('shoops') down the level after
defeating all enemies. Player moves relatively slowly. Camera zooms in
(actually, level zooms out) a little slower than the player moves. After
player reaches bottom, camera zooms faster. Level marked as finished when
zoom level is very high (10x normal)."
[game-state]
(let [player (:player game-state)
level (:level game-state)
zoom (:zoom game-state)]
(cond
(:level-done? game-state) game-state
(>= zoom 10) (assoc game-state :level-done? true)
(zero? (:step player)) (assoc game-state :zoom (+ zoom .2))
:else (assoc game-state
:player (update-entity-position! player)
:zoom (+ 1 (/ (- (:steps level) (:step player)) 150))
:is-zooming? true
:zoom-in? false
))))
(defn animate-player-capture
"Updates player's position on board while player is in the process of being
captured by an enemy, and marks player as dead when he reaches the inner
boundary of the level. When player dies, level zoom-out is initiated."
[game-state]
(let [player (:player game-state)
captured? (:captured? player)
isdead? (zero? (:step player))]
(cond
(false? captured?) game-state
(true? isdead?) (assoc (clear-level-entities game-state)
:player (assoc player :is-dead? true)
:is-zooming? true
:zoom-in? false)
:else (assoc game-state :player (update-entity-position! player)))))
(defn clear-level-entities
"Clears enemies, projectiles, and spikes from level."
[game-state]
(assoc game-state
:enemy-list '()
:projectile-list '()
:spikes []))
(defn update-zoom
"Updates current zoom value of the level, based on direction of :zoom-in?
in the game-state. This is used to animate the board zooming in or
zooming out at the start or end of a round. If this was a zoom out, and
it's finished, mark the level as done so it can restart."
[game-state]
(let [zoom (:zoom game-state)
zoom-in? (:zoom-in? game-state)
zoom-step 0.04
newzoom (if zoom-in? (+ zoom zoom-step) (- zoom zoom-step))
target (if zoom-in? 1.0 0.0)
cmp (if zoom-in? >= <=)]
(if (cmp zoom target) (assoc game-state
:is-zooming? false
:level-done? (not zoom-in?))
(if (cmp newzoom target)
(assoc game-state :zoom target)
(assoc game-state :zoom newzoom)))))
(defn clear-player-segment
"Returns game-state unchanged, and as a side affect clears the player's
current segment back to blue. To avoid weird color mixing, it is cleared
to black first (2px wide), then redrawn as blue (1.5px wide). This looks
right, but is different from how the board is drawn when done all at once."
[game-state]
(do
(set! (. (:bgcontext game-state) -lineWidth) 2)
(draw/draw-player-segment game-state {:r 0 :g 0 :b 0})
(set! (. (:bgcontext game-state) -lineWidth) 1.5)
(draw/draw-player-segment game-state {:r 10 :g 10 :b 100})
game-state))
(defn highlight-player-segment
"Returns game-state unchanged, and as a side effect draws the player's
current segment with a yellow border."
[game-state]
(do
(set! (. (:bgcontext game-state) -lineWidth) 1)
(draw/draw-player-segment game-state {:r 150 :g 150 :b 15})
game-state))
(defn draw-board
"Draws the level when level is zooming in or out, and updates the zoom level.
This doesn't redraw the board normally, since the board is drawn on a
different HTML5 canvas than the players for efficiency."
[game-state]
(let [is-zooming? (:is-zooming? game-state)
zoom (:zoom game-state)
{width :width height :height} (:dims game-state)]
(if is-zooming?
(do
(draw/clear-context (:bgcontext game-state) (:dims game-state))
(draw/draw-board (assoc game-state
:dims {:width (/ width zoom)
:height (/ height zoom)}))
(if (:player-zooming? game-state)
game-state
(update-zoom game-state)))
game-state)))
(defn collisions-with-projectile
"Returns map with keys true and false. Values under true key have or
will collide with bullet in the next bullet update. Values under the
false key will not."
[enemy-list bullet]
(group-by (partial entity-between-steps
(:segment bullet)
(:step bullet)
(entity-next-step bullet))
enemy-list))
(defn decrement-enemy-hits
"Decrement hits-remaining count on given enemy."
[enemy]
(assoc enemy :hits-remaining (dec (:hits-remaining enemy))))
(defn projectile-off-level?
"Returns true if a projectile has reached either boundary of the level."
[projectile]
(cond
(zero? (:step projectile)) true
(>= (:step projectile) (:steps (:level projectile))) true
:else false))
(defn add-enemy-projectile
"Add a new projectile to the global list of live projectiles, originating
from the given enemy, on the segment he is currently on."
[projectile-list enemy]
(let [level (:level enemy)
seg-idx (:segment enemy)
stride (+ (:stride enemy) 2)
step (:step enemy)]
(conj projectile-list
(build-projectile level seg-idx stride :step step :from-enemy? true))))
(defn add-player-projectile
"Add a new projectile to the global list of live projectiles, originating
from the given player, on the segment he is currently on."
[projectile-list player]
(let [level (:level player)
seg-idx (:segment player)
stride (:bullet-stride player)
step (:step player)]
(conj projectile-list
(build-projectile level seg-idx stride :step step))))
(defn segment-entity-cw
"Returns the segment to the left of the player. Loops around the level
on connected levels, and stops at 0 on unconnected levels."
[player]
(let [level (:level player)
seg-max (dec (count (:segments level)))
cur-seg (:segment player)
loops? (:loops? level)
new-seg (dec cur-seg)]
(if (< new-seg 0)
(if loops? seg-max 0)
new-seg)))
(defn segment-entity-ccw
"Returns the segment to the right of the player. Loops around the level
on connected levels, and stops at max on unconnected levels."
[player]
(let [level (:level player)
seg-max (dec (count (:segments level)))
cur-seg (:segment player)
loops? (:loops? level)
new-seg (inc cur-seg)]
(if (> new-seg seg-max)
(if loops? 0 seg-max)
new-seg)))
(defn queue-keypress
"Atomically queue keypress in global queue for later handling. This should
be called as the browser's key-handling callback."
[event]
(let [key (.-keyCode event)]
(swap! *key-event-queue* #(concat % [key]))
(.preventDefault event)
(.stopPropagation event)))
(defn dequeue-keypresses-while-paused
"See dequeue-keypresses for details. This unqueues all keypresses, but only
responds to unpause."
[game-state]
(loop [state game-state
queue @*key-event-queue*]
(if (empty? queue)
state
(let [key (first queue)
valid? (compare-and-set! *key-event-queue* queue (rest queue))]
(if valid?
(recur (handle-keypress-unpause state key) @*key-event-queue*)
(recur state @*key-event-queue*))))))
(defn handle-keypress-unpause
"See handle-keypress. This version only accepts unpause."
[game-state key]
(let [paused? (:paused? game-state)]
(condp = key
key-codes/ESC (assoc game-state :paused? (not paused?))
game-state)))
(defn handle-keypress
"Returns new game state updated to reflect the results of a player's
keypress.
## Key map
* Right -- Move counter-clockwise
* Left -- Move clockwise
* Space -- Shoot
* Escape -- Pause
"
[game-state key]
(let [player (:player game-state)
projectile-list (:projectile-list game-state)
paused? (:paused? game-state)]
(condp = key
key-codes/RIGHT (assoc game-state
:player
(assoc player :segment (segment-entity-ccw player)))
key-codes/LEFT (assoc game-state
:player
(assoc player :segment (segment-entity-cw player)))
key-codes/SPACE (assoc game-state
:projectile-list
(add-player-projectile projectile-list player))
key-codes/ESC (assoc game-state :paused? (not paused?))
game-state)))
(defn dequeue-keypresses
"Atomically dequeue keypresses from global queue and pass to handle-keypress,
until global queue is empty. Returns game state updated after applying
all keypresses.
Has a side effect of clearing global *key-event-queue*.
## Implementation details:
Use compare-and-set! instead of swap! to test against the value we
entered the loop with, instead of the current value. compare-and-set!
returns true only if the update was a success (i.e. the queue hasn't
changed since entering the loop), in which case we handle the key.
If the queue has changed, we do nothing. The loop always gets called
again with the current deref of the global state.
"
[game-state]
(loop [state game-state
queue @*key-event-queue*]
(if (empty? queue)
state
(let [key (first queue)
valid? (compare-and-set! *key-event-queue* queue (rest queue))]
(cond
(not valid?) (recur state @*key-event-queue*)
(not (:captured? (:player game-state))) (recur (handle-keypress
state
key)
@*key-event-queue*)
:else (recur (handle-keypress-unpause state key) @*key-event-queue*)
)))))
(defn animationFrameMethod
"Returns a callable javascript function to schedule a frame to be drawn.
Tries to use requestAnimationFrame, or the browser-specific version of
it that is available. Falls back on setTimeout if requestAnimationFrame
is not available on player's browser.
requestAnimationFrame tries to figure out a consistent framerate based
on how long frame takes to render.
The setTimeout fail-over is hard-coded to attempt 30fps.
"
[]
(let [window (dom/getWindow)
names ["requestAnimationFrame"
"webkitRequestAnimationFrame"
"mozRequestAnimationFrame"
"oRequestAnimationFrame"
"msRequestAnimationFrame"]
options (map (fn [name] #(aget window name)) names)]
((fn [[current & remaining]]
(cond
(nil? current) #((.-setTimeout window) % (/ 1000 30))
(fn? (current)) (current)
:else (recur remaining)))
options)))
(defn clear-frame
"Returns game state unmodified, clears the HTML5 canvas as a side-effect."
[game-state]
(do
(draw/clear-context (:context game-state) (:dims game-state))
game-state))
(defn render-frame
"Draws the current game-state on the HTML5 canvas. Returns the game state
unmodified (drawing is a side-effect)."
[game-state]
(let [{context :context
dims :dims
level :level
enemy-list :enemy-list
projectile-list :projectile-list
player :player}
game-state
{enemy-shots true player-shots false}
(group-by :from-enemy? projectile-list)
zoom (:zoom game-state)
zoom-dims {:width (/ (:width dims) zoom)
:height (/ (:height dims) zoom)}]
(draw/draw-all-spikes (assoc game-state :dims zoom-dims))
(if (not (:is-dead? player))
(draw/draw-player context zoom-dims level player (:zoom game-state)))
(draw/draw-entities context zoom-dims level
enemy-list
{:r 150 :g 10 :b 10}
zoom)
(draw/draw-entities context zoom-dims level
player-shots
{:r 255 :g 255 :b 255}
zoom)
(draw/draw-entities context zoom-dims level
enemy-shots
{:r 150 :g 15 :b 150}
zoom)
game-state))
(defn remove-collided-entities
"Detects and removes projectiles that have collided with enemies, and enemies
whose hit counts have dropped to zero. Returns updated game-state."
[game-state]
(let [{enemy-list :enemy-list
projectile-list :projectile-list}
game-state]
(let [{plist :projectiles elist :entities}
(entities-after-collisions enemy-list projectile-list)]
(assoc game-state
:projectile-list plist
:enemy-list elist))))
(defn bullets-will-collide?
"Returns true if two bullets will collide within the next frame, and one is
from the player and the other is from an enemy."
[bullet1 bullet2]
(let [max-stride (max (:stride bullet1) (:stride bullet2))
min-stride (min (:stride bullet1) (:stride bullet2))
step1 (:step bullet1)
step2 (:step bullet2)
next-step1 (entity-next-step bullet1)
next-step2 (entity-next-step bullet2)]
(and (or (and (>= step1 step2) (<= next-step1 next-step2))
(and (>= step2 step1) (<= next-step2 next-step1)))
(neg? min-stride)
(pos? max-stride)
(if (:from-enemy? bullet1)
(not (:from-enemy? bullet2))
(:from-enemy? bullet2)))))
(defn projectile-list-without-collisions
"Given a list of projectiles, returns the list minus any bullet-on-bullet
collisions that occur within it."
[projectiles]
(loop [[bullet & others] projectiles
survivors '()]
(if (nil? bullet) survivors
(let [{not-hit false hit true}
(group-by #(bullets-will-collide? bullet %) others)]
(if-not (empty? hit)
(recur (concat not-hit (rest hit)) survivors)
(recur others (cons bullet survivors)))))))
(defn remove-collided-bullets
"Remove bullets that have hit each other. Only player-vs-enemy collisions
count. Breaks list of projectiles into one list per segment, and then
runs projectile-list-without-collisions on each of those lists to get
back a final list of only bullets that aren't involved in collisions."
[game-state]
(let [projectile-list (:projectile-list game-state)
segment-lists (vals (group-by :segment projectile-list))
non-collided (mapcat projectile-list-without-collisions segment-lists)]
(assoc game-state :projectile-list non-collided)))
(defn decrement-spike-length
"Returns a new spike length based on the given spike length and the number
of times the spike was hit. Spike is arbitrarily shrunk by 10 steps per
hit. If it falls below a short threshhold (5), it is set to zero."
[spike-len hit-count]
(let [new-len (- spike-len (* 10 hit-count))]
(if (<= new-len 5) 0 new-len)))
(defn filter-spike-bullet-collisions
"Given a list of projectiles on a segment (it is mandatory that they all
be on the same segment), and the spike length on that segment, returns
[projectile-list spike-len], where any projectiles that hit the spike
have been removed from projectile-list, and spike-len has been updated
to be shorter if it was hit."
[projectile-list spike-len]
(let [{hit true missed false}
(group-by #(<= (:step %) spike-len) projectile-list)]
[missed (decrement-spike-length spike-len (count hit))]))
(defn remove-spiked-bullets
"Returns the game state with any bullets that hit a spike removed, and any
spikes that were hit shrunk in length."
[game-state]
(let [projectile-list (:projectile-list game-state)
{player-list false enemy-list true}
(group-by :from-enemy? projectile-list)
segmented-projectiles (group-by :segment player-list)]
(loop [[seg-bullets & remaining] segmented-projectiles
spikes (:spikes game-state)
projectiles-out '()]
(if (nil? seg-bullets)
(assoc game-state
:projectile-list (concat projectiles-out enemy-list)
:spikes spikes)
(let [[key bullets] seg-bullets
spike-len (nth spikes key)
[bullets new-len] (filter-spike-bullet-collisions bullets
spike-len)]
(recur remaining
(assoc spikes key new-len)
(concat projectiles-out bullets)))))))
(defn bullets-will-kill-player?
"Returns true given bullet will hit the given player."
[player bullet]
(let [next-step (entity-next-step bullet)
player-step (:step player)]
(and (= player-step next-step)
(:from-enemy? bullet))))
(defn update-player-if-shot
"Updates the player to indicate whether he was shot by an enemy."
[game-state]
(let [projectile-list (:projectile-list game-state)
player (:player game-state)
on-segment (filter #(= (:segment player) (:segment %)) projectile-list)
{hit true miss false} (group-by
#(bullets-will-kill-player? player %)
on-segment)]
(if-not (empty? hit)
(assoc (clear-level-entities game-state)
:player (assoc player :is-dead? true)
:is-zooming? true
:player-zooming? false
:zoom-in? false)
game-state)))
(defn update-projectile-locations
"Returns game-state with all projectiles updated to have new positions
based on their speeds and current position."
[game-state]
(let [{projectile-list :projectile-list} game-state
rm-fn (partial remove projectile-off-level?)]
(assoc game-state
:projectile-list (-> projectile-list
update-entity-list-positions
rm-fn))))
(defn update-enemy-locations
"Returns game-state with all of the enemies updated to have new positions
based on their speeds and current position."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (update-entity-list-positions enemy-list))))
(defn update-enemy-directions
"Return game state with any enemies who were ready to turn around marked to
travel in the opposite direction."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (update-entity-list-directions enemy-list))))
(defn schedule-next-frame
"Tells the player's browser to schedule the next frame to be drawn, using
whatever the best mechanism the browser has to do so."
[game-state]
((:anim-fn game-state) #(next-game-state game-state)))
(defn update-frame-count
"Increments the game-state's frame counter, which is a count of frames since
the last FPS measurement."
[game-state]
(let [{frame-count :frame-count}
game-state]
(assoc game-state :frame-count (inc frame-count))))
(defn render-fps-display
"Print a string representation of the most recent FPS measurement in
an HTML element named 'fps'. This resets the frame-count and frame-time
currently stored in the game state."
[game-state]
(let [{frame-count :frame-count
frame-time :frame-time}
game-state
fps (/ (* 1000 frame-count) (- (goog.now) frame-time))
str-fps (pr-str (util/round fps))]
(dom/setTextContent (dom/getElement "fps") (str "FPS: " str-fps))
(assoc game-state
:frame-count 0
:frame-time (goog.now))))
(defn maybe-render-fps-display
"Calls render-fps-display if the frame-count is above a certain threshhold."
[game-state]
(if (= (:frame-count game-state) 20)
(render-fps-display game-state)
game-state))
| 53992 | ;;
;; This file is part of tempest-cljs
;; Copyright (c) 2012, <NAME>
;; All rights reserved.
;; See LICENSE file for details.
;;
(ns ^{:doc "
Functions related to the game of tempest, and game state.
Functions in this module create the game state, and modify it based on
player actions or time. This includes management of entities such as
the player's ship, enemies, and projectiles.
Enemy types:
* **Flipper** -- Moves quickly up level, flips randomly to adjacent segments,
and shoots. When a flipper reaches the outer edge, he flips endlessly
back and forth along the perimeter. If he touches the player, he carries
the player down the level and the player is dead.
* **Tanker** -- Moves slowly, shoots, and never leaves his segment. If a
tanker is shot or reaches the outer edge, it is destroyed and two
flippers flip out of it in opposite directions.
* **Spiker** -- Moves quickly, shoots, and lays a spike on the level where it
travels. Spikers cannot change segments. The spiker turns around when it
reaches a random point on the level and goes back down, and disappears if
it reaches the inner edge. The spike it lays remains, and can be shot.
If the player kills all the enemies, he must fly down the level and avoid
hitting any spikes, or he will be killed.
"}
tempest.core
(:require [tempest.levels :as levels]
[tempest.util :as util]
[tempest.draw :as draw]
[tempest.path :as path]
[goog.dom :as dom]
[goog.events :as events]
[goog.events.KeyCodes :as key-codes]
[clojure.browser.repl :as repl])
(:require-macros [tempest.macros :as macros]))
;;(repl/connect "http://localhost:9000/repl")
;; ---
(defn next-game-state
"**Main logic loop**
Given the current game-state, threads it through a series of functions that
calculate the next game-state. This is the most fundamental call in the
game; it applies all of the logic.
The last call, schedule-next-frame, schedules this function to be called
again by the browser sometime in the future with the update game-state
after passing through all the other functions. This implements the game loop.
This function actualy dispatches to one of multiple other functions, starting
with the 'game-logic-' prefix, that actually do the function threading. This
is because the game's main loop logic changes based on a few possible states:
* Normal, active gameplay is handled by game-logic-playable. This is the
longest path, and has to handle all of the gameplay logic, collision
detection, etc.
* Animation of levels zooming in and out, when first loading or after the
player dies, are handled by game-logic-non-playable. Most of the game
logic is disabled during this stage, as it is primarily displaying a
non-interactive animation.
* 'Shooping' is what I call the end-of-level gameplay, after all enemies are
defeated, when the player's ship travels down the level and must destroy
or avoid any spikes remaining. All of the game logic regarding enemies is
disabled in this path, but moving and shooting still works.
* The 'Paused' state is an extremely reduced state that only listens for the
unpause key.
"
[game-state]
(cond
(:paused? game-state) (game-logic-paused game-state)
(:player-zooming? game-state)
(game-logic-player-shooping-down-level game-state)
(and (:is-zooming? game-state))
(game-logic-non-playable game-state)
:else (game-logic-playable game-state)))
(defn game-logic-paused
"Called by next-game-state when game is paused. Just listens for keypress
to unpause game."
[game-state]
(->> game-state
dequeue-keypresses-while-paused
schedule-next-frame))
(defn game-logic-player-shooping-down-level
"That's right, I named it that. This is the game logic path that handles
the player 'shooping' down the level, traveling into it, after all enemies
have been defeated. The player can still move and shoot, and can kill or
be killed by spikes remaining on the level."
[game-state]
(->> game-state
clear-player-segment
dequeue-keypresses
highlight-player-segment
clear-frame
draw-board
render-frame
remove-spiked-bullets
update-projectile-locations
animate-player-shooping
mark-player-if-spiked
maybe-change-level
update-frame-count
maybe-render-fps-display
schedule-next-frame
))
(defn game-logic-playable
"Called by next-game-state when game and player are active. This logic path
handles all the good stuff: drawing the player, drawing the board, enemies,
bullets, spikes, movement, player capture, player death, etc."
[game-state]
(let [gs1 (->> game-state
clear-player-segment
dequeue-keypresses
highlight-player-segment
maybe-change-level
clear-frame
draw-board
render-frame)
gs2 (->> gs1
remove-spiked-bullets
remove-collided-entities
remove-collided-bullets
update-projectile-locations
update-enemy-locations
update-enemy-directions
maybe-split-tankers
handle-dead-enemies
handle-exiting-spikers
maybe-enemies-shoot)
gs3 (->> gs2
handle-spike-laying
maybe-make-enemy
check-if-enemies-remain
check-if-player-captured
update-player-if-shot
update-entity-is-flipping
update-entity-flippyness
animate-player-capture
update-frame-count
maybe-render-fps-display)]
(->> gs3 schedule-next-frame)))
(defn game-logic-non-playable
"Called by next-game-state for non-playable animations. This is used when
the level is quickly zoomed in or out between stages or after the player
dies. Most of the game logic is disabled during this animation."
[game-state]
(->> game-state
dequeue-keypresses-while-paused
clear-frame
draw-board
render-frame
update-frame-count
maybe-render-fps-display
schedule-next-frame))
;; ---
(def ^{:doc
"Global queue for storing player's keypresses. The browser
sticks keypresses in this queue via callback, and keys are
later pulled out and applied to the game state during the
game logic loop."}
*key-event-queue* (atom '()))
(defn build-game-state
"Returns an empty game-state map."
[]
{:enemy-list '()
:projectile-list '()
:player '()
:spikes []
:context nil
:bgcontext nil
:anim-fn identity
:dims {:width 0 :height 0}
:level-idx 0
:level nil
:frame-count 0
:frame-time 0
:paused? false
:is-zooming? true
:zoom-in? true
:zoom 0.0
:level-done? false
:player-zooming? false
})
(defn check-if-enemies-remain
"If no enemies are left on the level, and no enemies remain to be launched
mark level as zooming out."
[game-state]
(let [level (:level game-state)
player (:player game-state)
on-board (count (:enemy-list game-state))
unlaunched (apply + (vals (:remaining level)))
remaining (+ on-board unlaunched)]
(if (zero? remaining)
(assoc game-state
:player (assoc player :stride -2)
:player-zooming? true)
game-state)))
(defn change-level
"Changes current level of game."
[game-state level-idx]
(let [level (get levels/*levels* level-idx)]
(assoc game-state
:level-idx level-idx
:level level
:player (build-player level 0)
:zoom 0.0
:zoom-in? true
:is-zooming? true
:level-done? false
:player-zooming? false
:projectile-list '()
:enemy-list '()
:spikes (vec (take (count (:segments level)) (repeat 0))))))
(defn maybe-change-level
"Reloads or moves to the next level if player is dead, or if all enemies are
dead."
[game-state]
(let [player (:player game-state)
level (:level game-state)]
(cond
(and (:is-dead? player) (:level-done? game-state))
(change-level game-state (:level-idx game-state))
(and (not (:is-dead? player)) (:level-done? game-state))
(change-level game-state (inc (:level-idx game-state)))
:else game-state)))
(defn build-projectile
"Returns a dictionary describing a projectile (bullet) on the given level,
in the given segment, with a given stride (steps per update to move, with
negative meaning in and positive meaning out), and given step to start on."
[level seg-idx stride & {:keys [step from-enemy?]
:or {step 0 from-enemy? false}}]
{:step step
:stride stride
:segment seg-idx
:damage-segment seg-idx
:level level
:path-fn path/projectile-path-on-level
:from-enemy? from-enemy?
})
(def ^{:doc "Enumeration of directions a flipper can be flipping."}
DirectionEnum {"NONE" 0 "CW" 1 "CCW" 2})
(def ^{:doc "Enumeration of types of enemies."}
EnemyEnum {"NONE" 0 "FLIPPER" 1 "TANKER" 2
"SPIKER" 3 "FUSEBALL" 4 "PULSAR" 5})
(defn direction-string-from-value
"Given a value from DirectionEnum, return the corresponding string."
[val]
(first (first (filter #(= 1 (peek %)) (into [] maptest)))))
(defn build-enemy
"Returns a dictionary describing an enemy on the given level and segment,
and starting on the given step. Step defaults to 0 (innermost step of
level) if not specified."
[level seg-idx & {:keys [step] :or {step 0}}]
{:step step
:stride 1
:segment seg-idx
:damage-segment seg-idx
:level level
:hits-remaining 1
:path-fn #([])
:flip-dir (DirectionEnum "NONE")
:flip-point [0 0]
:flip-stride 1
:flip-max-angle 0
:flip-cur-angle 0
:flip-probability 0
:can-flip false
:shoot-probability 0
:type (EnemyEnum "NONE")
})
(defn build-tanker
"Returns a new tanker enemy. Tankers move slowly and do not shoot or flip."
[level seg-idx & {:keys [step] :or {step 0}}]
(assoc (build-enemy level seg-idx :step step)
:type (EnemyEnum "TANKER")
:path-fn path/tanker-path-on-level
:can-flip false
:stride 0.2
:shoot-probability 0.0
))
(defn build-spiker
"Returns a new spiker enemy. Spiker cannot change segments, travels quickly,
and turns around on a random step, where 20 <= step <= max_step - 20.
Spikers can shoot, and they lay spikes behind them as they move."
[level seg-idx & {:keys [step] :or {step 0}}]
(assoc (build-enemy level seg-idx :step step)
:type (EnemyEnum "SPIKER")
:path-fn path/spiker-path-on-level
:can-flip false
:stride 1
:shoot-probability 0.001
:max-step (+ (rand-int (- (:steps level) 40)) 20)
))
(defn build-flipper
"A more specific form of build-enemy for initializing a flipper."
[level seg-idx & {:keys [step] :or {step 0}}]
(assoc (build-enemy level seg-idx :step step)
:type (EnemyEnum "FLIPPER")
:path-fn path/flipper-path-on-level
:flip-dir (DirectionEnum "NONE")
:flip-point [0 0]
:flip-stride 1
:flip-step-count 20
:flip-max-angle 0
:flip-cur-angle 0
:flip-permanent-dir nil
:flip-probability 0.015
:can-flip true
:shoot-probability 0.004
))
(defn projectiles-after-shooting
"Returns a new list of active projectiles after randomly adding shots from
enemies."
[enemy-list projectile-list]
(loop [[enemy & enemies] enemy-list
projectiles projectile-list]
(if (nil? enemy) projectiles
(if (and (<= (rand) (:shoot-probability enemy))
(not= (:step enemy) (:steps (:level enemy)))
(pos? (:stride enemy)))
(recur enemies (add-enemy-projectile projectiles enemy))
(recur enemies projectiles)))))
(defn maybe-enemies-shoot
"Randomly adds new projectiles coming from enemies based on the enemies'
shoot-probability field. See projectiles-after-shooting."
[game-state]
(let [enemies (:enemy-list game-state)
projectiles (:projectile-list game-state)]
(assoc game-state
:projectile-list (projectiles-after-shooting enemies projectiles))))
(defn maybe-make-enemy
"Randomly create new enemies if the level needs more. Each level has a total
count and probability of arrival for each type of enemy. When a new enemy
is added by this function, the total count for that type is decremented.
If zero enemies are on the board, probability of placing one is increased
two-fold to avoid long gaps with nothing to do."
[game-state]
(let [flipper-fn (macros/random-enemy-fn flipper)
tanker-fn (macros/random-enemy-fn tanker)
spiker-fn (macros/random-enemy-fn spiker)]
(->> game-state
flipper-fn
tanker-fn
spiker-fn)))
(defn flip-angle-stride
"Returns the angle stride of a flipper, which is how many radians to
increment his current flip angle by to be completely flipped onto his
destination segment (angle of max-angle) on 'steps' number of increments,
going clockwise if cw? is true, or counter-clockwise otherwise.
### Implementation details:
There are three known possibilities for determining the stride such that the
flipper appears to flip 'inside' the level:
* max-angle/steps -- If flipper is going clockwise and max-angle is less
than zero, or if flipper is going counter-clockwise and max-angle is
greater than zero.
* (max-angle - 2PI)/steps -- If flipper is going clockwise and max-angle
is greater than zero.
* (max-angle + 2PI)/steps -- If flipper is going counter-clockwise and
max-angle is less than zero.
"
[max-angle steps cw?]
(let [dir0 (/ max-angle steps)
dir1 (/ (- max-angle 6.2831853) steps)
dir2 (/ (+ max-angle 6.2831853) steps)]
(cond
(<= max-angle 0) (if cw? dir0 dir2)
:else (if cw? dir1 dir0))))
(defn mark-flipper-for-flipping
"Updates a flipper's map to indicate that it is currently flipping in the
given direction, to the given segment index. cw? should be true if
flipping clockwise, false for counter-clockwise."
[flipper direction seg-idx cw?]
(let [point (path/flip-point-between-segments
(:level flipper)
(:segment flipper)
seg-idx
(:step flipper)
cw?)
max-angle (path/flip-angle-between-segments
(:level flipper)
(:segment flipper)
seg-idx
cw?)
step-count (:flip-step-count flipper)
stride (flip-angle-stride max-angle step-count cw?)
permanent (if (= (:steps (:level flipper))
(:step flipper)) direction nil)]
(assoc flipper
:stride 0
:old-stride (:stride flipper)
:flip-dir direction
:flip-cur-angle 0
:flip-to-segment seg-idx
:flip-point point
:flip-max-angle max-angle
:flip-stride stride
:flip-steps-remaining step-count
:flip-permanent-dir permanent)))
(defn update-entity-stop-flipping
"Updates an entity and marks it as not currently flipping."
[flipper]
(assoc flipper
:stride (:old-stride flipper)
:flip-dir (DirectionEnum "NONE")
:flip-cur-angle 0
:segment (:flip-to-segment flipper)))
(defn random-direction
"Returns a random direction from DirectionEnum (not 'NONE')"
[]
(condp = (rand-int 2)
0 (DirectionEnum "CW")
(DirectionEnum "CCW")))
(defn segment-for-flip-direction
"Returns the segment that the given flipper would flip into if it flipped
in direction flip-dir. If the flipper can't flip that way, it will
return the flipper's current segment."
[flipper flip-dir]
(condp = flip-dir
(DirectionEnum "CW") (segment-entity-cw flipper)
(segment-entity-ccw flipper)))
(defn swap-flipper-permanent-dir
"Given a flipper with its 'permanent direction' set, this swaps the
permanent direction to be opposite. A flipper's permanent direction is
the direction it flips constantly along the outermost edge of the level
until it hits a boundary."
[flipper]
(let [cur-dir (:flip-permanent-dir flipper)
new-dir (if (= (DirectionEnum "CW") cur-dir)
(DirectionEnum "CCW")
(DirectionEnum "CW"))]
(assoc flipper :flip-permanent-dir new-dir)))
(defn engage-flipping
"Mark flipper as flipping in given direction, unless no segment is in
that direction."
[flipper flip-dir]
(let [flip-seg-idx (segment-for-flip-direction flipper flip-dir)
cw? (= flip-dir (DirectionEnum "CW"))]
(if (not= flip-seg-idx (:segment flipper))
(mark-flipper-for-flipping flipper flip-dir
flip-seg-idx cw?)
flipper)))
(defn maybe-engage-flipping
"Given a flipper, returns the flipper possibly modified to be in a state
of flipping to another segment. This will always be true if the flipper
is on the outermost edge of the level, and will randomly be true if it
has not reached the edge."
[flipper]
(let [should-flip (and
(true? (:can-flip flipper))
(= (:flip-dir flipper) (DirectionEnum "NONE"))
(or (<= (rand) (:flip-probability flipper))
(= (:step flipper) (:steps (:level flipper)))))
permanent-dir (:flip-permanent-dir flipper)
flip-dir (or permanent-dir (random-direction))
flip-seg-idx (segment-for-flip-direction flipper flip-dir)
cw? (= flip-dir (DirectionEnum "CW"))]
(cond
(false? should-flip) flipper
(not= flip-seg-idx (:segment flipper)) (mark-flipper-for-flipping
flipper flip-dir
flip-seg-idx cw?)
(not (nil? permanent-dir)) (swap-flipper-permanent-dir flipper)
:else flipper)))
(defn mark-player-captured
"Marks player as being captured."
[player]
(assoc player
:captured? true
:stride -4))
(defn mark-enemy-capturing
"Marks enemy as having captured the player."
[enemy]
(assoc enemy
:capturing true
:can-flip false
:step (- (:step enemy) 10) ;; looks better if enemy leads player
:stride -4))
(defn enemy-is-on-player?
"Returns true if given enemy and player are on top of each other."
[player enemy]
(and (= (:segment player) (:segment enemy))
(= (:step player) (:step enemy))
(= (DirectionEnum "NONE") (:flip-dir enemy))))
(defn player-and-enemies-if-captured
"Given player and current list of enemies, returns an updated player
and updated enemy list if an enemy is capturing the player in vector
[player enemy-list]. Returns nil if no capture occurred."
[player enemy-list]
(let [{colliders true missers false}
(group-by (partial enemy-is-on-player? player) enemy-list)]
(when-let [[enemy & rest] colliders]
[(mark-player-captured player)
(cons (mark-enemy-capturing enemy) (concat missers rest))])))
(defn check-if-player-captured
"If player is not already captured, checks all enemies to see if they
are now capturing the player. See player-and-enemies-if-captured.
If capture is in progress, returns game-state with player and enemy-list
updated."
[game-state]
(if (:captured? (:player game-state))
game-state
(if-let [[player enemy-list] (player-and-enemies-if-captured
(:player game-state)
(:enemy-list game-state))]
(assoc game-state :enemy-list enemy-list :player player)
game-state)))
(defn update-entity-is-flipping
"Decide if an enemy should start flipping for every enemy on the level."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (map maybe-engage-flipping enemy-list))))
(defn update-entity-flippyness
"Update the position of any actively flipping enemy for every enemy on the
level."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (map update-flip-angle enemy-list))))
(defn update-flip-angle
"Given a flipper in the state of flipping, updates its current angle. If
the update would cause it to 'land' on its new segment, the flipper is
updated and returned as a no-longer-flipping. If the given enemy is
not flipping, returns it unchanged."
[flipper]
(let [new-angle (+ (:flip-stride flipper) (:flip-cur-angle flipper))
remaining (dec (:flip-steps-remaining flipper))
new-seg (if (<= remaining (/ (:flip-step-count flipper) 2))
(:flip-to-segment flipper)
(:segment flipper))]
(if (not= (:flip-dir flipper) (DirectionEnum "NONE"))
(if (< remaining 0)
(update-entity-stop-flipping flipper)
(assoc flipper
:damage-segment new-seg
:flip-cur-angle new-angle
:flip-steps-remaining remaining))
flipper)))
(defn build-player
"Returns a dictionary describing a player on the given level and segment."
[level seg-idx]
{:segment seg-idx
:level level
:captured? false
:step (:steps level)
:bullet-stride -5
:stride 0
:path path/*player-path*
:is-dead? false
})
(defn entity-next-step
"Returns the next step position of given entity, taking into account
minimum and maximum positions of the level."
[entity]
(let [stride (:stride entity)
maxstep (:steps (:level entity))
newstep (+ stride (:step entity))]
(cond
(> newstep maxstep) maxstep
(< newstep 0) 0
:else newstep)))
(defn update-entity-position!
"Return entity updated with a new position based on its current location and
stride. Won't go lower than 0, or higher than the maximum steps of the
level."
[entity]
(assoc entity :step (entity-next-step entity)))
(defn update-entity-list-positions
"Call update-entity-position! on all entities in list."
[entity-list]
(map update-entity-position! entity-list))
(defn update-entity-direction!
"Updates an enemy to travel in the opposite direction if he has reached
his maximum allowable step. This is used for Spikers, which travel
back down the level after laying spikes."
[entity]
(let [{:keys [step max-step stride]} entity
newstride (if (>= step max-step) (- stride) stride)]
(assoc entity :stride newstride)))
(defn update-entity-list-directions
"Apply update-entity-direction! to all enemies in the given list that have
a maximum step."
[entity-list]
(let [{spikers true others false}
(group-by #(contains? % :max-step) entity-list)]
(concat others (map update-entity-direction! spikers))))
(defn entity-between-steps
"Returns true of entity is on seg-idx, and between steps step0 and step1,
inclusive."
[seg-idx step0 step1 entity]
(let [min (min step0 step1)
max (max step0 step1)]
(and
(= (:damage-segment entity) seg-idx)
(>= (:step entity) min)
(<= (:step entity) max))))
(defn projectiles-after-collision
"Given an entity and a list of projectiles, returns the entity and updated
list of projectiles after collisions. The entity's hits-remaining counter
is decremented on a collision, and the projectile is removed. Small amount
of fudge factor (1 step += actual projectile location) to avoid narrow
misses in the collision algorithm."
[entity projectile-list]
((fn [entity projectiles-in projectiles-out was-hit?]
(if (empty? projectiles-in)
{:entity entity :projectiles projectiles-out :was-hit? was-hit?}
(let [bullet (first projectiles-in)
collision? (entity-between-steps
(:segment bullet)
(inc (:step bullet))
(dec (entity-next-step bullet))
entity)]
(if (and (not (:from-enemy? bullet)) collision?)
(recur (decrement-enemy-hits entity)
nil
(concat projectiles-out (rest projectiles-in))
true)
(recur entity
(rest projectiles-in)
(cons bullet projectiles-out)
was-hit?)))))
entity projectile-list '() false))
(defn entities-after-collisions
"Given a list of entities and a list of projectiles, returns the lists
with entity hit counts updated, entities removed if they have no hits
remaining, and collided projectiles removed.
See projectiles-after-collision, which is called for each entity in
entity-list."
[entity-list projectile-list]
((fn [entities-in entities-out projectiles-in]
(if (empty? entities-in)
{:entities entities-out :projectiles projectiles-in}
(let [{entity :entity projectiles :projectiles was-hit? :was-hit?}
(projectiles-after-collision (first entities-in)
projectiles-in)]
(recur (rest entities-in)
(cons entity entities-out)
projectiles))))
entity-list '() projectile-list))
(defn new-flippers-from-tanker
"Spawns two new flippers from one tanker. These flippers are automatically
set to be flipping to the segments surround the tanker, unless one of the
directions is blocked, in which case that flipper just stays on the tanker's
segment."
[enemy]
(let [{:keys [segment level step]} enemy]
(list
(engage-flipping
(build-flipper level segment :step step)
(DirectionEnum "CW"))
(engage-flipping
(build-flipper level segment :step step)
(DirectionEnum "CCW")))))
(defn enemy-list-after-deaths
"Returns the enemy list updated for deaths. This means removing enemies
that died, and possibly adding new enemies for those that spawn children
on death."
[enemy-list]
(let [{live-enemies false dead-enemies true}
(group-by #(zero? (:hits-remaining %)) enemy-list)]
(loop [[enemy & enemies] dead-enemies
enemies-out '()]
(cond
(nil? enemy) (concat live-enemies enemies-out)
(= (:type enemy) (EnemyEnum "TANKER"))
(recur enemies (concat (new-flippers-from-tanker enemy) enemies-out))
:else (recur enemies enemies-out)))))
(defn handle-dead-enemies
"Return game state after handling dead enemies, by removing them and possibly
replacing them with children."
[game-state]
(let [enemy-list (:enemy-list game-state)]
(assoc game-state :enemy-list (enemy-list-after-deaths enemy-list))))
(defn enemy-list-after-exiting-spikers
"Returns an updated copy of the given list of enemies with spikers removed
if they have returned to the innermost edge of the level. Spikers travel
out towards the player a random distance, then turn around and go back in.
They disappear when they are all the way in."
[enemy-list]
(let [{spikers true others false}
(group-by #(= (:type %) (EnemyEnum "SPIKER")) enemy-list)]
(loop [[enemy & enemies] spikers
enemies-out '()]
(cond
(nil? enemy) (concat others enemies-out)
(and (neg? (:stride enemy)) (zero? (:step enemy)))
(recur enemies enemies-out)
:else
(recur enemies (cons enemy enemies-out))))))
(defn handle-exiting-spikers
"Apply enemy-list-after-exiting-spikers to the enemy list and update game
state. This removes any spikers that are ready to disappear."
[game-state]
(let [enemy-list (:enemy-list game-state)]
(assoc game-state
:enemy-list (enemy-list-after-exiting-spikers enemy-list))))
(defn spikes-after-spike-laying
"Given a list of spikers and the current length of spikes on each segment,
this updates the spike lengths to be longer if a spiker has traveled past
the edge of an existing spike. Returns [enemy-list spikes]"
[enemy-list spikes]
(loop [[enemy & enemies] enemy-list
spikes-out spikes]
(let [{:keys [step segment]} enemy
spike-step (nth spikes-out segment)]
(cond
(nil? enemy) spikes-out
(>= step spike-step) (recur enemies (assoc spikes-out segment step))
:else (recur enemies spikes-out)))))
(defn handle-spike-laying
"Updates the length of spikes on the level. See spikes-after-spike-laying."
[game-state]
(let [enemy-list (:enemy-list game-state)
spikes (:spikes game-state)
spiker-list (filter #(= (:type %) (EnemyEnum "SPIKER")) enemy-list)]
(assoc game-state :spikes (spikes-after-spike-laying spiker-list spikes))))
(defn kill-tanker-at-top
"If the given tanker is at the top of a level, mark it as dead. Tankers
die when they reach the player, and split into two flippers."
[tanker]
(let [step (:step tanker)
maxstep (:steps (:level tanker))]
(if (= step maxstep)
(assoc tanker :hits-remaining 0)
tanker)))
(defn maybe-split-tankers
"Marks tankers at the top of the level as ready to split into flippers."
[game-state]
(let [enemy-list (:enemy-list game-state)
{tankers true others false}
(group-by #(= (:type %) (EnemyEnum "TANKER")) enemy-list)]
(assoc game-state
:enemy-list (concat (map kill-tanker-at-top tankers) others))))
(defn mark-player-if-spiked
"Marks the player as dead and sets up the animation flags to trigger a
level reload if the player has impacted a spike while traveling down the
level."
[game-state]
(let [{:keys [spikes player]} game-state step (:step player)
;; TODO: (nth) caused an error here once, spikes was length 0.
segment (:segment player) spike-len (nth spikes segment)]
(cond
(zero? spike-len) game-state
(<= step spike-len)
(assoc game-state
:player (assoc player :is-dead? true)
:is-zooming? true
:zoom-in? false
:player-zooming? false)
:else game-state)))
(defn animate-player-shooping
"Updates the player's position as he travels ('shoops') down the level after
defeating all enemies. Player moves relatively slowly. Camera zooms in
(actually, level zooms out) a little slower than the player moves. After
player reaches bottom, camera zooms faster. Level marked as finished when
zoom level is very high (10x normal)."
[game-state]
(let [player (:player game-state)
level (:level game-state)
zoom (:zoom game-state)]
(cond
(:level-done? game-state) game-state
(>= zoom 10) (assoc game-state :level-done? true)
(zero? (:step player)) (assoc game-state :zoom (+ zoom .2))
:else (assoc game-state
:player (update-entity-position! player)
:zoom (+ 1 (/ (- (:steps level) (:step player)) 150))
:is-zooming? true
:zoom-in? false
))))
(defn animate-player-capture
"Updates player's position on board while player is in the process of being
captured by an enemy, and marks player as dead when he reaches the inner
boundary of the level. When player dies, level zoom-out is initiated."
[game-state]
(let [player (:player game-state)
captured? (:captured? player)
isdead? (zero? (:step player))]
(cond
(false? captured?) game-state
(true? isdead?) (assoc (clear-level-entities game-state)
:player (assoc player :is-dead? true)
:is-zooming? true
:zoom-in? false)
:else (assoc game-state :player (update-entity-position! player)))))
(defn clear-level-entities
"Clears enemies, projectiles, and spikes from level."
[game-state]
(assoc game-state
:enemy-list '()
:projectile-list '()
:spikes []))
(defn update-zoom
"Updates current zoom value of the level, based on direction of :zoom-in?
in the game-state. This is used to animate the board zooming in or
zooming out at the start or end of a round. If this was a zoom out, and
it's finished, mark the level as done so it can restart."
[game-state]
(let [zoom (:zoom game-state)
zoom-in? (:zoom-in? game-state)
zoom-step 0.04
newzoom (if zoom-in? (+ zoom zoom-step) (- zoom zoom-step))
target (if zoom-in? 1.0 0.0)
cmp (if zoom-in? >= <=)]
(if (cmp zoom target) (assoc game-state
:is-zooming? false
:level-done? (not zoom-in?))
(if (cmp newzoom target)
(assoc game-state :zoom target)
(assoc game-state :zoom newzoom)))))
(defn clear-player-segment
"Returns game-state unchanged, and as a side affect clears the player's
current segment back to blue. To avoid weird color mixing, it is cleared
to black first (2px wide), then redrawn as blue (1.5px wide). This looks
right, but is different from how the board is drawn when done all at once."
[game-state]
(do
(set! (. (:bgcontext game-state) -lineWidth) 2)
(draw/draw-player-segment game-state {:r 0 :g 0 :b 0})
(set! (. (:bgcontext game-state) -lineWidth) 1.5)
(draw/draw-player-segment game-state {:r 10 :g 10 :b 100})
game-state))
(defn highlight-player-segment
"Returns game-state unchanged, and as a side effect draws the player's
current segment with a yellow border."
[game-state]
(do
(set! (. (:bgcontext game-state) -lineWidth) 1)
(draw/draw-player-segment game-state {:r 150 :g 150 :b 15})
game-state))
(defn draw-board
"Draws the level when level is zooming in or out, and updates the zoom level.
This doesn't redraw the board normally, since the board is drawn on a
different HTML5 canvas than the players for efficiency."
[game-state]
(let [is-zooming? (:is-zooming? game-state)
zoom (:zoom game-state)
{width :width height :height} (:dims game-state)]
(if is-zooming?
(do
(draw/clear-context (:bgcontext game-state) (:dims game-state))
(draw/draw-board (assoc game-state
:dims {:width (/ width zoom)
:height (/ height zoom)}))
(if (:player-zooming? game-state)
game-state
(update-zoom game-state)))
game-state)))
(defn collisions-with-projectile
"Returns map with keys true and false. Values under true key have or
will collide with bullet in the next bullet update. Values under the
false key will not."
[enemy-list bullet]
(group-by (partial entity-between-steps
(:segment bullet)
(:step bullet)
(entity-next-step bullet))
enemy-list))
(defn decrement-enemy-hits
"Decrement hits-remaining count on given enemy."
[enemy]
(assoc enemy :hits-remaining (dec (:hits-remaining enemy))))
(defn projectile-off-level?
"Returns true if a projectile has reached either boundary of the level."
[projectile]
(cond
(zero? (:step projectile)) true
(>= (:step projectile) (:steps (:level projectile))) true
:else false))
(defn add-enemy-projectile
"Add a new projectile to the global list of live projectiles, originating
from the given enemy, on the segment he is currently on."
[projectile-list enemy]
(let [level (:level enemy)
seg-idx (:segment enemy)
stride (+ (:stride enemy) 2)
step (:step enemy)]
(conj projectile-list
(build-projectile level seg-idx stride :step step :from-enemy? true))))
(defn add-player-projectile
"Add a new projectile to the global list of live projectiles, originating
from the given player, on the segment he is currently on."
[projectile-list player]
(let [level (:level player)
seg-idx (:segment player)
stride (:bullet-stride player)
step (:step player)]
(conj projectile-list
(build-projectile level seg-idx stride :step step))))
(defn segment-entity-cw
"Returns the segment to the left of the player. Loops around the level
on connected levels, and stops at 0 on unconnected levels."
[player]
(let [level (:level player)
seg-max (dec (count (:segments level)))
cur-seg (:segment player)
loops? (:loops? level)
new-seg (dec cur-seg)]
(if (< new-seg 0)
(if loops? seg-max 0)
new-seg)))
(defn segment-entity-ccw
"Returns the segment to the right of the player. Loops around the level
on connected levels, and stops at max on unconnected levels."
[player]
(let [level (:level player)
seg-max (dec (count (:segments level)))
cur-seg (:segment player)
loops? (:loops? level)
new-seg (inc cur-seg)]
(if (> new-seg seg-max)
(if loops? 0 seg-max)
new-seg)))
(defn queue-keypress
"Atomically queue keypress in global queue for later handling. This should
be called as the browser's key-handling callback."
[event]
(let [key (.-keyCode event)]
(swap! *key-event-queue* #(concat % [key]))
(.preventDefault event)
(.stopPropagation event)))
(defn dequeue-keypresses-while-paused
"See dequeue-keypresses for details. This unqueues all keypresses, but only
responds to unpause."
[game-state]
(loop [state game-state
queue @*key-event-queue*]
(if (empty? queue)
state
(let [key (first queue)
valid? (compare-and-set! *key-event-queue* queue (rest queue))]
(if valid?
(recur (handle-keypress-unpause state key) @*key-event-queue*)
(recur state @*key-event-queue*))))))
(defn handle-keypress-unpause
"See handle-keypress. This version only accepts unpause."
[game-state key]
(let [paused? (:paused? game-state)]
(condp = key
key-codes/ESC (assoc game-state :paused? (not paused?))
game-state)))
(defn handle-keypress
"Returns new game state updated to reflect the results of a player's
keypress.
## Key map
* Right -- Move counter-clockwise
* Left -- Move clockwise
* Space -- Shoot
* Escape -- Pause
"
[game-state key]
(let [player (:player game-state)
projectile-list (:projectile-list game-state)
paused? (:paused? game-state)]
(condp = key
key-codes/RIGHT (assoc game-state
:player
(assoc player :segment (segment-entity-ccw player)))
key-codes/LEFT (assoc game-state
:player
(assoc player :segment (segment-entity-cw player)))
key-codes/SPACE (assoc game-state
:projectile-list
(add-player-projectile projectile-list player))
key-codes/ESC (assoc game-state :paused? (not paused?))
game-state)))
(defn dequeue-keypresses
"Atomically dequeue keypresses from global queue and pass to handle-keypress,
until global queue is empty. Returns game state updated after applying
all keypresses.
Has a side effect of clearing global *key-event-queue*.
## Implementation details:
Use compare-and-set! instead of swap! to test against the value we
entered the loop with, instead of the current value. compare-and-set!
returns true only if the update was a success (i.e. the queue hasn't
changed since entering the loop), in which case we handle the key.
If the queue has changed, we do nothing. The loop always gets called
again with the current deref of the global state.
"
[game-state]
(loop [state game-state
queue @*key-event-queue*]
(if (empty? queue)
state
(let [key (first queue)
valid? (compare-and-set! *key-event-queue* queue (rest queue))]
(cond
(not valid?) (recur state @*key-event-queue*)
(not (:captured? (:player game-state))) (recur (handle-keypress
state
key)
@*key-event-queue*)
:else (recur (handle-keypress-unpause state key) @*key-event-queue*)
)))))
(defn animationFrameMethod
"Returns a callable javascript function to schedule a frame to be drawn.
Tries to use requestAnimationFrame, or the browser-specific version of
it that is available. Falls back on setTimeout if requestAnimationFrame
is not available on player's browser.
requestAnimationFrame tries to figure out a consistent framerate based
on how long frame takes to render.
The setTimeout fail-over is hard-coded to attempt 30fps.
"
[]
(let [window (dom/getWindow)
names ["requestAnimationFrame"
"webkitRequestAnimationFrame"
"mozRequestAnimationFrame"
"oRequestAnimationFrame"
"msRequestAnimationFrame"]
options (map (fn [name] #(aget window name)) names)]
((fn [[current & remaining]]
(cond
(nil? current) #((.-setTimeout window) % (/ 1000 30))
(fn? (current)) (current)
:else (recur remaining)))
options)))
(defn clear-frame
"Returns game state unmodified, clears the HTML5 canvas as a side-effect."
[game-state]
(do
(draw/clear-context (:context game-state) (:dims game-state))
game-state))
(defn render-frame
"Draws the current game-state on the HTML5 canvas. Returns the game state
unmodified (drawing is a side-effect)."
[game-state]
(let [{context :context
dims :dims
level :level
enemy-list :enemy-list
projectile-list :projectile-list
player :player}
game-state
{enemy-shots true player-shots false}
(group-by :from-enemy? projectile-list)
zoom (:zoom game-state)
zoom-dims {:width (/ (:width dims) zoom)
:height (/ (:height dims) zoom)}]
(draw/draw-all-spikes (assoc game-state :dims zoom-dims))
(if (not (:is-dead? player))
(draw/draw-player context zoom-dims level player (:zoom game-state)))
(draw/draw-entities context zoom-dims level
enemy-list
{:r 150 :g 10 :b 10}
zoom)
(draw/draw-entities context zoom-dims level
player-shots
{:r 255 :g 255 :b 255}
zoom)
(draw/draw-entities context zoom-dims level
enemy-shots
{:r 150 :g 15 :b 150}
zoom)
game-state))
(defn remove-collided-entities
"Detects and removes projectiles that have collided with enemies, and enemies
whose hit counts have dropped to zero. Returns updated game-state."
[game-state]
(let [{enemy-list :enemy-list
projectile-list :projectile-list}
game-state]
(let [{plist :projectiles elist :entities}
(entities-after-collisions enemy-list projectile-list)]
(assoc game-state
:projectile-list plist
:enemy-list elist))))
(defn bullets-will-collide?
"Returns true if two bullets will collide within the next frame, and one is
from the player and the other is from an enemy."
[bullet1 bullet2]
(let [max-stride (max (:stride bullet1) (:stride bullet2))
min-stride (min (:stride bullet1) (:stride bullet2))
step1 (:step bullet1)
step2 (:step bullet2)
next-step1 (entity-next-step bullet1)
next-step2 (entity-next-step bullet2)]
(and (or (and (>= step1 step2) (<= next-step1 next-step2))
(and (>= step2 step1) (<= next-step2 next-step1)))
(neg? min-stride)
(pos? max-stride)
(if (:from-enemy? bullet1)
(not (:from-enemy? bullet2))
(:from-enemy? bullet2)))))
(defn projectile-list-without-collisions
"Given a list of projectiles, returns the list minus any bullet-on-bullet
collisions that occur within it."
[projectiles]
(loop [[bullet & others] projectiles
survivors '()]
(if (nil? bullet) survivors
(let [{not-hit false hit true}
(group-by #(bullets-will-collide? bullet %) others)]
(if-not (empty? hit)
(recur (concat not-hit (rest hit)) survivors)
(recur others (cons bullet survivors)))))))
(defn remove-collided-bullets
"Remove bullets that have hit each other. Only player-vs-enemy collisions
count. Breaks list of projectiles into one list per segment, and then
runs projectile-list-without-collisions on each of those lists to get
back a final list of only bullets that aren't involved in collisions."
[game-state]
(let [projectile-list (:projectile-list game-state)
segment-lists (vals (group-by :segment projectile-list))
non-collided (mapcat projectile-list-without-collisions segment-lists)]
(assoc game-state :projectile-list non-collided)))
(defn decrement-spike-length
"Returns a new spike length based on the given spike length and the number
of times the spike was hit. Spike is arbitrarily shrunk by 10 steps per
hit. If it falls below a short threshhold (5), it is set to zero."
[spike-len hit-count]
(let [new-len (- spike-len (* 10 hit-count))]
(if (<= new-len 5) 0 new-len)))
(defn filter-spike-bullet-collisions
"Given a list of projectiles on a segment (it is mandatory that they all
be on the same segment), and the spike length on that segment, returns
[projectile-list spike-len], where any projectiles that hit the spike
have been removed from projectile-list, and spike-len has been updated
to be shorter if it was hit."
[projectile-list spike-len]
(let [{hit true missed false}
(group-by #(<= (:step %) spike-len) projectile-list)]
[missed (decrement-spike-length spike-len (count hit))]))
(defn remove-spiked-bullets
"Returns the game state with any bullets that hit a spike removed, and any
spikes that were hit shrunk in length."
[game-state]
(let [projectile-list (:projectile-list game-state)
{player-list false enemy-list true}
(group-by :from-enemy? projectile-list)
segmented-projectiles (group-by :segment player-list)]
(loop [[seg-bullets & remaining] segmented-projectiles
spikes (:spikes game-state)
projectiles-out '()]
(if (nil? seg-bullets)
(assoc game-state
:projectile-list (concat projectiles-out enemy-list)
:spikes spikes)
(let [[key bullets] seg-bullets
spike-len (nth spikes key)
[bullets new-len] (filter-spike-bullet-collisions bullets
spike-len)]
(recur remaining
(assoc spikes key new-len)
(concat projectiles-out bullets)))))))
(defn bullets-will-kill-player?
"Returns true given bullet will hit the given player."
[player bullet]
(let [next-step (entity-next-step bullet)
player-step (:step player)]
(and (= player-step next-step)
(:from-enemy? bullet))))
(defn update-player-if-shot
"Updates the player to indicate whether he was shot by an enemy."
[game-state]
(let [projectile-list (:projectile-list game-state)
player (:player game-state)
on-segment (filter #(= (:segment player) (:segment %)) projectile-list)
{hit true miss false} (group-by
#(bullets-will-kill-player? player %)
on-segment)]
(if-not (empty? hit)
(assoc (clear-level-entities game-state)
:player (assoc player :is-dead? true)
:is-zooming? true
:player-zooming? false
:zoom-in? false)
game-state)))
(defn update-projectile-locations
"Returns game-state with all projectiles updated to have new positions
based on their speeds and current position."
[game-state]
(let [{projectile-list :projectile-list} game-state
rm-fn (partial remove projectile-off-level?)]
(assoc game-state
:projectile-list (-> projectile-list
update-entity-list-positions
rm-fn))))
(defn update-enemy-locations
"Returns game-state with all of the enemies updated to have new positions
based on their speeds and current position."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (update-entity-list-positions enemy-list))))
(defn update-enemy-directions
"Return game state with any enemies who were ready to turn around marked to
travel in the opposite direction."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (update-entity-list-directions enemy-list))))
(defn schedule-next-frame
"Tells the player's browser to schedule the next frame to be drawn, using
whatever the best mechanism the browser has to do so."
[game-state]
((:anim-fn game-state) #(next-game-state game-state)))
(defn update-frame-count
"Increments the game-state's frame counter, which is a count of frames since
the last FPS measurement."
[game-state]
(let [{frame-count :frame-count}
game-state]
(assoc game-state :frame-count (inc frame-count))))
(defn render-fps-display
"Print a string representation of the most recent FPS measurement in
an HTML element named 'fps'. This resets the frame-count and frame-time
currently stored in the game state."
[game-state]
(let [{frame-count :frame-count
frame-time :frame-time}
game-state
fps (/ (* 1000 frame-count) (- (goog.now) frame-time))
str-fps (pr-str (util/round fps))]
(dom/setTextContent (dom/getElement "fps") (str "FPS: " str-fps))
(assoc game-state
:frame-count 0
:frame-time (goog.now))))
(defn maybe-render-fps-display
"Calls render-fps-display if the frame-count is above a certain threshhold."
[game-state]
(if (= (:frame-count game-state) 20)
(render-fps-display game-state)
game-state))
| true | ;;
;; This file is part of tempest-cljs
;; Copyright (c) 2012, PI:NAME:<NAME>END_PI
;; All rights reserved.
;; See LICENSE file for details.
;;
(ns ^{:doc "
Functions related to the game of tempest, and game state.
Functions in this module create the game state, and modify it based on
player actions or time. This includes management of entities such as
the player's ship, enemies, and projectiles.
Enemy types:
* **Flipper** -- Moves quickly up level, flips randomly to adjacent segments,
and shoots. When a flipper reaches the outer edge, he flips endlessly
back and forth along the perimeter. If he touches the player, he carries
the player down the level and the player is dead.
* **Tanker** -- Moves slowly, shoots, and never leaves his segment. If a
tanker is shot or reaches the outer edge, it is destroyed and two
flippers flip out of it in opposite directions.
* **Spiker** -- Moves quickly, shoots, and lays a spike on the level where it
travels. Spikers cannot change segments. The spiker turns around when it
reaches a random point on the level and goes back down, and disappears if
it reaches the inner edge. The spike it lays remains, and can be shot.
If the player kills all the enemies, he must fly down the level and avoid
hitting any spikes, or he will be killed.
"}
tempest.core
(:require [tempest.levels :as levels]
[tempest.util :as util]
[tempest.draw :as draw]
[tempest.path :as path]
[goog.dom :as dom]
[goog.events :as events]
[goog.events.KeyCodes :as key-codes]
[clojure.browser.repl :as repl])
(:require-macros [tempest.macros :as macros]))
;;(repl/connect "http://localhost:9000/repl")
;; ---
(defn next-game-state
"**Main logic loop**
Given the current game-state, threads it through a series of functions that
calculate the next game-state. This is the most fundamental call in the
game; it applies all of the logic.
The last call, schedule-next-frame, schedules this function to be called
again by the browser sometime in the future with the update game-state
after passing through all the other functions. This implements the game loop.
This function actualy dispatches to one of multiple other functions, starting
with the 'game-logic-' prefix, that actually do the function threading. This
is because the game's main loop logic changes based on a few possible states:
* Normal, active gameplay is handled by game-logic-playable. This is the
longest path, and has to handle all of the gameplay logic, collision
detection, etc.
* Animation of levels zooming in and out, when first loading or after the
player dies, are handled by game-logic-non-playable. Most of the game
logic is disabled during this stage, as it is primarily displaying a
non-interactive animation.
* 'Shooping' is what I call the end-of-level gameplay, after all enemies are
defeated, when the player's ship travels down the level and must destroy
or avoid any spikes remaining. All of the game logic regarding enemies is
disabled in this path, but moving and shooting still works.
* The 'Paused' state is an extremely reduced state that only listens for the
unpause key.
"
[game-state]
(cond
(:paused? game-state) (game-logic-paused game-state)
(:player-zooming? game-state)
(game-logic-player-shooping-down-level game-state)
(and (:is-zooming? game-state))
(game-logic-non-playable game-state)
:else (game-logic-playable game-state)))
(defn game-logic-paused
"Called by next-game-state when game is paused. Just listens for keypress
to unpause game."
[game-state]
(->> game-state
dequeue-keypresses-while-paused
schedule-next-frame))
(defn game-logic-player-shooping-down-level
"That's right, I named it that. This is the game logic path that handles
the player 'shooping' down the level, traveling into it, after all enemies
have been defeated. The player can still move and shoot, and can kill or
be killed by spikes remaining on the level."
[game-state]
(->> game-state
clear-player-segment
dequeue-keypresses
highlight-player-segment
clear-frame
draw-board
render-frame
remove-spiked-bullets
update-projectile-locations
animate-player-shooping
mark-player-if-spiked
maybe-change-level
update-frame-count
maybe-render-fps-display
schedule-next-frame
))
(defn game-logic-playable
"Called by next-game-state when game and player are active. This logic path
handles all the good stuff: drawing the player, drawing the board, enemies,
bullets, spikes, movement, player capture, player death, etc."
[game-state]
(let [gs1 (->> game-state
clear-player-segment
dequeue-keypresses
highlight-player-segment
maybe-change-level
clear-frame
draw-board
render-frame)
gs2 (->> gs1
remove-spiked-bullets
remove-collided-entities
remove-collided-bullets
update-projectile-locations
update-enemy-locations
update-enemy-directions
maybe-split-tankers
handle-dead-enemies
handle-exiting-spikers
maybe-enemies-shoot)
gs3 (->> gs2
handle-spike-laying
maybe-make-enemy
check-if-enemies-remain
check-if-player-captured
update-player-if-shot
update-entity-is-flipping
update-entity-flippyness
animate-player-capture
update-frame-count
maybe-render-fps-display)]
(->> gs3 schedule-next-frame)))
(defn game-logic-non-playable
"Called by next-game-state for non-playable animations. This is used when
the level is quickly zoomed in or out between stages or after the player
dies. Most of the game logic is disabled during this animation."
[game-state]
(->> game-state
dequeue-keypresses-while-paused
clear-frame
draw-board
render-frame
update-frame-count
maybe-render-fps-display
schedule-next-frame))
;; ---
(def ^{:doc
"Global queue for storing player's keypresses. The browser
sticks keypresses in this queue via callback, and keys are
later pulled out and applied to the game state during the
game logic loop."}
*key-event-queue* (atom '()))
(defn build-game-state
"Returns an empty game-state map."
[]
{:enemy-list '()
:projectile-list '()
:player '()
:spikes []
:context nil
:bgcontext nil
:anim-fn identity
:dims {:width 0 :height 0}
:level-idx 0
:level nil
:frame-count 0
:frame-time 0
:paused? false
:is-zooming? true
:zoom-in? true
:zoom 0.0
:level-done? false
:player-zooming? false
})
(defn check-if-enemies-remain
"If no enemies are left on the level, and no enemies remain to be launched
mark level as zooming out."
[game-state]
(let [level (:level game-state)
player (:player game-state)
on-board (count (:enemy-list game-state))
unlaunched (apply + (vals (:remaining level)))
remaining (+ on-board unlaunched)]
(if (zero? remaining)
(assoc game-state
:player (assoc player :stride -2)
:player-zooming? true)
game-state)))
(defn change-level
"Changes current level of game."
[game-state level-idx]
(let [level (get levels/*levels* level-idx)]
(assoc game-state
:level-idx level-idx
:level level
:player (build-player level 0)
:zoom 0.0
:zoom-in? true
:is-zooming? true
:level-done? false
:player-zooming? false
:projectile-list '()
:enemy-list '()
:spikes (vec (take (count (:segments level)) (repeat 0))))))
(defn maybe-change-level
"Reloads or moves to the next level if player is dead, or if all enemies are
dead."
[game-state]
(let [player (:player game-state)
level (:level game-state)]
(cond
(and (:is-dead? player) (:level-done? game-state))
(change-level game-state (:level-idx game-state))
(and (not (:is-dead? player)) (:level-done? game-state))
(change-level game-state (inc (:level-idx game-state)))
:else game-state)))
(defn build-projectile
"Returns a dictionary describing a projectile (bullet) on the given level,
in the given segment, with a given stride (steps per update to move, with
negative meaning in and positive meaning out), and given step to start on."
[level seg-idx stride & {:keys [step from-enemy?]
:or {step 0 from-enemy? false}}]
{:step step
:stride stride
:segment seg-idx
:damage-segment seg-idx
:level level
:path-fn path/projectile-path-on-level
:from-enemy? from-enemy?
})
(def ^{:doc "Enumeration of directions a flipper can be flipping."}
DirectionEnum {"NONE" 0 "CW" 1 "CCW" 2})
(def ^{:doc "Enumeration of types of enemies."}
EnemyEnum {"NONE" 0 "FLIPPER" 1 "TANKER" 2
"SPIKER" 3 "FUSEBALL" 4 "PULSAR" 5})
(defn direction-string-from-value
"Given a value from DirectionEnum, return the corresponding string."
[val]
(first (first (filter #(= 1 (peek %)) (into [] maptest)))))
(defn build-enemy
"Returns a dictionary describing an enemy on the given level and segment,
and starting on the given step. Step defaults to 0 (innermost step of
level) if not specified."
[level seg-idx & {:keys [step] :or {step 0}}]
{:step step
:stride 1
:segment seg-idx
:damage-segment seg-idx
:level level
:hits-remaining 1
:path-fn #([])
:flip-dir (DirectionEnum "NONE")
:flip-point [0 0]
:flip-stride 1
:flip-max-angle 0
:flip-cur-angle 0
:flip-probability 0
:can-flip false
:shoot-probability 0
:type (EnemyEnum "NONE")
})
(defn build-tanker
"Returns a new tanker enemy. Tankers move slowly and do not shoot or flip."
[level seg-idx & {:keys [step] :or {step 0}}]
(assoc (build-enemy level seg-idx :step step)
:type (EnemyEnum "TANKER")
:path-fn path/tanker-path-on-level
:can-flip false
:stride 0.2
:shoot-probability 0.0
))
(defn build-spiker
"Returns a new spiker enemy. Spiker cannot change segments, travels quickly,
and turns around on a random step, where 20 <= step <= max_step - 20.
Spikers can shoot, and they lay spikes behind them as they move."
[level seg-idx & {:keys [step] :or {step 0}}]
(assoc (build-enemy level seg-idx :step step)
:type (EnemyEnum "SPIKER")
:path-fn path/spiker-path-on-level
:can-flip false
:stride 1
:shoot-probability 0.001
:max-step (+ (rand-int (- (:steps level) 40)) 20)
))
(defn build-flipper
"A more specific form of build-enemy for initializing a flipper."
[level seg-idx & {:keys [step] :or {step 0}}]
(assoc (build-enemy level seg-idx :step step)
:type (EnemyEnum "FLIPPER")
:path-fn path/flipper-path-on-level
:flip-dir (DirectionEnum "NONE")
:flip-point [0 0]
:flip-stride 1
:flip-step-count 20
:flip-max-angle 0
:flip-cur-angle 0
:flip-permanent-dir nil
:flip-probability 0.015
:can-flip true
:shoot-probability 0.004
))
(defn projectiles-after-shooting
"Returns a new list of active projectiles after randomly adding shots from
enemies."
[enemy-list projectile-list]
(loop [[enemy & enemies] enemy-list
projectiles projectile-list]
(if (nil? enemy) projectiles
(if (and (<= (rand) (:shoot-probability enemy))
(not= (:step enemy) (:steps (:level enemy)))
(pos? (:stride enemy)))
(recur enemies (add-enemy-projectile projectiles enemy))
(recur enemies projectiles)))))
(defn maybe-enemies-shoot
"Randomly adds new projectiles coming from enemies based on the enemies'
shoot-probability field. See projectiles-after-shooting."
[game-state]
(let [enemies (:enemy-list game-state)
projectiles (:projectile-list game-state)]
(assoc game-state
:projectile-list (projectiles-after-shooting enemies projectiles))))
(defn maybe-make-enemy
"Randomly create new enemies if the level needs more. Each level has a total
count and probability of arrival for each type of enemy. When a new enemy
is added by this function, the total count for that type is decremented.
If zero enemies are on the board, probability of placing one is increased
two-fold to avoid long gaps with nothing to do."
[game-state]
(let [flipper-fn (macros/random-enemy-fn flipper)
tanker-fn (macros/random-enemy-fn tanker)
spiker-fn (macros/random-enemy-fn spiker)]
(->> game-state
flipper-fn
tanker-fn
spiker-fn)))
(defn flip-angle-stride
"Returns the angle stride of a flipper, which is how many radians to
increment his current flip angle by to be completely flipped onto his
destination segment (angle of max-angle) on 'steps' number of increments,
going clockwise if cw? is true, or counter-clockwise otherwise.
### Implementation details:
There are three known possibilities for determining the stride such that the
flipper appears to flip 'inside' the level:
* max-angle/steps -- If flipper is going clockwise and max-angle is less
than zero, or if flipper is going counter-clockwise and max-angle is
greater than zero.
* (max-angle - 2PI)/steps -- If flipper is going clockwise and max-angle
is greater than zero.
* (max-angle + 2PI)/steps -- If flipper is going counter-clockwise and
max-angle is less than zero.
"
[max-angle steps cw?]
(let [dir0 (/ max-angle steps)
dir1 (/ (- max-angle 6.2831853) steps)
dir2 (/ (+ max-angle 6.2831853) steps)]
(cond
(<= max-angle 0) (if cw? dir0 dir2)
:else (if cw? dir1 dir0))))
(defn mark-flipper-for-flipping
"Updates a flipper's map to indicate that it is currently flipping in the
given direction, to the given segment index. cw? should be true if
flipping clockwise, false for counter-clockwise."
[flipper direction seg-idx cw?]
(let [point (path/flip-point-between-segments
(:level flipper)
(:segment flipper)
seg-idx
(:step flipper)
cw?)
max-angle (path/flip-angle-between-segments
(:level flipper)
(:segment flipper)
seg-idx
cw?)
step-count (:flip-step-count flipper)
stride (flip-angle-stride max-angle step-count cw?)
permanent (if (= (:steps (:level flipper))
(:step flipper)) direction nil)]
(assoc flipper
:stride 0
:old-stride (:stride flipper)
:flip-dir direction
:flip-cur-angle 0
:flip-to-segment seg-idx
:flip-point point
:flip-max-angle max-angle
:flip-stride stride
:flip-steps-remaining step-count
:flip-permanent-dir permanent)))
(defn update-entity-stop-flipping
"Updates an entity and marks it as not currently flipping."
[flipper]
(assoc flipper
:stride (:old-stride flipper)
:flip-dir (DirectionEnum "NONE")
:flip-cur-angle 0
:segment (:flip-to-segment flipper)))
(defn random-direction
"Returns a random direction from DirectionEnum (not 'NONE')"
[]
(condp = (rand-int 2)
0 (DirectionEnum "CW")
(DirectionEnum "CCW")))
(defn segment-for-flip-direction
"Returns the segment that the given flipper would flip into if it flipped
in direction flip-dir. If the flipper can't flip that way, it will
return the flipper's current segment."
[flipper flip-dir]
(condp = flip-dir
(DirectionEnum "CW") (segment-entity-cw flipper)
(segment-entity-ccw flipper)))
(defn swap-flipper-permanent-dir
"Given a flipper with its 'permanent direction' set, this swaps the
permanent direction to be opposite. A flipper's permanent direction is
the direction it flips constantly along the outermost edge of the level
until it hits a boundary."
[flipper]
(let [cur-dir (:flip-permanent-dir flipper)
new-dir (if (= (DirectionEnum "CW") cur-dir)
(DirectionEnum "CCW")
(DirectionEnum "CW"))]
(assoc flipper :flip-permanent-dir new-dir)))
(defn engage-flipping
"Mark flipper as flipping in given direction, unless no segment is in
that direction."
[flipper flip-dir]
(let [flip-seg-idx (segment-for-flip-direction flipper flip-dir)
cw? (= flip-dir (DirectionEnum "CW"))]
(if (not= flip-seg-idx (:segment flipper))
(mark-flipper-for-flipping flipper flip-dir
flip-seg-idx cw?)
flipper)))
(defn maybe-engage-flipping
"Given a flipper, returns the flipper possibly modified to be in a state
of flipping to another segment. This will always be true if the flipper
is on the outermost edge of the level, and will randomly be true if it
has not reached the edge."
[flipper]
(let [should-flip (and
(true? (:can-flip flipper))
(= (:flip-dir flipper) (DirectionEnum "NONE"))
(or (<= (rand) (:flip-probability flipper))
(= (:step flipper) (:steps (:level flipper)))))
permanent-dir (:flip-permanent-dir flipper)
flip-dir (or permanent-dir (random-direction))
flip-seg-idx (segment-for-flip-direction flipper flip-dir)
cw? (= flip-dir (DirectionEnum "CW"))]
(cond
(false? should-flip) flipper
(not= flip-seg-idx (:segment flipper)) (mark-flipper-for-flipping
flipper flip-dir
flip-seg-idx cw?)
(not (nil? permanent-dir)) (swap-flipper-permanent-dir flipper)
:else flipper)))
(defn mark-player-captured
"Marks player as being captured."
[player]
(assoc player
:captured? true
:stride -4))
(defn mark-enemy-capturing
"Marks enemy as having captured the player."
[enemy]
(assoc enemy
:capturing true
:can-flip false
:step (- (:step enemy) 10) ;; looks better if enemy leads player
:stride -4))
(defn enemy-is-on-player?
"Returns true if given enemy and player are on top of each other."
[player enemy]
(and (= (:segment player) (:segment enemy))
(= (:step player) (:step enemy))
(= (DirectionEnum "NONE") (:flip-dir enemy))))
(defn player-and-enemies-if-captured
"Given player and current list of enemies, returns an updated player
and updated enemy list if an enemy is capturing the player in vector
[player enemy-list]. Returns nil if no capture occurred."
[player enemy-list]
(let [{colliders true missers false}
(group-by (partial enemy-is-on-player? player) enemy-list)]
(when-let [[enemy & rest] colliders]
[(mark-player-captured player)
(cons (mark-enemy-capturing enemy) (concat missers rest))])))
(defn check-if-player-captured
"If player is not already captured, checks all enemies to see if they
are now capturing the player. See player-and-enemies-if-captured.
If capture is in progress, returns game-state with player and enemy-list
updated."
[game-state]
(if (:captured? (:player game-state))
game-state
(if-let [[player enemy-list] (player-and-enemies-if-captured
(:player game-state)
(:enemy-list game-state))]
(assoc game-state :enemy-list enemy-list :player player)
game-state)))
(defn update-entity-is-flipping
"Decide if an enemy should start flipping for every enemy on the level."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (map maybe-engage-flipping enemy-list))))
(defn update-entity-flippyness
"Update the position of any actively flipping enemy for every enemy on the
level."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (map update-flip-angle enemy-list))))
(defn update-flip-angle
"Given a flipper in the state of flipping, updates its current angle. If
the update would cause it to 'land' on its new segment, the flipper is
updated and returned as a no-longer-flipping. If the given enemy is
not flipping, returns it unchanged."
[flipper]
(let [new-angle (+ (:flip-stride flipper) (:flip-cur-angle flipper))
remaining (dec (:flip-steps-remaining flipper))
new-seg (if (<= remaining (/ (:flip-step-count flipper) 2))
(:flip-to-segment flipper)
(:segment flipper))]
(if (not= (:flip-dir flipper) (DirectionEnum "NONE"))
(if (< remaining 0)
(update-entity-stop-flipping flipper)
(assoc flipper
:damage-segment new-seg
:flip-cur-angle new-angle
:flip-steps-remaining remaining))
flipper)))
(defn build-player
"Returns a dictionary describing a player on the given level and segment."
[level seg-idx]
{:segment seg-idx
:level level
:captured? false
:step (:steps level)
:bullet-stride -5
:stride 0
:path path/*player-path*
:is-dead? false
})
(defn entity-next-step
"Returns the next step position of given entity, taking into account
minimum and maximum positions of the level."
[entity]
(let [stride (:stride entity)
maxstep (:steps (:level entity))
newstep (+ stride (:step entity))]
(cond
(> newstep maxstep) maxstep
(< newstep 0) 0
:else newstep)))
(defn update-entity-position!
"Return entity updated with a new position based on its current location and
stride. Won't go lower than 0, or higher than the maximum steps of the
level."
[entity]
(assoc entity :step (entity-next-step entity)))
(defn update-entity-list-positions
"Call update-entity-position! on all entities in list."
[entity-list]
(map update-entity-position! entity-list))
(defn update-entity-direction!
"Updates an enemy to travel in the opposite direction if he has reached
his maximum allowable step. This is used for Spikers, which travel
back down the level after laying spikes."
[entity]
(let [{:keys [step max-step stride]} entity
newstride (if (>= step max-step) (- stride) stride)]
(assoc entity :stride newstride)))
(defn update-entity-list-directions
"Apply update-entity-direction! to all enemies in the given list that have
a maximum step."
[entity-list]
(let [{spikers true others false}
(group-by #(contains? % :max-step) entity-list)]
(concat others (map update-entity-direction! spikers))))
(defn entity-between-steps
"Returns true of entity is on seg-idx, and between steps step0 and step1,
inclusive."
[seg-idx step0 step1 entity]
(let [min (min step0 step1)
max (max step0 step1)]
(and
(= (:damage-segment entity) seg-idx)
(>= (:step entity) min)
(<= (:step entity) max))))
(defn projectiles-after-collision
"Given an entity and a list of projectiles, returns the entity and updated
list of projectiles after collisions. The entity's hits-remaining counter
is decremented on a collision, and the projectile is removed. Small amount
of fudge factor (1 step += actual projectile location) to avoid narrow
misses in the collision algorithm."
[entity projectile-list]
((fn [entity projectiles-in projectiles-out was-hit?]
(if (empty? projectiles-in)
{:entity entity :projectiles projectiles-out :was-hit? was-hit?}
(let [bullet (first projectiles-in)
collision? (entity-between-steps
(:segment bullet)
(inc (:step bullet))
(dec (entity-next-step bullet))
entity)]
(if (and (not (:from-enemy? bullet)) collision?)
(recur (decrement-enemy-hits entity)
nil
(concat projectiles-out (rest projectiles-in))
true)
(recur entity
(rest projectiles-in)
(cons bullet projectiles-out)
was-hit?)))))
entity projectile-list '() false))
(defn entities-after-collisions
"Given a list of entities and a list of projectiles, returns the lists
with entity hit counts updated, entities removed if they have no hits
remaining, and collided projectiles removed.
See projectiles-after-collision, which is called for each entity in
entity-list."
[entity-list projectile-list]
((fn [entities-in entities-out projectiles-in]
(if (empty? entities-in)
{:entities entities-out :projectiles projectiles-in}
(let [{entity :entity projectiles :projectiles was-hit? :was-hit?}
(projectiles-after-collision (first entities-in)
projectiles-in)]
(recur (rest entities-in)
(cons entity entities-out)
projectiles))))
entity-list '() projectile-list))
(defn new-flippers-from-tanker
"Spawns two new flippers from one tanker. These flippers are automatically
set to be flipping to the segments surround the tanker, unless one of the
directions is blocked, in which case that flipper just stays on the tanker's
segment."
[enemy]
(let [{:keys [segment level step]} enemy]
(list
(engage-flipping
(build-flipper level segment :step step)
(DirectionEnum "CW"))
(engage-flipping
(build-flipper level segment :step step)
(DirectionEnum "CCW")))))
(defn enemy-list-after-deaths
"Returns the enemy list updated for deaths. This means removing enemies
that died, and possibly adding new enemies for those that spawn children
on death."
[enemy-list]
(let [{live-enemies false dead-enemies true}
(group-by #(zero? (:hits-remaining %)) enemy-list)]
(loop [[enemy & enemies] dead-enemies
enemies-out '()]
(cond
(nil? enemy) (concat live-enemies enemies-out)
(= (:type enemy) (EnemyEnum "TANKER"))
(recur enemies (concat (new-flippers-from-tanker enemy) enemies-out))
:else (recur enemies enemies-out)))))
(defn handle-dead-enemies
"Return game state after handling dead enemies, by removing them and possibly
replacing them with children."
[game-state]
(let [enemy-list (:enemy-list game-state)]
(assoc game-state :enemy-list (enemy-list-after-deaths enemy-list))))
(defn enemy-list-after-exiting-spikers
"Returns an updated copy of the given list of enemies with spikers removed
if they have returned to the innermost edge of the level. Spikers travel
out towards the player a random distance, then turn around and go back in.
They disappear when they are all the way in."
[enemy-list]
(let [{spikers true others false}
(group-by #(= (:type %) (EnemyEnum "SPIKER")) enemy-list)]
(loop [[enemy & enemies] spikers
enemies-out '()]
(cond
(nil? enemy) (concat others enemies-out)
(and (neg? (:stride enemy)) (zero? (:step enemy)))
(recur enemies enemies-out)
:else
(recur enemies (cons enemy enemies-out))))))
(defn handle-exiting-spikers
"Apply enemy-list-after-exiting-spikers to the enemy list and update game
state. This removes any spikers that are ready to disappear."
[game-state]
(let [enemy-list (:enemy-list game-state)]
(assoc game-state
:enemy-list (enemy-list-after-exiting-spikers enemy-list))))
(defn spikes-after-spike-laying
"Given a list of spikers and the current length of spikes on each segment,
this updates the spike lengths to be longer if a spiker has traveled past
the edge of an existing spike. Returns [enemy-list spikes]"
[enemy-list spikes]
(loop [[enemy & enemies] enemy-list
spikes-out spikes]
(let [{:keys [step segment]} enemy
spike-step (nth spikes-out segment)]
(cond
(nil? enemy) spikes-out
(>= step spike-step) (recur enemies (assoc spikes-out segment step))
:else (recur enemies spikes-out)))))
(defn handle-spike-laying
"Updates the length of spikes on the level. See spikes-after-spike-laying."
[game-state]
(let [enemy-list (:enemy-list game-state)
spikes (:spikes game-state)
spiker-list (filter #(= (:type %) (EnemyEnum "SPIKER")) enemy-list)]
(assoc game-state :spikes (spikes-after-spike-laying spiker-list spikes))))
(defn kill-tanker-at-top
"If the given tanker is at the top of a level, mark it as dead. Tankers
die when they reach the player, and split into two flippers."
[tanker]
(let [step (:step tanker)
maxstep (:steps (:level tanker))]
(if (= step maxstep)
(assoc tanker :hits-remaining 0)
tanker)))
(defn maybe-split-tankers
"Marks tankers at the top of the level as ready to split into flippers."
[game-state]
(let [enemy-list (:enemy-list game-state)
{tankers true others false}
(group-by #(= (:type %) (EnemyEnum "TANKER")) enemy-list)]
(assoc game-state
:enemy-list (concat (map kill-tanker-at-top tankers) others))))
(defn mark-player-if-spiked
"Marks the player as dead and sets up the animation flags to trigger a
level reload if the player has impacted a spike while traveling down the
level."
[game-state]
(let [{:keys [spikes player]} game-state step (:step player)
;; TODO: (nth) caused an error here once, spikes was length 0.
segment (:segment player) spike-len (nth spikes segment)]
(cond
(zero? spike-len) game-state
(<= step spike-len)
(assoc game-state
:player (assoc player :is-dead? true)
:is-zooming? true
:zoom-in? false
:player-zooming? false)
:else game-state)))
(defn animate-player-shooping
"Updates the player's position as he travels ('shoops') down the level after
defeating all enemies. Player moves relatively slowly. Camera zooms in
(actually, level zooms out) a little slower than the player moves. After
player reaches bottom, camera zooms faster. Level marked as finished when
zoom level is very high (10x normal)."
[game-state]
(let [player (:player game-state)
level (:level game-state)
zoom (:zoom game-state)]
(cond
(:level-done? game-state) game-state
(>= zoom 10) (assoc game-state :level-done? true)
(zero? (:step player)) (assoc game-state :zoom (+ zoom .2))
:else (assoc game-state
:player (update-entity-position! player)
:zoom (+ 1 (/ (- (:steps level) (:step player)) 150))
:is-zooming? true
:zoom-in? false
))))
(defn animate-player-capture
"Updates player's position on board while player is in the process of being
captured by an enemy, and marks player as dead when he reaches the inner
boundary of the level. When player dies, level zoom-out is initiated."
[game-state]
(let [player (:player game-state)
captured? (:captured? player)
isdead? (zero? (:step player))]
(cond
(false? captured?) game-state
(true? isdead?) (assoc (clear-level-entities game-state)
:player (assoc player :is-dead? true)
:is-zooming? true
:zoom-in? false)
:else (assoc game-state :player (update-entity-position! player)))))
(defn clear-level-entities
"Clears enemies, projectiles, and spikes from level."
[game-state]
(assoc game-state
:enemy-list '()
:projectile-list '()
:spikes []))
(defn update-zoom
"Updates current zoom value of the level, based on direction of :zoom-in?
in the game-state. This is used to animate the board zooming in or
zooming out at the start or end of a round. If this was a zoom out, and
it's finished, mark the level as done so it can restart."
[game-state]
(let [zoom (:zoom game-state)
zoom-in? (:zoom-in? game-state)
zoom-step 0.04
newzoom (if zoom-in? (+ zoom zoom-step) (- zoom zoom-step))
target (if zoom-in? 1.0 0.0)
cmp (if zoom-in? >= <=)]
(if (cmp zoom target) (assoc game-state
:is-zooming? false
:level-done? (not zoom-in?))
(if (cmp newzoom target)
(assoc game-state :zoom target)
(assoc game-state :zoom newzoom)))))
(defn clear-player-segment
"Returns game-state unchanged, and as a side affect clears the player's
current segment back to blue. To avoid weird color mixing, it is cleared
to black first (2px wide), then redrawn as blue (1.5px wide). This looks
right, but is different from how the board is drawn when done all at once."
[game-state]
(do
(set! (. (:bgcontext game-state) -lineWidth) 2)
(draw/draw-player-segment game-state {:r 0 :g 0 :b 0})
(set! (. (:bgcontext game-state) -lineWidth) 1.5)
(draw/draw-player-segment game-state {:r 10 :g 10 :b 100})
game-state))
(defn highlight-player-segment
"Returns game-state unchanged, and as a side effect draws the player's
current segment with a yellow border."
[game-state]
(do
(set! (. (:bgcontext game-state) -lineWidth) 1)
(draw/draw-player-segment game-state {:r 150 :g 150 :b 15})
game-state))
(defn draw-board
"Draws the level when level is zooming in or out, and updates the zoom level.
This doesn't redraw the board normally, since the board is drawn on a
different HTML5 canvas than the players for efficiency."
[game-state]
(let [is-zooming? (:is-zooming? game-state)
zoom (:zoom game-state)
{width :width height :height} (:dims game-state)]
(if is-zooming?
(do
(draw/clear-context (:bgcontext game-state) (:dims game-state))
(draw/draw-board (assoc game-state
:dims {:width (/ width zoom)
:height (/ height zoom)}))
(if (:player-zooming? game-state)
game-state
(update-zoom game-state)))
game-state)))
(defn collisions-with-projectile
"Returns map with keys true and false. Values under true key have or
will collide with bullet in the next bullet update. Values under the
false key will not."
[enemy-list bullet]
(group-by (partial entity-between-steps
(:segment bullet)
(:step bullet)
(entity-next-step bullet))
enemy-list))
(defn decrement-enemy-hits
"Decrement hits-remaining count on given enemy."
[enemy]
(assoc enemy :hits-remaining (dec (:hits-remaining enemy))))
(defn projectile-off-level?
"Returns true if a projectile has reached either boundary of the level."
[projectile]
(cond
(zero? (:step projectile)) true
(>= (:step projectile) (:steps (:level projectile))) true
:else false))
(defn add-enemy-projectile
"Add a new projectile to the global list of live projectiles, originating
from the given enemy, on the segment he is currently on."
[projectile-list enemy]
(let [level (:level enemy)
seg-idx (:segment enemy)
stride (+ (:stride enemy) 2)
step (:step enemy)]
(conj projectile-list
(build-projectile level seg-idx stride :step step :from-enemy? true))))
(defn add-player-projectile
"Add a new projectile to the global list of live projectiles, originating
from the given player, on the segment he is currently on."
[projectile-list player]
(let [level (:level player)
seg-idx (:segment player)
stride (:bullet-stride player)
step (:step player)]
(conj projectile-list
(build-projectile level seg-idx stride :step step))))
(defn segment-entity-cw
"Returns the segment to the left of the player. Loops around the level
on connected levels, and stops at 0 on unconnected levels."
[player]
(let [level (:level player)
seg-max (dec (count (:segments level)))
cur-seg (:segment player)
loops? (:loops? level)
new-seg (dec cur-seg)]
(if (< new-seg 0)
(if loops? seg-max 0)
new-seg)))
(defn segment-entity-ccw
"Returns the segment to the right of the player. Loops around the level
on connected levels, and stops at max on unconnected levels."
[player]
(let [level (:level player)
seg-max (dec (count (:segments level)))
cur-seg (:segment player)
loops? (:loops? level)
new-seg (inc cur-seg)]
(if (> new-seg seg-max)
(if loops? 0 seg-max)
new-seg)))
(defn queue-keypress
"Atomically queue keypress in global queue for later handling. This should
be called as the browser's key-handling callback."
[event]
(let [key (.-keyCode event)]
(swap! *key-event-queue* #(concat % [key]))
(.preventDefault event)
(.stopPropagation event)))
(defn dequeue-keypresses-while-paused
"See dequeue-keypresses for details. This unqueues all keypresses, but only
responds to unpause."
[game-state]
(loop [state game-state
queue @*key-event-queue*]
(if (empty? queue)
state
(let [key (first queue)
valid? (compare-and-set! *key-event-queue* queue (rest queue))]
(if valid?
(recur (handle-keypress-unpause state key) @*key-event-queue*)
(recur state @*key-event-queue*))))))
(defn handle-keypress-unpause
"See handle-keypress. This version only accepts unpause."
[game-state key]
(let [paused? (:paused? game-state)]
(condp = key
key-codes/ESC (assoc game-state :paused? (not paused?))
game-state)))
(defn handle-keypress
"Returns new game state updated to reflect the results of a player's
keypress.
## Key map
* Right -- Move counter-clockwise
* Left -- Move clockwise
* Space -- Shoot
* Escape -- Pause
"
[game-state key]
(let [player (:player game-state)
projectile-list (:projectile-list game-state)
paused? (:paused? game-state)]
(condp = key
key-codes/RIGHT (assoc game-state
:player
(assoc player :segment (segment-entity-ccw player)))
key-codes/LEFT (assoc game-state
:player
(assoc player :segment (segment-entity-cw player)))
key-codes/SPACE (assoc game-state
:projectile-list
(add-player-projectile projectile-list player))
key-codes/ESC (assoc game-state :paused? (not paused?))
game-state)))
(defn dequeue-keypresses
"Atomically dequeue keypresses from global queue and pass to handle-keypress,
until global queue is empty. Returns game state updated after applying
all keypresses.
Has a side effect of clearing global *key-event-queue*.
## Implementation details:
Use compare-and-set! instead of swap! to test against the value we
entered the loop with, instead of the current value. compare-and-set!
returns true only if the update was a success (i.e. the queue hasn't
changed since entering the loop), in which case we handle the key.
If the queue has changed, we do nothing. The loop always gets called
again with the current deref of the global state.
"
[game-state]
(loop [state game-state
queue @*key-event-queue*]
(if (empty? queue)
state
(let [key (first queue)
valid? (compare-and-set! *key-event-queue* queue (rest queue))]
(cond
(not valid?) (recur state @*key-event-queue*)
(not (:captured? (:player game-state))) (recur (handle-keypress
state
key)
@*key-event-queue*)
:else (recur (handle-keypress-unpause state key) @*key-event-queue*)
)))))
(defn animationFrameMethod
"Returns a callable javascript function to schedule a frame to be drawn.
Tries to use requestAnimationFrame, or the browser-specific version of
it that is available. Falls back on setTimeout if requestAnimationFrame
is not available on player's browser.
requestAnimationFrame tries to figure out a consistent framerate based
on how long frame takes to render.
The setTimeout fail-over is hard-coded to attempt 30fps.
"
[]
(let [window (dom/getWindow)
names ["requestAnimationFrame"
"webkitRequestAnimationFrame"
"mozRequestAnimationFrame"
"oRequestAnimationFrame"
"msRequestAnimationFrame"]
options (map (fn [name] #(aget window name)) names)]
((fn [[current & remaining]]
(cond
(nil? current) #((.-setTimeout window) % (/ 1000 30))
(fn? (current)) (current)
:else (recur remaining)))
options)))
(defn clear-frame
"Returns game state unmodified, clears the HTML5 canvas as a side-effect."
[game-state]
(do
(draw/clear-context (:context game-state) (:dims game-state))
game-state))
(defn render-frame
"Draws the current game-state on the HTML5 canvas. Returns the game state
unmodified (drawing is a side-effect)."
[game-state]
(let [{context :context
dims :dims
level :level
enemy-list :enemy-list
projectile-list :projectile-list
player :player}
game-state
{enemy-shots true player-shots false}
(group-by :from-enemy? projectile-list)
zoom (:zoom game-state)
zoom-dims {:width (/ (:width dims) zoom)
:height (/ (:height dims) zoom)}]
(draw/draw-all-spikes (assoc game-state :dims zoom-dims))
(if (not (:is-dead? player))
(draw/draw-player context zoom-dims level player (:zoom game-state)))
(draw/draw-entities context zoom-dims level
enemy-list
{:r 150 :g 10 :b 10}
zoom)
(draw/draw-entities context zoom-dims level
player-shots
{:r 255 :g 255 :b 255}
zoom)
(draw/draw-entities context zoom-dims level
enemy-shots
{:r 150 :g 15 :b 150}
zoom)
game-state))
(defn remove-collided-entities
"Detects and removes projectiles that have collided with enemies, and enemies
whose hit counts have dropped to zero. Returns updated game-state."
[game-state]
(let [{enemy-list :enemy-list
projectile-list :projectile-list}
game-state]
(let [{plist :projectiles elist :entities}
(entities-after-collisions enemy-list projectile-list)]
(assoc game-state
:projectile-list plist
:enemy-list elist))))
(defn bullets-will-collide?
"Returns true if two bullets will collide within the next frame, and one is
from the player and the other is from an enemy."
[bullet1 bullet2]
(let [max-stride (max (:stride bullet1) (:stride bullet2))
min-stride (min (:stride bullet1) (:stride bullet2))
step1 (:step bullet1)
step2 (:step bullet2)
next-step1 (entity-next-step bullet1)
next-step2 (entity-next-step bullet2)]
(and (or (and (>= step1 step2) (<= next-step1 next-step2))
(and (>= step2 step1) (<= next-step2 next-step1)))
(neg? min-stride)
(pos? max-stride)
(if (:from-enemy? bullet1)
(not (:from-enemy? bullet2))
(:from-enemy? bullet2)))))
(defn projectile-list-without-collisions
"Given a list of projectiles, returns the list minus any bullet-on-bullet
collisions that occur within it."
[projectiles]
(loop [[bullet & others] projectiles
survivors '()]
(if (nil? bullet) survivors
(let [{not-hit false hit true}
(group-by #(bullets-will-collide? bullet %) others)]
(if-not (empty? hit)
(recur (concat not-hit (rest hit)) survivors)
(recur others (cons bullet survivors)))))))
(defn remove-collided-bullets
"Remove bullets that have hit each other. Only player-vs-enemy collisions
count. Breaks list of projectiles into one list per segment, and then
runs projectile-list-without-collisions on each of those lists to get
back a final list of only bullets that aren't involved in collisions."
[game-state]
(let [projectile-list (:projectile-list game-state)
segment-lists (vals (group-by :segment projectile-list))
non-collided (mapcat projectile-list-without-collisions segment-lists)]
(assoc game-state :projectile-list non-collided)))
(defn decrement-spike-length
"Returns a new spike length based on the given spike length and the number
of times the spike was hit. Spike is arbitrarily shrunk by 10 steps per
hit. If it falls below a short threshhold (5), it is set to zero."
[spike-len hit-count]
(let [new-len (- spike-len (* 10 hit-count))]
(if (<= new-len 5) 0 new-len)))
(defn filter-spike-bullet-collisions
"Given a list of projectiles on a segment (it is mandatory that they all
be on the same segment), and the spike length on that segment, returns
[projectile-list spike-len], where any projectiles that hit the spike
have been removed from projectile-list, and spike-len has been updated
to be shorter if it was hit."
[projectile-list spike-len]
(let [{hit true missed false}
(group-by #(<= (:step %) spike-len) projectile-list)]
[missed (decrement-spike-length spike-len (count hit))]))
(defn remove-spiked-bullets
"Returns the game state with any bullets that hit a spike removed, and any
spikes that were hit shrunk in length."
[game-state]
(let [projectile-list (:projectile-list game-state)
{player-list false enemy-list true}
(group-by :from-enemy? projectile-list)
segmented-projectiles (group-by :segment player-list)]
(loop [[seg-bullets & remaining] segmented-projectiles
spikes (:spikes game-state)
projectiles-out '()]
(if (nil? seg-bullets)
(assoc game-state
:projectile-list (concat projectiles-out enemy-list)
:spikes spikes)
(let [[key bullets] seg-bullets
spike-len (nth spikes key)
[bullets new-len] (filter-spike-bullet-collisions bullets
spike-len)]
(recur remaining
(assoc spikes key new-len)
(concat projectiles-out bullets)))))))
(defn bullets-will-kill-player?
"Returns true given bullet will hit the given player."
[player bullet]
(let [next-step (entity-next-step bullet)
player-step (:step player)]
(and (= player-step next-step)
(:from-enemy? bullet))))
(defn update-player-if-shot
"Updates the player to indicate whether he was shot by an enemy."
[game-state]
(let [projectile-list (:projectile-list game-state)
player (:player game-state)
on-segment (filter #(= (:segment player) (:segment %)) projectile-list)
{hit true miss false} (group-by
#(bullets-will-kill-player? player %)
on-segment)]
(if-not (empty? hit)
(assoc (clear-level-entities game-state)
:player (assoc player :is-dead? true)
:is-zooming? true
:player-zooming? false
:zoom-in? false)
game-state)))
(defn update-projectile-locations
"Returns game-state with all projectiles updated to have new positions
based on their speeds and current position."
[game-state]
(let [{projectile-list :projectile-list} game-state
rm-fn (partial remove projectile-off-level?)]
(assoc game-state
:projectile-list (-> projectile-list
update-entity-list-positions
rm-fn))))
(defn update-enemy-locations
"Returns game-state with all of the enemies updated to have new positions
based on their speeds and current position."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (update-entity-list-positions enemy-list))))
(defn update-enemy-directions
"Return game state with any enemies who were ready to turn around marked to
travel in the opposite direction."
[game-state]
(let [{enemy-list :enemy-list} game-state]
(assoc game-state :enemy-list (update-entity-list-directions enemy-list))))
(defn schedule-next-frame
"Tells the player's browser to schedule the next frame to be drawn, using
whatever the best mechanism the browser has to do so."
[game-state]
((:anim-fn game-state) #(next-game-state game-state)))
(defn update-frame-count
"Increments the game-state's frame counter, which is a count of frames since
the last FPS measurement."
[game-state]
(let [{frame-count :frame-count}
game-state]
(assoc game-state :frame-count (inc frame-count))))
(defn render-fps-display
"Print a string representation of the most recent FPS measurement in
an HTML element named 'fps'. This resets the frame-count and frame-time
currently stored in the game state."
[game-state]
(let [{frame-count :frame-count
frame-time :frame-time}
game-state
fps (/ (* 1000 frame-count) (- (goog.now) frame-time))
str-fps (pr-str (util/round fps))]
(dom/setTextContent (dom/getElement "fps") (str "FPS: " str-fps))
(assoc game-state
:frame-count 0
:frame-time (goog.now))))
(defn maybe-render-fps-display
"Calls render-fps-display if the frame-count is above a certain threshhold."
[game-state]
(if (= (:frame-count game-state) 20)
(render-fps-display game-state)
game-state))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-05-20\"\n :doc \"Tests for zana.da",
"end": 105,
"score": 0.9998794198036194,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
},
{
"context": " p1 (Typical.\n; 17 Math/PI \"Galileo\"\n; (Primitive. 0 1 2 3 4 5 \\a)\n; ",
"end": 3222,
"score": 0.9997397065162659,
"start": 3215,
"tag": "NAME",
"value": "Galileo"
},
{
"context": " p2 (Typical.\n; 13 Math/E \"Darwin\"\n; (Primitive. 1 2 3 4 5 6 \\b)\n; ",
"end": 3433,
"score": 0.9997326135635376,
"start": 3427,
"tag": "NAME",
"value": "Darwin"
}
] | src/test/clojure/zana/test/data/edn.clj | wahpenayo/zana | 2 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald" :date "2016-05-20"
:doc "Tests for zana.data.datum." }
zana.test.data.edn
(:require [clojure.edn :as edn]
[clojure.test :as test]))
;;------------------------------------------------------------------------------
;; mvn -Dtest=zana.test.data.edn clojure:test
#_(test/run-tests 'zana.test.data.edn)
;;------------------------------------------------------------------------------
(defrecord Record [^long n ^double x ^String s]
Object
(toString [this] (str "#zana.test.data.edn.Record" (into {} this))))
;;------------------------------------------------------------------------------
(test/deftest defrecords
(let [r0 (Record. 17 Math/PI "forty-two")
m0 (into {} r0)
r1 (->Record 17 Math/PI "forty-two")
r2 (map->Record m0)
r3 (edn/read-string {:readers {'zana.test.data.edn.Record map->Record}}
(str r0))]
(test/is (= r0 r1))
(test/is (= r1 r2))
(test/is (= r2 r3))))
;;------------------------------------------------------------------------------
;; edge case
;(test/deftest empty-datum
; (let [e0 (Empty.)
; s (pr-str e0)]
; ;; Datums have identity semantics
; (test/is (empty? empty/fields))
; (test/is (not= e0 e1))
; (test/is (not= (.hashCode e0) (.hashCode e1)))))
;;------------------------------------------------------------------------------
;(test/deftest primitive-datum
; (let [p0 (Primitive. (byte 0) (short 1) (int 2) (long 3) 4 5 \a)
; p1 (Primitive. 0 1 2 3 4 5 \a)
; p2 (Primitive. 1 2 3 4 5 6 \b)
; p3 (assoc p2 :d 0.0)]
; (test/is (== 6.0 (:d p2)))
; (test/is (== 0.0 (primitive/d p3)))
; ;; Datums have identity semantics
; (test/is (= primitive/fields
; [primitive/b primitive/sh primitive/i primitive/l
; primitive/f primitive/d primitive/c]))
; (test/is (not= p0 p1))
; (test/is (not= p0 p2))
; (test/is (not= (.hashCode p0) (.hashCode p1)))
; (test/is (not= (.hashCode p0) (.hashCode p2)))
; (test/is (== (primitive/b p0) (primitive/b p1)))
; (test/is (not (== (primitive/b p0) (primitive/b p2))))
; (test/is (instance? clojure.lang.IFn$OL primitive/b))
; (test/is (instance? clojure.lang.IFn$OL primitive/sh))
; (test/is (instance? clojure.lang.IFn$OL primitive/i))
; (test/is (instance? clojure.lang.IFn$OL primitive/l))
; (test/is (instance? clojure.lang.IFn$OD primitive/f))
; (test/is (instance? clojure.lang.IFn$OD primitive/d))
; ;; could simplify z/define-datum code if memfn type-hinted the return
; ;; value
; ;;(test/is (not (instance? clojure.lang.IFn$OD (memfn ^Primitive d))))
; ))
;;------------------------------------------------------------------------------
;(test/deftest typical-datum
; (let [p0 (Typical.
; 17 Math/PI "Galileo"
; (Primitive. 0 1 2 3 4 5 \a)
; (LocalDate/parse "2015-02-20")
; (LocalDateTime/parse "2015-02-20T10:15:30"))
; p1 (Typical.
; 17 Math/PI "Galileo"
; (Primitive. 0 1 2 3 4 5 \a)
; (LocalDate/parse "2015-02-20")
; (LocalDateTime/parse "2015-02-20T10:15:30"))
; p2 (Typical.
; 13 Math/E "Darwin"
; (Primitive. 1 2 3 4 5 6 \b)
; (LocalDate/parse "1776-07-03")
; (LocalDateTime/parse "1826-07-04T09:00:00"))]
; ;; Datums have identity semantics
; (test/is (not= p0 p1))
; (test/is (not= p0 p2))
; (test/is (not= (.hashCode p0) (.hashCode p1)))
; (test/is (not= (.hashCode p0) (.hashCode p2)))
; (test/is (not= (typical/p p0) (typical/p p1)))
; (test/is (not= (typical/p p0) (typical/p p2)))
; (test/is (== (typical/x p0) (typical/x p1)))
; (test/is (not (== (typical/n p0) (typical/n p2))))
; (test/is (instance? clojure.lang.IFn$OL typical/n))
; (test/is (instance? clojure.lang.IFn$OD typical/x))))
;;------------------------------------------------------------------------------ | 67384 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>" :date "2016-05-20"
:doc "Tests for zana.data.datum." }
zana.test.data.edn
(:require [clojure.edn :as edn]
[clojure.test :as test]))
;;------------------------------------------------------------------------------
;; mvn -Dtest=zana.test.data.edn clojure:test
#_(test/run-tests 'zana.test.data.edn)
;;------------------------------------------------------------------------------
(defrecord Record [^long n ^double x ^String s]
Object
(toString [this] (str "#zana.test.data.edn.Record" (into {} this))))
;;------------------------------------------------------------------------------
(test/deftest defrecords
(let [r0 (Record. 17 Math/PI "forty-two")
m0 (into {} r0)
r1 (->Record 17 Math/PI "forty-two")
r2 (map->Record m0)
r3 (edn/read-string {:readers {'zana.test.data.edn.Record map->Record}}
(str r0))]
(test/is (= r0 r1))
(test/is (= r1 r2))
(test/is (= r2 r3))))
;;------------------------------------------------------------------------------
;; edge case
;(test/deftest empty-datum
; (let [e0 (Empty.)
; s (pr-str e0)]
; ;; Datums have identity semantics
; (test/is (empty? empty/fields))
; (test/is (not= e0 e1))
; (test/is (not= (.hashCode e0) (.hashCode e1)))))
;;------------------------------------------------------------------------------
;(test/deftest primitive-datum
; (let [p0 (Primitive. (byte 0) (short 1) (int 2) (long 3) 4 5 \a)
; p1 (Primitive. 0 1 2 3 4 5 \a)
; p2 (Primitive. 1 2 3 4 5 6 \b)
; p3 (assoc p2 :d 0.0)]
; (test/is (== 6.0 (:d p2)))
; (test/is (== 0.0 (primitive/d p3)))
; ;; Datums have identity semantics
; (test/is (= primitive/fields
; [primitive/b primitive/sh primitive/i primitive/l
; primitive/f primitive/d primitive/c]))
; (test/is (not= p0 p1))
; (test/is (not= p0 p2))
; (test/is (not= (.hashCode p0) (.hashCode p1)))
; (test/is (not= (.hashCode p0) (.hashCode p2)))
; (test/is (== (primitive/b p0) (primitive/b p1)))
; (test/is (not (== (primitive/b p0) (primitive/b p2))))
; (test/is (instance? clojure.lang.IFn$OL primitive/b))
; (test/is (instance? clojure.lang.IFn$OL primitive/sh))
; (test/is (instance? clojure.lang.IFn$OL primitive/i))
; (test/is (instance? clojure.lang.IFn$OL primitive/l))
; (test/is (instance? clojure.lang.IFn$OD primitive/f))
; (test/is (instance? clojure.lang.IFn$OD primitive/d))
; ;; could simplify z/define-datum code if memfn type-hinted the return
; ;; value
; ;;(test/is (not (instance? clojure.lang.IFn$OD (memfn ^Primitive d))))
; ))
;;------------------------------------------------------------------------------
;(test/deftest typical-datum
; (let [p0 (Typical.
; 17 Math/PI "Galileo"
; (Primitive. 0 1 2 3 4 5 \a)
; (LocalDate/parse "2015-02-20")
; (LocalDateTime/parse "2015-02-20T10:15:30"))
; p1 (Typical.
; 17 Math/PI "<NAME>"
; (Primitive. 0 1 2 3 4 5 \a)
; (LocalDate/parse "2015-02-20")
; (LocalDateTime/parse "2015-02-20T10:15:30"))
; p2 (Typical.
; 13 Math/E "<NAME>"
; (Primitive. 1 2 3 4 5 6 \b)
; (LocalDate/parse "1776-07-03")
; (LocalDateTime/parse "1826-07-04T09:00:00"))]
; ;; Datums have identity semantics
; (test/is (not= p0 p1))
; (test/is (not= p0 p2))
; (test/is (not= (.hashCode p0) (.hashCode p1)))
; (test/is (not= (.hashCode p0) (.hashCode p2)))
; (test/is (not= (typical/p p0) (typical/p p1)))
; (test/is (not= (typical/p p0) (typical/p p2)))
; (test/is (== (typical/x p0) (typical/x p1)))
; (test/is (not (== (typical/n p0) (typical/n p2))))
; (test/is (instance? clojure.lang.IFn$OL typical/n))
; (test/is (instance? clojure.lang.IFn$OD typical/x))))
;;------------------------------------------------------------------------------ | true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-05-20"
:doc "Tests for zana.data.datum." }
zana.test.data.edn
(:require [clojure.edn :as edn]
[clojure.test :as test]))
;;------------------------------------------------------------------------------
;; mvn -Dtest=zana.test.data.edn clojure:test
#_(test/run-tests 'zana.test.data.edn)
;;------------------------------------------------------------------------------
(defrecord Record [^long n ^double x ^String s]
Object
(toString [this] (str "#zana.test.data.edn.Record" (into {} this))))
;;------------------------------------------------------------------------------
(test/deftest defrecords
(let [r0 (Record. 17 Math/PI "forty-two")
m0 (into {} r0)
r1 (->Record 17 Math/PI "forty-two")
r2 (map->Record m0)
r3 (edn/read-string {:readers {'zana.test.data.edn.Record map->Record}}
(str r0))]
(test/is (= r0 r1))
(test/is (= r1 r2))
(test/is (= r2 r3))))
;;------------------------------------------------------------------------------
;; edge case
;(test/deftest empty-datum
; (let [e0 (Empty.)
; s (pr-str e0)]
; ;; Datums have identity semantics
; (test/is (empty? empty/fields))
; (test/is (not= e0 e1))
; (test/is (not= (.hashCode e0) (.hashCode e1)))))
;;------------------------------------------------------------------------------
;(test/deftest primitive-datum
; (let [p0 (Primitive. (byte 0) (short 1) (int 2) (long 3) 4 5 \a)
; p1 (Primitive. 0 1 2 3 4 5 \a)
; p2 (Primitive. 1 2 3 4 5 6 \b)
; p3 (assoc p2 :d 0.0)]
; (test/is (== 6.0 (:d p2)))
; (test/is (== 0.0 (primitive/d p3)))
; ;; Datums have identity semantics
; (test/is (= primitive/fields
; [primitive/b primitive/sh primitive/i primitive/l
; primitive/f primitive/d primitive/c]))
; (test/is (not= p0 p1))
; (test/is (not= p0 p2))
; (test/is (not= (.hashCode p0) (.hashCode p1)))
; (test/is (not= (.hashCode p0) (.hashCode p2)))
; (test/is (== (primitive/b p0) (primitive/b p1)))
; (test/is (not (== (primitive/b p0) (primitive/b p2))))
; (test/is (instance? clojure.lang.IFn$OL primitive/b))
; (test/is (instance? clojure.lang.IFn$OL primitive/sh))
; (test/is (instance? clojure.lang.IFn$OL primitive/i))
; (test/is (instance? clojure.lang.IFn$OL primitive/l))
; (test/is (instance? clojure.lang.IFn$OD primitive/f))
; (test/is (instance? clojure.lang.IFn$OD primitive/d))
; ;; could simplify z/define-datum code if memfn type-hinted the return
; ;; value
; ;;(test/is (not (instance? clojure.lang.IFn$OD (memfn ^Primitive d))))
; ))
;;------------------------------------------------------------------------------
;(test/deftest typical-datum
; (let [p0 (Typical.
; 17 Math/PI "Galileo"
; (Primitive. 0 1 2 3 4 5 \a)
; (LocalDate/parse "2015-02-20")
; (LocalDateTime/parse "2015-02-20T10:15:30"))
; p1 (Typical.
; 17 Math/PI "PI:NAME:<NAME>END_PI"
; (Primitive. 0 1 2 3 4 5 \a)
; (LocalDate/parse "2015-02-20")
; (LocalDateTime/parse "2015-02-20T10:15:30"))
; p2 (Typical.
; 13 Math/E "PI:NAME:<NAME>END_PI"
; (Primitive. 1 2 3 4 5 6 \b)
; (LocalDate/parse "1776-07-03")
; (LocalDateTime/parse "1826-07-04T09:00:00"))]
; ;; Datums have identity semantics
; (test/is (not= p0 p1))
; (test/is (not= p0 p2))
; (test/is (not= (.hashCode p0) (.hashCode p1)))
; (test/is (not= (.hashCode p0) (.hashCode p2)))
; (test/is (not= (typical/p p0) (typical/p p1)))
; (test/is (not= (typical/p p0) (typical/p p2)))
; (test/is (== (typical/x p0) (typical/x p1)))
; (test/is (not (== (typical/n p0) (typical/n p2))))
; (test/is (instance? clojure.lang.IFn$OL typical/n))
; (test/is (instance? clojure.lang.IFn$OD typical/x))))
;;------------------------------------------------------------------------------ |
[
{
"context": ";; Copyright © 2015-2021 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.9998841881752014,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
},
{
"context": "rants)\n (set grants))\n {:username grantee\n :schema table_schema})))\n\n(defn get-presen",
"end": 7702,
"score": 0.9981114268302917,
"start": 7695,
"tag": "USERNAME",
"value": "grantee"
}
] | src/territory_bro/gis/gis_db.clj | orfjackal/territory-bro | 2 | ;; Copyright © 2015-2021 Esko Luontola
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.gis.gis-db
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log]
[medley.core :refer [map-keys remove-vals]]
[schema.coerce :as coerce]
[schema.core :as s]
[territory-bro.infra.db :as db])
(:import (java.time Instant)
(java.util UUID)
(org.postgresql.util PSQLException)))
(def ^:private query! (db/compile-queries "db/hugsql/gis.sql"))
;;;; Features
(defn- format-feature [feature]
(map-keys #(keyword "gis-feature" (name %))
feature))
;; TODO: not used in production code; remove?
(defn get-congregation-boundaries [conn]
(->> (query! conn :get-congregation-boundaries)
(map format-feature)
(doall)))
(defn create-congregation-boundary! [conn location]
(:id (query! conn :create-congregation-boundary {:id (UUID/randomUUID)
:location location})))
;; TODO: not used in production code; remove?
(defn get-regions [conn]
(->> (query! conn :get-regions)
(map format-feature)
(doall)))
(defn create-region-with-id! [conn id name location]
(:id (query! conn :create-region {:id id
:name name
:location location})))
(defn create-region! [conn name location]
(create-region-with-id! conn (UUID/randomUUID) name location))
;; TODO: not used in production code; remove?
(defn get-card-minimap-viewports [conn]
(->> (query! conn :get-card-minimap-viewports)
(map format-feature)
(doall)))
(defn create-card-minimap-viewport! [conn location]
(:id (query! conn :create-card-minimap-viewport {:id (UUID/randomUUID)
:location location})))
;; TODO: not used in production code; remove?
(defn get-territories
([conn]
(get-territories conn {}))
([conn search]
(->> (query! conn :get-territories search)
(map format-feature)
(doall))))
(defn get-territory-by-id [conn id]
(first (get-territories conn {:ids [id]})))
(defn create-territory! [conn territory]
(:id (query! conn :create-territory {:id (UUID/randomUUID)
:number (:territory/number territory)
:addresses (:territory/addresses territory)
:subregion (:territory/region territory)
:meta (:territory/meta territory)
:location (:territory/location territory)})))
;;;; Changes
(s/defschema GisFeature
{:id UUID
:location s/Str
(s/optional-key :name) s/Str
(s/optional-key :number) s/Str
(s/optional-key :subregion) s/Str
(s/optional-key :addresses) s/Str
(s/optional-key :meta) {s/Any s/Any}})
(s/defschema GisChange
{:gis-change/id s/Int
:gis-change/schema s/Str
:gis-change/table (s/enum "territory" "congregation_boundary" "subregion" "card_minimap_viewport")
:gis-change/op (s/enum :INSERT :UPDATE :DELETE)
:gis-change/user s/Str
:gis-change/time Instant
:gis-change/old (s/maybe GisFeature)
:gis-change/new (s/maybe GisFeature)
:gis-change/processed? s/Bool})
(def ^:private gis-change-coercer
(coerce/coercer! GisChange coerce/string-coercion-matcher))
(def ^:private column->key
{:id :gis-change/id
:schema :gis-change/schema
:table :gis-change/table
:op :gis-change/op
:user :gis-change/user
:time :gis-change/time
:old :gis-change/old
:new :gis-change/new
:processed :gis-change/processed?})
(defn- format-gis-change [change]
(->> change
(map-keys #(get column->key % %))
(gis-change-coercer)))
(defn get-changes
([conn]
(get-changes conn {}))
([conn search]
(->> (query! conn :get-gis-changes search)
(map format-gis-change)
(doall))))
(defn next-unprocessed-change [conn]
(first (get-changes conn {:processed? false
:limit 1})))
(defn mark-changes-processed! [conn ids]
(query! conn :mark-changes-processed {:ids ids}))
;;;; Database users
(defn user-exists? [conn username]
(not (empty? (jdbc/query conn ["SELECT 1 FROM pg_roles WHERE rolname = ?" username]))))
(defn ensure-user-present! [conn {:keys [username password schema]}]
(log/info "Creating GIS user:" username)
(assert username)
(assert password)
(assert schema)
(try
(jdbc/execute! conn ["SAVEPOINT create_role"])
(jdbc/execute! conn [(str "CREATE ROLE " username " WITH LOGIN")])
(jdbc/execute! conn ["RELEASE SAVEPOINT create_role"])
(catch PSQLException e
;; ignore error if role already exists
(if (= db/psql-duplicate-object (.getSQLState e))
(do
(log/info "GIS user already present:" username)
(jdbc/execute! conn ["ROLLBACK TO SAVEPOINT create_role"]))
(throw e))))
(jdbc/execute! conn [(str "ALTER ROLE " username " WITH PASSWORD '" password "'")])
(jdbc/execute! conn [(str "ALTER ROLE " username " VALID UNTIL 'infinity'")])
;; TODO: move detailed permissions to schema specific role
(jdbc/execute! conn [(str "GRANT USAGE ON SCHEMA " schema " TO " username)])
(jdbc/execute! conn [(str "GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "
schema ".territory, "
schema ".congregation_boundary, "
schema ".subregion, "
schema ".card_minimap_viewport "
"TO " username)])
nil)
(defn drop-role-cascade! [conn role schemas]
(assert role)
(try
(doseq [schema schemas]
(assert schema)
(jdbc/execute! conn ["SAVEPOINT revoke_privileges"])
(jdbc/execute! conn [(str "REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA " schema " FROM " role)])
(jdbc/execute! conn [(str "REVOKE USAGE ON SCHEMA " schema " FROM " role)])
(jdbc/execute! conn ["RELEASE SAVEPOINT revoke_privileges"]))
(catch PSQLException e
;; ignore error if role already does not exist
(if (= db/psql-undefined-object (.getSQLState e))
(do
(log/info "GIS user already absent:" role)
(jdbc/execute! conn ["ROLLBACK TO SAVEPOINT revoke_privileges"]))
(throw e))))
(jdbc/execute! conn [(str "DROP ROLE IF EXISTS " role)])
nil)
(defn ensure-user-absent! [conn {:keys [username schema]}]
(log/info "Deleting GIS user:" username)
(drop-role-cascade! conn username [schema]))
(defn- validate-grants [grants]
(let [[{:keys [grantee table_schema]}] grants
expected-grants (->> ["territory"
"subregion"
"congregation_boundary"
"card_minimap_viewport"]
(mapcat (fn [table_name]
[{:table_name table_name :privilege_type "SELECT"}
{:table_name table_name :privilege_type "INSERT"}
{:table_name table_name :privilege_type "UPDATE"}
{:table_name table_name :privilege_type "DELETE"}]))
(map #(-> %
(assoc :grantee grantee)
(assoc :table_schema table_schema))))]
(when (= (set expected-grants)
(set grants))
{:username grantee
:schema table_schema})))
(defn get-present-users [conn {:keys [username-prefix schema-prefix]}]
(->> (query! conn :find-roles {:role (str username-prefix "%")
:schema (str schema-prefix "%")})
(group-by (juxt :grantee :table_schema))
(vals)
(map validate-grants)
(filter some?)
(doall)))
;;;; Tenant schemas
(defn- schema-history-query [schema]
(format "SELECT '%s' AS schema, * FROM %s.flyway_schema_history" schema schema))
(defn- simplify-schema-history [rows]
(->> rows
(sort-by :installed_rank)
(remove #(= "SCHEMA" (:type %)))
(map #(select-keys % [:version :type :script :checksum]))))
(defn get-present-schemas [conn {:keys [schema-prefix]}]
(let [schemas (->> (query! conn :find-flyway-managed-schemas {:schema (str schema-prefix "%")})
(map :table_schema))
reference-schema (->> schemas
(take 10) ; short-cut in case all tenant schemas are out of date
(filter db/tenant-schema-up-to-date?)
(first))]
(when reference-schema
(let [reference-history (simplify-schema-history (jdbc/query conn [(schema-history-query reference-schema)]))]
(->> (jdbc/query conn [(->> schemas
(map schema-history-query)
(str/join " UNION ALL "))])
(group-by :schema)
(filter (fn [[_schema history]]
(= reference-history (simplify-schema-history history))))
(keys)
(doall))))))
| 35787 | ;; Copyright © 2015-2021 <NAME>
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.gis.gis-db
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log]
[medley.core :refer [map-keys remove-vals]]
[schema.coerce :as coerce]
[schema.core :as s]
[territory-bro.infra.db :as db])
(:import (java.time Instant)
(java.util UUID)
(org.postgresql.util PSQLException)))
(def ^:private query! (db/compile-queries "db/hugsql/gis.sql"))
;;;; Features
(defn- format-feature [feature]
(map-keys #(keyword "gis-feature" (name %))
feature))
;; TODO: not used in production code; remove?
(defn get-congregation-boundaries [conn]
(->> (query! conn :get-congregation-boundaries)
(map format-feature)
(doall)))
(defn create-congregation-boundary! [conn location]
(:id (query! conn :create-congregation-boundary {:id (UUID/randomUUID)
:location location})))
;; TODO: not used in production code; remove?
(defn get-regions [conn]
(->> (query! conn :get-regions)
(map format-feature)
(doall)))
(defn create-region-with-id! [conn id name location]
(:id (query! conn :create-region {:id id
:name name
:location location})))
(defn create-region! [conn name location]
(create-region-with-id! conn (UUID/randomUUID) name location))
;; TODO: not used in production code; remove?
(defn get-card-minimap-viewports [conn]
(->> (query! conn :get-card-minimap-viewports)
(map format-feature)
(doall)))
(defn create-card-minimap-viewport! [conn location]
(:id (query! conn :create-card-minimap-viewport {:id (UUID/randomUUID)
:location location})))
;; TODO: not used in production code; remove?
(defn get-territories
([conn]
(get-territories conn {}))
([conn search]
(->> (query! conn :get-territories search)
(map format-feature)
(doall))))
(defn get-territory-by-id [conn id]
(first (get-territories conn {:ids [id]})))
(defn create-territory! [conn territory]
(:id (query! conn :create-territory {:id (UUID/randomUUID)
:number (:territory/number territory)
:addresses (:territory/addresses territory)
:subregion (:territory/region territory)
:meta (:territory/meta territory)
:location (:territory/location territory)})))
;;;; Changes
(s/defschema GisFeature
{:id UUID
:location s/Str
(s/optional-key :name) s/Str
(s/optional-key :number) s/Str
(s/optional-key :subregion) s/Str
(s/optional-key :addresses) s/Str
(s/optional-key :meta) {s/Any s/Any}})
(s/defschema GisChange
{:gis-change/id s/Int
:gis-change/schema s/Str
:gis-change/table (s/enum "territory" "congregation_boundary" "subregion" "card_minimap_viewport")
:gis-change/op (s/enum :INSERT :UPDATE :DELETE)
:gis-change/user s/Str
:gis-change/time Instant
:gis-change/old (s/maybe GisFeature)
:gis-change/new (s/maybe GisFeature)
:gis-change/processed? s/Bool})
(def ^:private gis-change-coercer
(coerce/coercer! GisChange coerce/string-coercion-matcher))
(def ^:private column->key
{:id :gis-change/id
:schema :gis-change/schema
:table :gis-change/table
:op :gis-change/op
:user :gis-change/user
:time :gis-change/time
:old :gis-change/old
:new :gis-change/new
:processed :gis-change/processed?})
(defn- format-gis-change [change]
(->> change
(map-keys #(get column->key % %))
(gis-change-coercer)))
(defn get-changes
([conn]
(get-changes conn {}))
([conn search]
(->> (query! conn :get-gis-changes search)
(map format-gis-change)
(doall))))
(defn next-unprocessed-change [conn]
(first (get-changes conn {:processed? false
:limit 1})))
(defn mark-changes-processed! [conn ids]
(query! conn :mark-changes-processed {:ids ids}))
;;;; Database users
(defn user-exists? [conn username]
(not (empty? (jdbc/query conn ["SELECT 1 FROM pg_roles WHERE rolname = ?" username]))))
(defn ensure-user-present! [conn {:keys [username password schema]}]
(log/info "Creating GIS user:" username)
(assert username)
(assert password)
(assert schema)
(try
(jdbc/execute! conn ["SAVEPOINT create_role"])
(jdbc/execute! conn [(str "CREATE ROLE " username " WITH LOGIN")])
(jdbc/execute! conn ["RELEASE SAVEPOINT create_role"])
(catch PSQLException e
;; ignore error if role already exists
(if (= db/psql-duplicate-object (.getSQLState e))
(do
(log/info "GIS user already present:" username)
(jdbc/execute! conn ["ROLLBACK TO SAVEPOINT create_role"]))
(throw e))))
(jdbc/execute! conn [(str "ALTER ROLE " username " WITH PASSWORD '" password "'")])
(jdbc/execute! conn [(str "ALTER ROLE " username " VALID UNTIL 'infinity'")])
;; TODO: move detailed permissions to schema specific role
(jdbc/execute! conn [(str "GRANT USAGE ON SCHEMA " schema " TO " username)])
(jdbc/execute! conn [(str "GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "
schema ".territory, "
schema ".congregation_boundary, "
schema ".subregion, "
schema ".card_minimap_viewport "
"TO " username)])
nil)
(defn drop-role-cascade! [conn role schemas]
(assert role)
(try
(doseq [schema schemas]
(assert schema)
(jdbc/execute! conn ["SAVEPOINT revoke_privileges"])
(jdbc/execute! conn [(str "REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA " schema " FROM " role)])
(jdbc/execute! conn [(str "REVOKE USAGE ON SCHEMA " schema " FROM " role)])
(jdbc/execute! conn ["RELEASE SAVEPOINT revoke_privileges"]))
(catch PSQLException e
;; ignore error if role already does not exist
(if (= db/psql-undefined-object (.getSQLState e))
(do
(log/info "GIS user already absent:" role)
(jdbc/execute! conn ["ROLLBACK TO SAVEPOINT revoke_privileges"]))
(throw e))))
(jdbc/execute! conn [(str "DROP ROLE IF EXISTS " role)])
nil)
(defn ensure-user-absent! [conn {:keys [username schema]}]
(log/info "Deleting GIS user:" username)
(drop-role-cascade! conn username [schema]))
(defn- validate-grants [grants]
(let [[{:keys [grantee table_schema]}] grants
expected-grants (->> ["territory"
"subregion"
"congregation_boundary"
"card_minimap_viewport"]
(mapcat (fn [table_name]
[{:table_name table_name :privilege_type "SELECT"}
{:table_name table_name :privilege_type "INSERT"}
{:table_name table_name :privilege_type "UPDATE"}
{:table_name table_name :privilege_type "DELETE"}]))
(map #(-> %
(assoc :grantee grantee)
(assoc :table_schema table_schema))))]
(when (= (set expected-grants)
(set grants))
{:username grantee
:schema table_schema})))
(defn get-present-users [conn {:keys [username-prefix schema-prefix]}]
(->> (query! conn :find-roles {:role (str username-prefix "%")
:schema (str schema-prefix "%")})
(group-by (juxt :grantee :table_schema))
(vals)
(map validate-grants)
(filter some?)
(doall)))
;;;; Tenant schemas
(defn- schema-history-query [schema]
(format "SELECT '%s' AS schema, * FROM %s.flyway_schema_history" schema schema))
(defn- simplify-schema-history [rows]
(->> rows
(sort-by :installed_rank)
(remove #(= "SCHEMA" (:type %)))
(map #(select-keys % [:version :type :script :checksum]))))
(defn get-present-schemas [conn {:keys [schema-prefix]}]
(let [schemas (->> (query! conn :find-flyway-managed-schemas {:schema (str schema-prefix "%")})
(map :table_schema))
reference-schema (->> schemas
(take 10) ; short-cut in case all tenant schemas are out of date
(filter db/tenant-schema-up-to-date?)
(first))]
(when reference-schema
(let [reference-history (simplify-schema-history (jdbc/query conn [(schema-history-query reference-schema)]))]
(->> (jdbc/query conn [(->> schemas
(map schema-history-query)
(str/join " UNION ALL "))])
(group-by :schema)
(filter (fn [[_schema history]]
(= reference-history (simplify-schema-history history))))
(keys)
(doall))))))
| true | ;; Copyright © 2015-2021 PI:NAME:<NAME>END_PI
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.gis.gis-db
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log]
[medley.core :refer [map-keys remove-vals]]
[schema.coerce :as coerce]
[schema.core :as s]
[territory-bro.infra.db :as db])
(:import (java.time Instant)
(java.util UUID)
(org.postgresql.util PSQLException)))
(def ^:private query! (db/compile-queries "db/hugsql/gis.sql"))
;;;; Features
(defn- format-feature [feature]
(map-keys #(keyword "gis-feature" (name %))
feature))
;; TODO: not used in production code; remove?
(defn get-congregation-boundaries [conn]
(->> (query! conn :get-congregation-boundaries)
(map format-feature)
(doall)))
(defn create-congregation-boundary! [conn location]
(:id (query! conn :create-congregation-boundary {:id (UUID/randomUUID)
:location location})))
;; TODO: not used in production code; remove?
(defn get-regions [conn]
(->> (query! conn :get-regions)
(map format-feature)
(doall)))
(defn create-region-with-id! [conn id name location]
(:id (query! conn :create-region {:id id
:name name
:location location})))
(defn create-region! [conn name location]
(create-region-with-id! conn (UUID/randomUUID) name location))
;; TODO: not used in production code; remove?
(defn get-card-minimap-viewports [conn]
(->> (query! conn :get-card-minimap-viewports)
(map format-feature)
(doall)))
(defn create-card-minimap-viewport! [conn location]
(:id (query! conn :create-card-minimap-viewport {:id (UUID/randomUUID)
:location location})))
;; TODO: not used in production code; remove?
(defn get-territories
([conn]
(get-territories conn {}))
([conn search]
(->> (query! conn :get-territories search)
(map format-feature)
(doall))))
(defn get-territory-by-id [conn id]
(first (get-territories conn {:ids [id]})))
(defn create-territory! [conn territory]
(:id (query! conn :create-territory {:id (UUID/randomUUID)
:number (:territory/number territory)
:addresses (:territory/addresses territory)
:subregion (:territory/region territory)
:meta (:territory/meta territory)
:location (:territory/location territory)})))
;;;; Changes
(s/defschema GisFeature
{:id UUID
:location s/Str
(s/optional-key :name) s/Str
(s/optional-key :number) s/Str
(s/optional-key :subregion) s/Str
(s/optional-key :addresses) s/Str
(s/optional-key :meta) {s/Any s/Any}})
(s/defschema GisChange
{:gis-change/id s/Int
:gis-change/schema s/Str
:gis-change/table (s/enum "territory" "congregation_boundary" "subregion" "card_minimap_viewport")
:gis-change/op (s/enum :INSERT :UPDATE :DELETE)
:gis-change/user s/Str
:gis-change/time Instant
:gis-change/old (s/maybe GisFeature)
:gis-change/new (s/maybe GisFeature)
:gis-change/processed? s/Bool})
(def ^:private gis-change-coercer
(coerce/coercer! GisChange coerce/string-coercion-matcher))
(def ^:private column->key
{:id :gis-change/id
:schema :gis-change/schema
:table :gis-change/table
:op :gis-change/op
:user :gis-change/user
:time :gis-change/time
:old :gis-change/old
:new :gis-change/new
:processed :gis-change/processed?})
(defn- format-gis-change [change]
(->> change
(map-keys #(get column->key % %))
(gis-change-coercer)))
(defn get-changes
([conn]
(get-changes conn {}))
([conn search]
(->> (query! conn :get-gis-changes search)
(map format-gis-change)
(doall))))
(defn next-unprocessed-change [conn]
(first (get-changes conn {:processed? false
:limit 1})))
(defn mark-changes-processed! [conn ids]
(query! conn :mark-changes-processed {:ids ids}))
;;;; Database users
(defn user-exists? [conn username]
(not (empty? (jdbc/query conn ["SELECT 1 FROM pg_roles WHERE rolname = ?" username]))))
(defn ensure-user-present! [conn {:keys [username password schema]}]
(log/info "Creating GIS user:" username)
(assert username)
(assert password)
(assert schema)
(try
(jdbc/execute! conn ["SAVEPOINT create_role"])
(jdbc/execute! conn [(str "CREATE ROLE " username " WITH LOGIN")])
(jdbc/execute! conn ["RELEASE SAVEPOINT create_role"])
(catch PSQLException e
;; ignore error if role already exists
(if (= db/psql-duplicate-object (.getSQLState e))
(do
(log/info "GIS user already present:" username)
(jdbc/execute! conn ["ROLLBACK TO SAVEPOINT create_role"]))
(throw e))))
(jdbc/execute! conn [(str "ALTER ROLE " username " WITH PASSWORD '" password "'")])
(jdbc/execute! conn [(str "ALTER ROLE " username " VALID UNTIL 'infinity'")])
;; TODO: move detailed permissions to schema specific role
(jdbc/execute! conn [(str "GRANT USAGE ON SCHEMA " schema " TO " username)])
(jdbc/execute! conn [(str "GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "
schema ".territory, "
schema ".congregation_boundary, "
schema ".subregion, "
schema ".card_minimap_viewport "
"TO " username)])
nil)
(defn drop-role-cascade! [conn role schemas]
(assert role)
(try
(doseq [schema schemas]
(assert schema)
(jdbc/execute! conn ["SAVEPOINT revoke_privileges"])
(jdbc/execute! conn [(str "REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA " schema " FROM " role)])
(jdbc/execute! conn [(str "REVOKE USAGE ON SCHEMA " schema " FROM " role)])
(jdbc/execute! conn ["RELEASE SAVEPOINT revoke_privileges"]))
(catch PSQLException e
;; ignore error if role already does not exist
(if (= db/psql-undefined-object (.getSQLState e))
(do
(log/info "GIS user already absent:" role)
(jdbc/execute! conn ["ROLLBACK TO SAVEPOINT revoke_privileges"]))
(throw e))))
(jdbc/execute! conn [(str "DROP ROLE IF EXISTS " role)])
nil)
(defn ensure-user-absent! [conn {:keys [username schema]}]
(log/info "Deleting GIS user:" username)
(drop-role-cascade! conn username [schema]))
(defn- validate-grants [grants]
(let [[{:keys [grantee table_schema]}] grants
expected-grants (->> ["territory"
"subregion"
"congregation_boundary"
"card_minimap_viewport"]
(mapcat (fn [table_name]
[{:table_name table_name :privilege_type "SELECT"}
{:table_name table_name :privilege_type "INSERT"}
{:table_name table_name :privilege_type "UPDATE"}
{:table_name table_name :privilege_type "DELETE"}]))
(map #(-> %
(assoc :grantee grantee)
(assoc :table_schema table_schema))))]
(when (= (set expected-grants)
(set grants))
{:username grantee
:schema table_schema})))
(defn get-present-users [conn {:keys [username-prefix schema-prefix]}]
(->> (query! conn :find-roles {:role (str username-prefix "%")
:schema (str schema-prefix "%")})
(group-by (juxt :grantee :table_schema))
(vals)
(map validate-grants)
(filter some?)
(doall)))
;;;; Tenant schemas
(defn- schema-history-query [schema]
(format "SELECT '%s' AS schema, * FROM %s.flyway_schema_history" schema schema))
(defn- simplify-schema-history [rows]
(->> rows
(sort-by :installed_rank)
(remove #(= "SCHEMA" (:type %)))
(map #(select-keys % [:version :type :script :checksum]))))
(defn get-present-schemas [conn {:keys [schema-prefix]}]
(let [schemas (->> (query! conn :find-flyway-managed-schemas {:schema (str schema-prefix "%")})
(map :table_schema))
reference-schema (->> schemas
(take 10) ; short-cut in case all tenant schemas are out of date
(filter db/tenant-schema-up-to-date?)
(first))]
(when reference-schema
(let [reference-history (simplify-schema-history (jdbc/query conn [(schema-history-query reference-schema)]))]
(->> (jdbc/query conn [(->> schemas
(map schema-history-query)
(str/join " UNION ALL "))])
(group-by :schema)
(filter (fn [[_schema history]]
(= reference-history (simplify-schema-history history))))
(keys)
(doall))))))
|
[
{
"context": "]\n [clojure.string :as str]))\n\n;; HACK(Richo): I wrote this macro because I'm lazy and I didn'",
"end": 129,
"score": 0.9989668130874634,
"start": 124,
"tag": "NAME",
"value": "Richo"
}
] | middleware/server/src/middleware/utils/fs/browser_macros.clj | GIRA/UziScript | 15 | (ns middleware.utils.fs.browser-macros
(:require [clojure.java.io :as io]
[clojure.string :as str]))
;; HACK(Richo): I wrote this macro because I'm lazy and I didn't want to refactor the
;; compiler to work with asynchronous code.
;; The problem I have is that the linker needs access to the file system in order to
;; read the imported libraries. However, when running in the browser I don't have direct
;; access to the file system. Instead I need to go through an http request. That should
;; be straightforward but the async nature of javascript makes it a little annoying.
;; And for this to work correctly, I'll need to change the entire compiler code to make
;; it asynchronous as well, which I don't really feel like doing right now.
;; So as a *temporary* solution I wrote this macro that reads all the libraries at compile
;; time and leaves them stored in the code. Since clojurescript macros run in the context
;; of the JVM, I can access the filesystem without problems. This way the compiler can keep
;; its sync implementation.
;; I know, it's an ugly hack and I will fix it soon, but for now, it seems to work.
(defmacro read-file* [path root]
(let [data (into {} (map (fn [f] [(str/replace (.getPath f) "\\" "/") (slurp f)])
(filter (memfn isFile)
(file-seq (io/file root)))))]
`(get ~data ~path nil)))
| 107012 | (ns middleware.utils.fs.browser-macros
(:require [clojure.java.io :as io]
[clojure.string :as str]))
;; HACK(<NAME>): I wrote this macro because I'm lazy and I didn't want to refactor the
;; compiler to work with asynchronous code.
;; The problem I have is that the linker needs access to the file system in order to
;; read the imported libraries. However, when running in the browser I don't have direct
;; access to the file system. Instead I need to go through an http request. That should
;; be straightforward but the async nature of javascript makes it a little annoying.
;; And for this to work correctly, I'll need to change the entire compiler code to make
;; it asynchronous as well, which I don't really feel like doing right now.
;; So as a *temporary* solution I wrote this macro that reads all the libraries at compile
;; time and leaves them stored in the code. Since clojurescript macros run in the context
;; of the JVM, I can access the filesystem without problems. This way the compiler can keep
;; its sync implementation.
;; I know, it's an ugly hack and I will fix it soon, but for now, it seems to work.
(defmacro read-file* [path root]
(let [data (into {} (map (fn [f] [(str/replace (.getPath f) "\\" "/") (slurp f)])
(filter (memfn isFile)
(file-seq (io/file root)))))]
`(get ~data ~path nil)))
| true | (ns middleware.utils.fs.browser-macros
(:require [clojure.java.io :as io]
[clojure.string :as str]))
;; HACK(PI:NAME:<NAME>END_PI): I wrote this macro because I'm lazy and I didn't want to refactor the
;; compiler to work with asynchronous code.
;; The problem I have is that the linker needs access to the file system in order to
;; read the imported libraries. However, when running in the browser I don't have direct
;; access to the file system. Instead I need to go through an http request. That should
;; be straightforward but the async nature of javascript makes it a little annoying.
;; And for this to work correctly, I'll need to change the entire compiler code to make
;; it asynchronous as well, which I don't really feel like doing right now.
;; So as a *temporary* solution I wrote this macro that reads all the libraries at compile
;; time and leaves them stored in the code. Since clojurescript macros run in the context
;; of the JVM, I can access the filesystem without problems. This way the compiler can keep
;; its sync implementation.
;; I know, it's an ugly hack and I will fix it soon, but for now, it seems to work.
(defmacro read-file* [path root]
(let [data (into {} (map (fn [f] [(str/replace (.getPath f) "\\" "/") (slurp f)])
(filter (memfn isFile)
(file-seq (io/file root)))))]
`(get ~data ~path nil)))
|
[
{
"context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License",
"end": 49,
"score": 0.9998869895935059,
"start": 37,
"tag": "NAME",
"value": "Ronen Narkis"
},
{
"context": "omment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version ",
"end": 62,
"score": 0.7728099226951599,
"start": 52,
"tag": "EMAIL",
"value": "arkisr.com"
}
] | src/freenas/validations.clj | celestial-ops/core | 1 | (comment
re-core, Copyright 2012 Ronen Narkis, narkisr.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 freenas.validations
"Freenas based validations"
(:require
[re-core.model :refer (check-validity)]
[re-core.provider :refer (mappings)]
[clojure.core.strint :refer (<<)]
[subs.core :refer (validate! combine validation when-not-nil)]
))
(validation :netmask
(when-not-nil (partial re-find #"\d+\.\d+\.\d+\.\d+\/\d\d") "must be a legal netmask"))
(def machine-common
{:hostname #{:required :String} :ip #{:required :String :ip}
:netmask #{:required :String} :mac #{:required :mac}
})
(def freenas
{:freenas {
:flags #{:String}
}})
(defmethod check-validity [:freenas :entity] [spec]
(validate! spec (combine {:machine machine-common} freenas) :error ::invalid-system))
(def jail-mappings {
:ip :jail_ipv4 :hostname :jail_host :netmask :jail_ipv4_netmask
:mac :jail_mac :flags :jail_flags })
(defn validate-provider [spec]
(validate! spec (combine (mappings machine-common jail-mappings)) :error ::invalid-jail))
| 58927 | (comment
re-core, Copyright 2012 <NAME>, n<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 freenas.validations
"Freenas based validations"
(:require
[re-core.model :refer (check-validity)]
[re-core.provider :refer (mappings)]
[clojure.core.strint :refer (<<)]
[subs.core :refer (validate! combine validation when-not-nil)]
))
(validation :netmask
(when-not-nil (partial re-find #"\d+\.\d+\.\d+\.\d+\/\d\d") "must be a legal netmask"))
(def machine-common
{:hostname #{:required :String} :ip #{:required :String :ip}
:netmask #{:required :String} :mac #{:required :mac}
})
(def freenas
{:freenas {
:flags #{:String}
}})
(defmethod check-validity [:freenas :entity] [spec]
(validate! spec (combine {:machine machine-common} freenas) :error ::invalid-system))
(def jail-mappings {
:ip :jail_ipv4 :hostname :jail_host :netmask :jail_ipv4_netmask
:mac :jail_mac :flags :jail_flags })
(defn validate-provider [spec]
(validate! spec (combine (mappings machine-common jail-mappings)) :error ::invalid-jail))
| true | (comment
re-core, Copyright 2012 PI:NAME:<NAME>END_PI, nPI: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 freenas.validations
"Freenas based validations"
(:require
[re-core.model :refer (check-validity)]
[re-core.provider :refer (mappings)]
[clojure.core.strint :refer (<<)]
[subs.core :refer (validate! combine validation when-not-nil)]
))
(validation :netmask
(when-not-nil (partial re-find #"\d+\.\d+\.\d+\.\d+\/\d\d") "must be a legal netmask"))
(def machine-common
{:hostname #{:required :String} :ip #{:required :String :ip}
:netmask #{:required :String} :mac #{:required :mac}
})
(def freenas
{:freenas {
:flags #{:String}
}})
(defmethod check-validity [:freenas :entity] [spec]
(validate! spec (combine {:machine machine-common} freenas) :error ::invalid-system))
(def jail-mappings {
:ip :jail_ipv4 :hostname :jail_host :netmask :jail_ipv4_netmask
:mac :jail_mac :flags :jail_flags })
(defn validate-provider [spec]
(validate! spec (combine (mappings machine-common jail-mappings)) :error ::invalid-jail))
|
[
{
"context": "rcPnjHcjFCeDlSQ2wxQzA/view\n\n(def players \n {\n :amaronian {:name \"Andre Maronian\" }\n :rprescott {:name \"R",
"end": 360,
"score": 0.9993475079536438,
"start": 351,
"tag": "USERNAME",
"value": "amaronian"
},
{
"context": "QzA/view\n\n(def players \n {\n :amaronian {:name \"Andre Maronian\" }\n :rprescott {:name \"Ralph Prescott\" }\n :rm",
"end": 383,
"score": 0.9998797178268433,
"start": 369,
"tag": "NAME",
"value": "Andre Maronian"
},
{
"context": " \n {\n :amaronian {:name \"Andre Maronian\" }\n :rprescott {:name \"Ralph Prescott\" }\n :rmack {:name \"Ray M",
"end": 400,
"score": 0.9995959401130676,
"start": 391,
"tag": "USERNAME",
"value": "rprescott"
},
{
"context": "n {:name \"Andre Maronian\" }\n :rprescott {:name \"Ralph Prescott\" }\n :rmack {:name \"Ray Mack\" }\n ;; ...\n})\n\n(d",
"end": 423,
"score": 0.9998732805252075,
"start": 409,
"tag": "NAME",
"value": "Ralph Prescott"
},
{
"context": "an\" }\n :rprescott {:name \"Ralph Prescott\" }\n :rmack {:name \"Ray Mack\" }\n ;; ...\n})\n\n(def monday-lea",
"end": 436,
"score": 0.993455171585083,
"start": 431,
"tag": "USERNAME",
"value": "rmack"
},
{
"context": "scott {:name \"Ralph Prescott\" }\n :rmack {:name \"Ray Mack\" }\n ;; ...\n})\n\n(def monday-league {\n :type :",
"end": 453,
"score": 0.9998672008514404,
"start": 445,
"tag": "NAME",
"value": "Ray Mack"
},
{
"context": "[] ] }\n\t\t;;#inst \"2015-12-21\" { :type :off :text \"Merry Christmas\"}\n\t )\n;; ...\n \n\t :teams \n [\n nil ",
"end": 1335,
"score": 0.9854205250740051,
"start": 1320,
"tag": "NAME",
"value": "Merry Christmas"
},
{
"context": " \n\t :teams \n [\n nil ;; team 0\n [:amaronian :dfreeeman :ebizari :gmaronian] ;; team 1\n\t\t [] ;",
"end": 1411,
"score": 0.9858456254005432,
"start": 1402,
"tag": "USERNAME",
"value": "amaronian"
},
{
"context": ":teams \n [\n nil ;; team 0\n [:amaronian :dfreeeman :ebizari :gmaronian] ;; team 1\n\t\t [] ;; team 2\n\t\t",
"end": 1422,
"score": 0.8732462525367737,
"start": 1413,
"tag": "USERNAME",
"value": "dfreeeman"
},
{
"context": "[\n nil ;; team 0\n [:amaronian :dfreeeman :ebizari :gmaronian] ;; team 1\n\t\t [] ;; team 2\n\t\t [] ",
"end": 1426,
"score": 0.7350554466247559,
"start": 1424,
"tag": "USERNAME",
"value": "eb"
},
{
"context": "eam 0\n [:amaronian :dfreeeman :ebizari :gmaronian] ;; team 1\n\t\t [] ;; team 2\n\t\t [] ;; team 3\n\t\t [] ",
"end": 1442,
"score": 0.5900191068649292,
"start": 1439,
"tag": "USERNAME",
"value": "ian"
},
{
"context": "[] ;; team 3\n\t\t [] ;; team 4\n\t\t [] ;; team 5\n\t\t [:rprescott :tmchang :hshi :ddwight] ;; team 6\n\t\t [] ;; team ",
"end": 1532,
"score": 0.9970495700836182,
"start": 1523,
"tag": "USERNAME",
"value": "rprescott"
},
{
"context": "3\n\t\t [] ;; team 4\n\t\t [] ;; team 5\n\t\t [:rprescott :tmchang :hshi :ddwight] ;; team 6\n\t\t [] ;; team 7\n\t\t [] ;",
"end": 1541,
"score": 0.7830848693847656,
"start": 1534,
"tag": "USERNAME",
"value": "tmchang"
},
{
"context": "eam 0\n [] ;; team 1\n\t\t [] ;; team 2\n\t\t [:pyu :rprescott :bstein] ;; team 3\n ]\n})\n\n;; https://drive.goog",
"end": 1902,
"score": 0.9941225647926331,
"start": 1893,
"tag": "USERNAME",
"value": "rprescott"
}
] | src/gvttc_ical/data_2015.clj | rmprescott/gvttc-ical | 0 | (ns gvttc-ical.data-2015)
;; TODO: consider switching to using EDN
;; 2016 schedules online
;; Monday: https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
;; Tuesday: https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
;; Wednesday: https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
(def players
{
:amaronian {:name "Andre Maronian" }
:rprescott {:name "Ralph Prescott" }
:rmack {:name "Ray Mack" }
;; ...
})
(def monday-league {
:type :monday
:start-time 18 ;; 6PM
:end-time 22 ;; 10PM
:events (sorted-map ;; not sure if a sorted map is actually is needed
#inst "2015-10-06" { :matches [[4 3] [8 10] [11 7] [1 6] [5 2] [9 12] ] }
#inst "2015-10-05" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-10-12" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-10-19" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-02" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-09" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-16" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-23" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-30" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-12-07" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-12-14" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-12-21" { :type :off :text "Merry Christmas"}
)
;; ...
:teams
[
nil ;; team 0
[:amaronian :dfreeeman :ebizari :gmaronian] ;; team 1
[] ;; team 2
[] ;; team 3
[] ;; team 4
[] ;; team 5
[:rprescott :tmchang :hshi :ddwight] ;; team 6
[] ;; team 7
[] ;; team 8
[] ;; team 9
[] ;; team 10
[] ;; team 11
]
:tables
[
"1 & Half of 2"
"3 & Half of 2"
"4 & Half of 5"
"6 & Half of 5"
"7 & 8"
:bye
]
})
(def tuesday-league
{
:type :tuesday
:teams
[
nil ;; team 0
[] ;; team 1
[] ;; team 2
[:pyu :rprescott :bstein] ;; team 3
]
})
;; https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
(def wednesday-league
{
:type :wednesday })
(def leagues [monday-league tuesday-league wednesday-league])
| 87204 | (ns gvttc-ical.data-2015)
;; TODO: consider switching to using EDN
;; 2016 schedules online
;; Monday: https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
;; Tuesday: https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
;; Wednesday: https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
(def players
{
:amaronian {:name "<NAME>" }
:rprescott {:name "<NAME>" }
:rmack {:name "<NAME>" }
;; ...
})
(def monday-league {
:type :monday
:start-time 18 ;; 6PM
:end-time 22 ;; 10PM
:events (sorted-map ;; not sure if a sorted map is actually is needed
#inst "2015-10-06" { :matches [[4 3] [8 10] [11 7] [1 6] [5 2] [9 12] ] }
#inst "2015-10-05" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-10-12" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-10-19" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-02" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-09" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-16" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-23" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-30" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-12-07" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-12-14" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-12-21" { :type :off :text "<NAME>"}
)
;; ...
:teams
[
nil ;; team 0
[:amaronian :dfreeeman :ebizari :gmaronian] ;; team 1
[] ;; team 2
[] ;; team 3
[] ;; team 4
[] ;; team 5
[:rprescott :tmchang :hshi :ddwight] ;; team 6
[] ;; team 7
[] ;; team 8
[] ;; team 9
[] ;; team 10
[] ;; team 11
]
:tables
[
"1 & Half of 2"
"3 & Half of 2"
"4 & Half of 5"
"6 & Half of 5"
"7 & 8"
:bye
]
})
(def tuesday-league
{
:type :tuesday
:teams
[
nil ;; team 0
[] ;; team 1
[] ;; team 2
[:pyu :rprescott :bstein] ;; team 3
]
})
;; https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
(def wednesday-league
{
:type :wednesday })
(def leagues [monday-league tuesday-league wednesday-league])
| true | (ns gvttc-ical.data-2015)
;; TODO: consider switching to using EDN
;; 2016 schedules online
;; Monday: https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
;; Tuesday: https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
;; Wednesday: https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
(def players
{
:amaronian {:name "PI:NAME:<NAME>END_PI" }
:rprescott {:name "PI:NAME:<NAME>END_PI" }
:rmack {:name "PI:NAME:<NAME>END_PI" }
;; ...
})
(def monday-league {
:type :monday
:start-time 18 ;; 6PM
:end-time 22 ;; 10PM
:events (sorted-map ;; not sure if a sorted map is actually is needed
#inst "2015-10-06" { :matches [[4 3] [8 10] [11 7] [1 6] [5 2] [9 12] ] }
#inst "2015-10-05" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-10-12" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-10-19" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-02" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-09" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-16" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-23" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-11-30" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-12-07" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-12-14" { :matches [[] [] [] [] [] [] ] }
;;#inst "2015-12-21" { :type :off :text "PI:NAME:<NAME>END_PI"}
)
;; ...
:teams
[
nil ;; team 0
[:amaronian :dfreeeman :ebizari :gmaronian] ;; team 1
[] ;; team 2
[] ;; team 3
[] ;; team 4
[] ;; team 5
[:rprescott :tmchang :hshi :ddwight] ;; team 6
[] ;; team 7
[] ;; team 8
[] ;; team 9
[] ;; team 10
[] ;; team 11
]
:tables
[
"1 & Half of 2"
"3 & Half of 2"
"4 & Half of 5"
"6 & Half of 5"
"7 & 8"
:bye
]
})
(def tuesday-league
{
:type :tuesday
:teams
[
nil ;; team 0
[] ;; team 1
[] ;; team 2
[:pyu :rprescott :bstein] ;; team 3
]
})
;; https://drive.google.com/file/d/0B8etdrrcPnjHcjFCeDlSQ2wxQzA/view
(def wednesday-league
{
:type :wednesday })
(def leagues [monday-league tuesday-league wednesday-league])
|
[
{
"context": "(ns hello-world)\n\n(defn hello-world []\n \"Goodbye, Mars!\")\n\n",
"end": 55,
"score": 0.9974682927131653,
"start": 51,
"tag": "NAME",
"value": "Mars"
}
] | exercises/practice/hello-world/src/hello_world.cljs | joetjen/clojurescript | 5 | (ns hello-world)
(defn hello-world []
"Goodbye, Mars!")
| 108458 | (ns hello-world)
(defn hello-world []
"Goodbye, <NAME>!")
| true | (ns hello-world)
(defn hello-world []
"Goodbye, PI:NAME:<NAME>END_PI!")
|
[
{
"context": " 1\n {:keylength 512\n :extensions [{:oid \"1.3.6",
"end": 6110,
"score": 0.995741069316864,
"start": 6107,
"tag": "KEY",
"value": "512"
},
{
"context": "\n {:keylength 512\n :extensions",
"end": 11462,
"score": 0.7064045071601868,
"start": 11459,
"tag": "KEY",
"value": "512"
}
] | test/integration/puppetlabs/puppetserver/auth_conf_test.clj | linuxadmin25/puppet89 | 0 | (ns puppetlabs.puppetserver.auth-conf-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[puppetlabs.puppetserver.bootstrap-testutils :as bootstrap]
[puppetlabs.http.client.sync :as http-client]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[puppetlabs.ssl-utils.simple :as ssl-simple]
[puppetlabs.ssl-utils.core :as ssl-utils]
[schema.test :as schema-test]
[puppetlabs.services.jruby.jruby-puppet-testutils :as jruby-testutils]
[puppetlabs.puppetserver.testutils :as testutils :refer [http-get]]
[me.raynes.fs :as fs]
[ring.util.codec :as ring-codec]
[puppetlabs.trapperkeeper.testutils.logging :as logging]
[cheshire.core :as cheshire])
(:import (java.io StringWriter)))
(def test-resources-dir
(ks/absolute-path "./dev-resources/puppetlabs/puppetserver/auth_conf_test"))
(def gem-path
[(ks/absolute-path jruby-testutils/gem-path)])
(defn script-path
[script-name]
(str test-resources-dir "/" script-name))
(use-fixtures
:once
schema-test/validate-schemas
(testutils/with-puppet-conf (fs/file test-resources-dir "puppet.conf")))
(deftest ^:integration request-with-ssl-cert-handled-via-tk-auth
(testing (str "Request with SSL certificate via trapperkeeper-authorization "
"handled")
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet
{:gem-path gem-path}
:authorization {:version 1
:allow-header-cert-info false
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog unencoded"}
{:match-request {:path "^/puppet/v3/node/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "node"}
{:match-request {:path
"^/puppet/v3/catalog/%65ncoded$"
:type
"regex"}
:allow ["localhost"]
:sort-order 1
:name "catalog encoded"}]}}
(logutils/with-test-logging
(testing "for puppet 4 routes without url encoding"
(let [response (http-get "puppet/v3/node/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/node/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (testutils/catalog-name-matches?
(testutils/catalog-ring-response->catalog response)
"private"))))
(testing "for puppet 4 routes with url encoding"
(let [response
(http-get
"puppet/v3/%63atalog/%65ncoded?environment=production")]
;; The web server should decode the above URI path component to
;; "puppet/v3/catalog/encoded". There is a rule allowing
;; "localhost" for "%65ncoded" but no rule allowing "localhost"
;; for "encoded", so this should request should fail with a
;; 403 (Forbidden) error.
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response
(http-get
"puppet/v3/%63atalog/%2565ncoded?environment=production")]
;; The web server should decode the above URI path component to
;; "puppet/v3/catalog/%65ncoded". There is a rule allowing
;; "localhost" for "%65ncoded", so this should request should
;; succeed.
(is (= 200 (:status response))
(ks/pprint-to-string response))
;; The catalog which is returned should have a name of "%65ncoded"
;; since this should be the name derived from the web server
;; request after a single percent-decode.
(is (testutils/catalog-name-matches?
(testutils/catalog-ring-response->catalog response)
"%65ncoded")))
(let [response
(http-get
(str "puppet/v3/%63atalog/private/%2E%2E/secret?"
"environment=production"))]
;; The web server should decode the above URI path component to
;; "puppet/v3/catalog/private/../secret". The relative
;; path, "/../", inside of the path component is forbidden and
;; so should cause the webserver to throw a 'Bad Request' error.
(is (= 400 (:status response))
(ks/pprint-to-string response)))))))))
(deftest ^:integration request-with-x-client-headers-handled-via-tk-auth
(testing (str "Request with X-Client headers via trapperkeeper-authorization "
"handled")
(let [extension-value "UUUU-IIIII-DDD"
cert (:cert (ssl-simple/gen-self-signed-cert
"ssl-client"
1
{:keylength 512
:extensions [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value extension-value}]}))
url-encoded-cert (let [cert-writer (StringWriter.)
_ (ssl-utils/cert->pem! cert cert-writer)]
(ring-codec/url-encode cert-writer))
http-get-no-ssl (fn [path]
(http-client/get
(str "http://localhost:8080/" path)
{:headers {"Accept" "application/json"
"X-Client-Cert" url-encoded-cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:gem-path gem-path}
:authorization {:version 1
:allow-header-cert-info true
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog"}]}
:webserver {:host "localhost"
:port 8080}}
(testing "as 403 for unauthorized user"
(logutils/with-test-logging
(let [response (http-get-no-ssl
"puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))))
(testing "for certificate when provided"
(let [environment-dir (fs/file jruby-testutils/code-dir
"environments")
manifest-dir (fs/file environment-dir
"production"
"manifests")]
(try
(fs/mkdirs manifest-dir)
(spit (fs/file manifest-dir "site.pp")
(str/join "\n"
["notify {'trusty_info':"
" message => $trusted[extensions][pp_uuid]"
"}\n"]))
(let [response
(http-get-no-ssl
"puppet/v3/catalog/private?environment=production")
expected-content-in-catalog
(str
"\"parameters\":{\"message\":\""
extension-value
"\"}")]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.contains (:body response) expected-content-in-catalog)
(str "Did not find '" expected-content-in-catalog
"' in full response body: " (:body response))))
(finally
(fs/delete-dir environment-dir))))))))))
(deftest ^:integration custom-oids-passed-to-tk-auth
(testing "puppet server successfully utilizes custom oid mappings and puppet short names for authorization"
(logging/with-test-logging
(bootstrap/with-puppetserver-running-with-mock-jruby-puppet-fn
"JRuby mocking is safe here because these tests are strictly validating
the Clojure tk-auth checks."
app
{:jruby-puppet {:gem-path gem-path}
:authorization {:version 1
:allow-header-cert-info true
:rules
[{:match-request {:path "/"
:type "path"}
:allow {:extensions {:shiningfinger "Burning Finger"}}
:deny {:extensions {:pp_uuid "not a uuid"}}
:sort-order 1
:name "all endpoints"}]}
:webserver {:host "localhost"
:port 8080}
:puppet {"csr_attributes" (str test-resources-dir "/csr_attributes.yaml")
"trusted_oid_mapping_file" (str test-resources-dir
"/custom_trusted_oid_mapping.yaml")}}
(jruby-testutils/create-mock-jruby-puppet-fn-with-handle-response-params
200
"we've been tk-authorized!")
(let [good-exts [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "12345"}
{:oid "1.3.6.1.4.1.34380.1.2.2"
:critical false
:value "Burning Finger"}]
bad-exts [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "not a uuid"}
{:oid "1.3.6.1.4.1.34380.1.2.2"
:critical false
:value "Burning Finger"}]
create-cert (fn [extensions]
(:cert (ssl-simple/gen-self-signed-cert
"ssl-client"
1
{:keylength 512
:extensions extensions})))
allowable-cert (create-cert good-exts)
deniable-cert (create-cert bad-exts)
url-encode-cert (fn [cert]
(let [cert-writer (StringWriter.)
_ (ssl-utils/cert->pem! cert cert-writer)]
(ring-codec/url-encode cert-writer)))
url-encoded-allowable-cert (url-encode-cert allowable-cert)
url-encoded-deniable-cert (url-encode-cert deniable-cert)
http-get-no-ssl (fn [path cert]
(http-client/get
(str "http://localhost:8080/" path)
{:headers {"Accept" "application/json"
"X-Client-Cert" cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(testing "ca endpoints use oid shortnames"
(let [path "/puppet-ca/v1/certificate_status/localhost"
cert-status-response (http-get-no-ssl path url-encoded-allowable-cert)
cert-status-body (-> cert-status-response
:body
cheshire/parse-string)]
(is (= 200 (:status cert-status-response)))
;; Assert that some of the content looks like it came from the
;; certificate_statuses endpoint
(is (= "localhost" (get cert-status-body "name")))
(is (= "signed" (get cert-status-body "state")))
(is (= 403 (:status (http-get-no-ssl path url-encoded-deniable-cert))))))
(testing "master endpoints use oid shortnames"
(let [path "puppet/v3/catalog/private?environment=production"
catalog-response (http-get-no-ssl path url-encoded-allowable-cert)]
(is (= 200 (:status catalog-response)))
(is (= "we've been tk-authorized!" (:body catalog-response)))
(is (= 403 (:status (http-get-no-ssl path url-encoded-deniable-cert))))))
(testing "puppet-admin endpoints support oid shortnames"
(let [path "/puppet-admin-api/v1/environment-cache?environment=production"
http-delete (fn [cert]
(http-client/delete
(str "http://localhost:8080/" path)
{:headers {"Accept" "application/json"
"X-Client-Cert" cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(is (= 204 (:status (http-delete url-encoded-allowable-cert))))
(is (= 403 (:status (http-delete url-encoded-deniable-cert)))))))))))
| 100247 | (ns puppetlabs.puppetserver.auth-conf-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[puppetlabs.puppetserver.bootstrap-testutils :as bootstrap]
[puppetlabs.http.client.sync :as http-client]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[puppetlabs.ssl-utils.simple :as ssl-simple]
[puppetlabs.ssl-utils.core :as ssl-utils]
[schema.test :as schema-test]
[puppetlabs.services.jruby.jruby-puppet-testutils :as jruby-testutils]
[puppetlabs.puppetserver.testutils :as testutils :refer [http-get]]
[me.raynes.fs :as fs]
[ring.util.codec :as ring-codec]
[puppetlabs.trapperkeeper.testutils.logging :as logging]
[cheshire.core :as cheshire])
(:import (java.io StringWriter)))
(def test-resources-dir
(ks/absolute-path "./dev-resources/puppetlabs/puppetserver/auth_conf_test"))
(def gem-path
[(ks/absolute-path jruby-testutils/gem-path)])
(defn script-path
[script-name]
(str test-resources-dir "/" script-name))
(use-fixtures
:once
schema-test/validate-schemas
(testutils/with-puppet-conf (fs/file test-resources-dir "puppet.conf")))
(deftest ^:integration request-with-ssl-cert-handled-via-tk-auth
(testing (str "Request with SSL certificate via trapperkeeper-authorization "
"handled")
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet
{:gem-path gem-path}
:authorization {:version 1
:allow-header-cert-info false
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog unencoded"}
{:match-request {:path "^/puppet/v3/node/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "node"}
{:match-request {:path
"^/puppet/v3/catalog/%65ncoded$"
:type
"regex"}
:allow ["localhost"]
:sort-order 1
:name "catalog encoded"}]}}
(logutils/with-test-logging
(testing "for puppet 4 routes without url encoding"
(let [response (http-get "puppet/v3/node/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/node/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (testutils/catalog-name-matches?
(testutils/catalog-ring-response->catalog response)
"private"))))
(testing "for puppet 4 routes with url encoding"
(let [response
(http-get
"puppet/v3/%63atalog/%65ncoded?environment=production")]
;; The web server should decode the above URI path component to
;; "puppet/v3/catalog/encoded". There is a rule allowing
;; "localhost" for "%65ncoded" but no rule allowing "localhost"
;; for "encoded", so this should request should fail with a
;; 403 (Forbidden) error.
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response
(http-get
"puppet/v3/%63atalog/%2565ncoded?environment=production")]
;; The web server should decode the above URI path component to
;; "puppet/v3/catalog/%65ncoded". There is a rule allowing
;; "localhost" for "%65ncoded", so this should request should
;; succeed.
(is (= 200 (:status response))
(ks/pprint-to-string response))
;; The catalog which is returned should have a name of "%65ncoded"
;; since this should be the name derived from the web server
;; request after a single percent-decode.
(is (testutils/catalog-name-matches?
(testutils/catalog-ring-response->catalog response)
"%65ncoded")))
(let [response
(http-get
(str "puppet/v3/%63atalog/private/%2E%2E/secret?"
"environment=production"))]
;; The web server should decode the above URI path component to
;; "puppet/v3/catalog/private/../secret". The relative
;; path, "/../", inside of the path component is forbidden and
;; so should cause the webserver to throw a 'Bad Request' error.
(is (= 400 (:status response))
(ks/pprint-to-string response)))))))))
(deftest ^:integration request-with-x-client-headers-handled-via-tk-auth
(testing (str "Request with X-Client headers via trapperkeeper-authorization "
"handled")
(let [extension-value "UUUU-IIIII-DDD"
cert (:cert (ssl-simple/gen-self-signed-cert
"ssl-client"
1
{:keylength <KEY>
:extensions [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value extension-value}]}))
url-encoded-cert (let [cert-writer (StringWriter.)
_ (ssl-utils/cert->pem! cert cert-writer)]
(ring-codec/url-encode cert-writer))
http-get-no-ssl (fn [path]
(http-client/get
(str "http://localhost:8080/" path)
{:headers {"Accept" "application/json"
"X-Client-Cert" url-encoded-cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:gem-path gem-path}
:authorization {:version 1
:allow-header-cert-info true
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog"}]}
:webserver {:host "localhost"
:port 8080}}
(testing "as 403 for unauthorized user"
(logutils/with-test-logging
(let [response (http-get-no-ssl
"puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))))
(testing "for certificate when provided"
(let [environment-dir (fs/file jruby-testutils/code-dir
"environments")
manifest-dir (fs/file environment-dir
"production"
"manifests")]
(try
(fs/mkdirs manifest-dir)
(spit (fs/file manifest-dir "site.pp")
(str/join "\n"
["notify {'trusty_info':"
" message => $trusted[extensions][pp_uuid]"
"}\n"]))
(let [response
(http-get-no-ssl
"puppet/v3/catalog/private?environment=production")
expected-content-in-catalog
(str
"\"parameters\":{\"message\":\""
extension-value
"\"}")]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.contains (:body response) expected-content-in-catalog)
(str "Did not find '" expected-content-in-catalog
"' in full response body: " (:body response))))
(finally
(fs/delete-dir environment-dir))))))))))
(deftest ^:integration custom-oids-passed-to-tk-auth
(testing "puppet server successfully utilizes custom oid mappings and puppet short names for authorization"
(logging/with-test-logging
(bootstrap/with-puppetserver-running-with-mock-jruby-puppet-fn
"JRuby mocking is safe here because these tests are strictly validating
the Clojure tk-auth checks."
app
{:jruby-puppet {:gem-path gem-path}
:authorization {:version 1
:allow-header-cert-info true
:rules
[{:match-request {:path "/"
:type "path"}
:allow {:extensions {:shiningfinger "Burning Finger"}}
:deny {:extensions {:pp_uuid "not a uuid"}}
:sort-order 1
:name "all endpoints"}]}
:webserver {:host "localhost"
:port 8080}
:puppet {"csr_attributes" (str test-resources-dir "/csr_attributes.yaml")
"trusted_oid_mapping_file" (str test-resources-dir
"/custom_trusted_oid_mapping.yaml")}}
(jruby-testutils/create-mock-jruby-puppet-fn-with-handle-response-params
200
"we've been tk-authorized!")
(let [good-exts [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "12345"}
{:oid "1.3.6.1.4.1.34380.1.2.2"
:critical false
:value "Burning Finger"}]
bad-exts [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "not a uuid"}
{:oid "1.3.6.1.4.1.34380.1.2.2"
:critical false
:value "Burning Finger"}]
create-cert (fn [extensions]
(:cert (ssl-simple/gen-self-signed-cert
"ssl-client"
1
{:keylength <KEY>
:extensions extensions})))
allowable-cert (create-cert good-exts)
deniable-cert (create-cert bad-exts)
url-encode-cert (fn [cert]
(let [cert-writer (StringWriter.)
_ (ssl-utils/cert->pem! cert cert-writer)]
(ring-codec/url-encode cert-writer)))
url-encoded-allowable-cert (url-encode-cert allowable-cert)
url-encoded-deniable-cert (url-encode-cert deniable-cert)
http-get-no-ssl (fn [path cert]
(http-client/get
(str "http://localhost:8080/" path)
{:headers {"Accept" "application/json"
"X-Client-Cert" cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(testing "ca endpoints use oid shortnames"
(let [path "/puppet-ca/v1/certificate_status/localhost"
cert-status-response (http-get-no-ssl path url-encoded-allowable-cert)
cert-status-body (-> cert-status-response
:body
cheshire/parse-string)]
(is (= 200 (:status cert-status-response)))
;; Assert that some of the content looks like it came from the
;; certificate_statuses endpoint
(is (= "localhost" (get cert-status-body "name")))
(is (= "signed" (get cert-status-body "state")))
(is (= 403 (:status (http-get-no-ssl path url-encoded-deniable-cert))))))
(testing "master endpoints use oid shortnames"
(let [path "puppet/v3/catalog/private?environment=production"
catalog-response (http-get-no-ssl path url-encoded-allowable-cert)]
(is (= 200 (:status catalog-response)))
(is (= "we've been tk-authorized!" (:body catalog-response)))
(is (= 403 (:status (http-get-no-ssl path url-encoded-deniable-cert))))))
(testing "puppet-admin endpoints support oid shortnames"
(let [path "/puppet-admin-api/v1/environment-cache?environment=production"
http-delete (fn [cert]
(http-client/delete
(str "http://localhost:8080/" path)
{:headers {"Accept" "application/json"
"X-Client-Cert" cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(is (= 204 (:status (http-delete url-encoded-allowable-cert))))
(is (= 403 (:status (http-delete url-encoded-deniable-cert)))))))))))
| true | (ns puppetlabs.puppetserver.auth-conf-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[puppetlabs.puppetserver.bootstrap-testutils :as bootstrap]
[puppetlabs.http.client.sync :as http-client]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[puppetlabs.ssl-utils.simple :as ssl-simple]
[puppetlabs.ssl-utils.core :as ssl-utils]
[schema.test :as schema-test]
[puppetlabs.services.jruby.jruby-puppet-testutils :as jruby-testutils]
[puppetlabs.puppetserver.testutils :as testutils :refer [http-get]]
[me.raynes.fs :as fs]
[ring.util.codec :as ring-codec]
[puppetlabs.trapperkeeper.testutils.logging :as logging]
[cheshire.core :as cheshire])
(:import (java.io StringWriter)))
(def test-resources-dir
(ks/absolute-path "./dev-resources/puppetlabs/puppetserver/auth_conf_test"))
(def gem-path
[(ks/absolute-path jruby-testutils/gem-path)])
(defn script-path
[script-name]
(str test-resources-dir "/" script-name))
(use-fixtures
:once
schema-test/validate-schemas
(testutils/with-puppet-conf (fs/file test-resources-dir "puppet.conf")))
(deftest ^:integration request-with-ssl-cert-handled-via-tk-auth
(testing (str "Request with SSL certificate via trapperkeeper-authorization "
"handled")
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet
{:gem-path gem-path}
:authorization {:version 1
:allow-header-cert-info false
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog unencoded"}
{:match-request {:path "^/puppet/v3/node/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "node"}
{:match-request {:path
"^/puppet/v3/catalog/%65ncoded$"
:type
"regex"}
:allow ["localhost"]
:sort-order 1
:name "catalog encoded"}]}}
(logutils/with-test-logging
(testing "for puppet 4 routes without url encoding"
(let [response (http-get "puppet/v3/node/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/node/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (testutils/catalog-name-matches?
(testutils/catalog-ring-response->catalog response)
"private"))))
(testing "for puppet 4 routes with url encoding"
(let [response
(http-get
"puppet/v3/%63atalog/%65ncoded?environment=production")]
;; The web server should decode the above URI path component to
;; "puppet/v3/catalog/encoded". There is a rule allowing
;; "localhost" for "%65ncoded" but no rule allowing "localhost"
;; for "encoded", so this should request should fail with a
;; 403 (Forbidden) error.
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response
(http-get
"puppet/v3/%63atalog/%2565ncoded?environment=production")]
;; The web server should decode the above URI path component to
;; "puppet/v3/catalog/%65ncoded". There is a rule allowing
;; "localhost" for "%65ncoded", so this should request should
;; succeed.
(is (= 200 (:status response))
(ks/pprint-to-string response))
;; The catalog which is returned should have a name of "%65ncoded"
;; since this should be the name derived from the web server
;; request after a single percent-decode.
(is (testutils/catalog-name-matches?
(testutils/catalog-ring-response->catalog response)
"%65ncoded")))
(let [response
(http-get
(str "puppet/v3/%63atalog/private/%2E%2E/secret?"
"environment=production"))]
;; The web server should decode the above URI path component to
;; "puppet/v3/catalog/private/../secret". The relative
;; path, "/../", inside of the path component is forbidden and
;; so should cause the webserver to throw a 'Bad Request' error.
(is (= 400 (:status response))
(ks/pprint-to-string response)))))))))
(deftest ^:integration request-with-x-client-headers-handled-via-tk-auth
(testing (str "Request with X-Client headers via trapperkeeper-authorization "
"handled")
(let [extension-value "UUUU-IIIII-DDD"
cert (:cert (ssl-simple/gen-self-signed-cert
"ssl-client"
1
{:keylength PI:KEY:<KEY>END_PI
:extensions [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value extension-value}]}))
url-encoded-cert (let [cert-writer (StringWriter.)
_ (ssl-utils/cert->pem! cert cert-writer)]
(ring-codec/url-encode cert-writer))
http-get-no-ssl (fn [path]
(http-client/get
(str "http://localhost:8080/" path)
{:headers {"Accept" "application/json"
"X-Client-Cert" url-encoded-cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:gem-path gem-path}
:authorization {:version 1
:allow-header-cert-info true
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog"}]}
:webserver {:host "localhost"
:port 8080}}
(testing "as 403 for unauthorized user"
(logutils/with-test-logging
(let [response (http-get-no-ssl
"puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))))
(testing "for certificate when provided"
(let [environment-dir (fs/file jruby-testutils/code-dir
"environments")
manifest-dir (fs/file environment-dir
"production"
"manifests")]
(try
(fs/mkdirs manifest-dir)
(spit (fs/file manifest-dir "site.pp")
(str/join "\n"
["notify {'trusty_info':"
" message => $trusted[extensions][pp_uuid]"
"}\n"]))
(let [response
(http-get-no-ssl
"puppet/v3/catalog/private?environment=production")
expected-content-in-catalog
(str
"\"parameters\":{\"message\":\""
extension-value
"\"}")]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.contains (:body response) expected-content-in-catalog)
(str "Did not find '" expected-content-in-catalog
"' in full response body: " (:body response))))
(finally
(fs/delete-dir environment-dir))))))))))
(deftest ^:integration custom-oids-passed-to-tk-auth
(testing "puppet server successfully utilizes custom oid mappings and puppet short names for authorization"
(logging/with-test-logging
(bootstrap/with-puppetserver-running-with-mock-jruby-puppet-fn
"JRuby mocking is safe here because these tests are strictly validating
the Clojure tk-auth checks."
app
{:jruby-puppet {:gem-path gem-path}
:authorization {:version 1
:allow-header-cert-info true
:rules
[{:match-request {:path "/"
:type "path"}
:allow {:extensions {:shiningfinger "Burning Finger"}}
:deny {:extensions {:pp_uuid "not a uuid"}}
:sort-order 1
:name "all endpoints"}]}
:webserver {:host "localhost"
:port 8080}
:puppet {"csr_attributes" (str test-resources-dir "/csr_attributes.yaml")
"trusted_oid_mapping_file" (str test-resources-dir
"/custom_trusted_oid_mapping.yaml")}}
(jruby-testutils/create-mock-jruby-puppet-fn-with-handle-response-params
200
"we've been tk-authorized!")
(let [good-exts [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "12345"}
{:oid "1.3.6.1.4.1.34380.1.2.2"
:critical false
:value "Burning Finger"}]
bad-exts [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "not a uuid"}
{:oid "1.3.6.1.4.1.34380.1.2.2"
:critical false
:value "Burning Finger"}]
create-cert (fn [extensions]
(:cert (ssl-simple/gen-self-signed-cert
"ssl-client"
1
{:keylength PI:KEY:<KEY>END_PI
:extensions extensions})))
allowable-cert (create-cert good-exts)
deniable-cert (create-cert bad-exts)
url-encode-cert (fn [cert]
(let [cert-writer (StringWriter.)
_ (ssl-utils/cert->pem! cert cert-writer)]
(ring-codec/url-encode cert-writer)))
url-encoded-allowable-cert (url-encode-cert allowable-cert)
url-encoded-deniable-cert (url-encode-cert deniable-cert)
http-get-no-ssl (fn [path cert]
(http-client/get
(str "http://localhost:8080/" path)
{:headers {"Accept" "application/json"
"X-Client-Cert" cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(testing "ca endpoints use oid shortnames"
(let [path "/puppet-ca/v1/certificate_status/localhost"
cert-status-response (http-get-no-ssl path url-encoded-allowable-cert)
cert-status-body (-> cert-status-response
:body
cheshire/parse-string)]
(is (= 200 (:status cert-status-response)))
;; Assert that some of the content looks like it came from the
;; certificate_statuses endpoint
(is (= "localhost" (get cert-status-body "name")))
(is (= "signed" (get cert-status-body "state")))
(is (= 403 (:status (http-get-no-ssl path url-encoded-deniable-cert))))))
(testing "master endpoints use oid shortnames"
(let [path "puppet/v3/catalog/private?environment=production"
catalog-response (http-get-no-ssl path url-encoded-allowable-cert)]
(is (= 200 (:status catalog-response)))
(is (= "we've been tk-authorized!" (:body catalog-response)))
(is (= 403 (:status (http-get-no-ssl path url-encoded-deniable-cert))))))
(testing "puppet-admin endpoints support oid shortnames"
(let [path "/puppet-admin-api/v1/environment-cache?environment=production"
http-delete (fn [cert]
(http-client/delete
(str "http://localhost:8080/" path)
{:headers {"Accept" "application/json"
"X-Client-Cert" cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(is (= 204 (:status (http-delete url-encoded-allowable-cert))))
(is (= 403 (:status (http-delete url-encoded-deniable-cert)))))))))))
|
[
{
"context": "va \"8.0.15\"]\n [com.oracle/ojdbc8 \"12.2.0.1\"]\n ]\r\n :main ^:skip-aot query-to",
"end": 799,
"score": 0.9991930723190308,
"start": 791,
"tag": "IP_ADDRESS",
"value": "12.2.0.1"
}
] | project.clj | tomaszgigiel/query-to-excel | 0 | (defproject query-to-excel "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/java.jdbc "0.7.6"]
[net.sourceforge.jtds/jtds "1.3.1"]
[com.microsoft.sqlserver/mssql-jdbc "6.4.0.jre8"]
[commons-io/commons-io "2.6"]
[org.apache.poi/poi "4.0.1"]
[org.apache.poi/poi-ooxml "4.0.1"]
[com.ibm.informix/jdbc "4.10.10.0"]
[org.postgresql/postgresql "42.2.5"]
[mysql/mysql-connector-java "8.0.15"]
[com.oracle/ojdbc8 "12.2.0.1"]
]
:main ^:skip-aot query-to-excel.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all :jar-name "query-to-excel.jar" :uberjar-name "query-to-excel-standalone.jar"}}
:jvm-opts ["-Xms2G" "-Xmx2G" "-XX:-UseGCOverheadLimit" "-XX:+UseConcMarkSweepGC"]
)
| 111785 | (defproject query-to-excel "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/java.jdbc "0.7.6"]
[net.sourceforge.jtds/jtds "1.3.1"]
[com.microsoft.sqlserver/mssql-jdbc "6.4.0.jre8"]
[commons-io/commons-io "2.6"]
[org.apache.poi/poi "4.0.1"]
[org.apache.poi/poi-ooxml "4.0.1"]
[com.ibm.informix/jdbc "4.10.10.0"]
[org.postgresql/postgresql "42.2.5"]
[mysql/mysql-connector-java "8.0.15"]
[com.oracle/ojdbc8 "172.16.31.10"]
]
:main ^:skip-aot query-to-excel.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all :jar-name "query-to-excel.jar" :uberjar-name "query-to-excel-standalone.jar"}}
:jvm-opts ["-Xms2G" "-Xmx2G" "-XX:-UseGCOverheadLimit" "-XX:+UseConcMarkSweepGC"]
)
| true | (defproject query-to-excel "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/java.jdbc "0.7.6"]
[net.sourceforge.jtds/jtds "1.3.1"]
[com.microsoft.sqlserver/mssql-jdbc "6.4.0.jre8"]
[commons-io/commons-io "2.6"]
[org.apache.poi/poi "4.0.1"]
[org.apache.poi/poi-ooxml "4.0.1"]
[com.ibm.informix/jdbc "4.10.10.0"]
[org.postgresql/postgresql "42.2.5"]
[mysql/mysql-connector-java "8.0.15"]
[com.oracle/ojdbc8 "PI:IP_ADDRESS:172.16.31.10END_PI"]
]
:main ^:skip-aot query-to-excel.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all :jar-name "query-to-excel.jar" :uberjar-name "query-to-excel-standalone.jar"}}
:jvm-opts ["-Xms2G" "-Xmx2G" "-XX:-UseGCOverheadLimit" "-XX:+UseConcMarkSweepGC"]
)
|
[
{
"context": ";; Copyright (c) James Reeves. All rights reserved.\n;; The use and distribution",
"end": 29,
"score": 0.9998772144317627,
"start": 17,
"tag": "NAME",
"value": "James Reeves"
}
] | data/clojure/6ad2c55e37e21f6a213adc58c060d2d0_crypto.clj | maxim5/code-inspector | 5 | ;; Copyright (c) James Reeves. 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 compojure.crypto
"Functions for cryptographically signing, verifying and encrypting data."
(:use compojure.encodings
clojure.contrib.def
clojure.contrib.java-utils)
(:import java.security.SecureRandom
[javax.crypto Cipher KeyGenerator Mac]
[javax.crypto.spec SecretKeySpec IvParameterSpec]
java.util.UUID))
(defvar hmac-defaults
{:algorithm "HmacSHA256"}
"Default options for HMACs.")
(defvar encrypt-defaults
{:algorithm "AES"
:key-size 128
:mode "CBC"
:padding "PKCS5Padding"}
"Default options for symmetric encryption.")
(defn secure-random-bytes
"Returns a random byte array of the specified size. Can optionally supply
an PRNG algorithm (defaults is SHA1PRNG)."
([size]
(secure-random-bytes size "SHA1PRNG"))
([size algorithm]
(let [seed (make-array Byte/TYPE size)]
(.nextBytes (SecureRandom/getInstance algorithm) seed)
seed)))
(defn gen-secret-key
"Generate a random secret key from a map of encryption options."
([]
(gen-secret-key {}))
([options]
(secure-random-bytes (/ (options :key-size) 8))))
(defn gen-uuid
"Generate a random UUID."
[]
(str (UUID/randomUUID)))
(defn- to-bytes
"Converts its argument into an array of bytes."
[x]
(cond
(string? x) (.getBytes x)
(sequential? x) (into-array Byte/TYPE x)
:else x))
(defn hmac-bytes
"Generate a HMAC byte array with the supplied key on a byte array of data.
Takes an optional map of cryptography options."
[options key data]
(let [options (merge hmac-defaults options)
algorithm (options :algorithm)
hmac (doto (Mac/getInstance algorithm)
(.init (SecretKeySpec. key algorithm)))]
(.doFinal hmac data)))
(defn hmac
"Generate a Basc64-encoded HMAC with the supplied key on a byte array or
string of data. Takes an optional map of cryptography options."
[options key data]
(base64-encode-bytes (hmac-bytes options key (to-bytes data))))
(defn- make-algorithm
"Return an algorithm string suitable for JCE from a map of options."
[options]
(str (options :algorithm) "/" (options :mode) "/" (options :padding)))
(defn- make-cipher
"Create an AES Cipher instance."
[options]
(Cipher/getInstance (make-algorithm options)))
(defn encrypt-bytes
"Encrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
secret-key (SecretKeySpec. key (options :algorithm))
iv (secure-random-bytes (.getBlockSize cipher))]
(.init cipher Cipher/ENCRYPT_MODE secret-key (IvParameterSpec. iv))
(to-bytes (concat iv (.doFinal cipher data)))))
(defn decrypt-bytes
"Decrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
[iv data] (split-at (.getBlockSize cipher) data)
iv-spec (IvParameterSpec. (to-bytes iv))
secret-key (SecretKeySpec. key (options :algorithm))]
(.init cipher Cipher/DECRYPT_MODE secret-key iv-spec)
(.doFinal cipher (to-bytes data))))
(defn encrypt
"Encrypts a string or byte array with the given key and encryption options."
[options key data]
(base64-encode-bytes (encrypt-bytes options key (to-bytes data))))
(defn decrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[options key data]
(String. (decrypt-bytes options key (base64-decode-bytes data))))
(defn seal
"Seal a data structure into a cryptographically secure string. Ensures no-one
looks at or tampers with the data inside."
[key data]
(let [data (encrypt {} key (marshal data))]
(str data "--" (hmac {} key data))))
(defn unseal
"Read a cryptographically sealed data structure."
[key data]
(let [[data mac] (.split data "--")]
(if (= mac (hmac {} key data))
(unmarshal (decrypt {} key data)))))
| 7170 | ;; 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 compojure.crypto
"Functions for cryptographically signing, verifying and encrypting data."
(:use compojure.encodings
clojure.contrib.def
clojure.contrib.java-utils)
(:import java.security.SecureRandom
[javax.crypto Cipher KeyGenerator Mac]
[javax.crypto.spec SecretKeySpec IvParameterSpec]
java.util.UUID))
(defvar hmac-defaults
{:algorithm "HmacSHA256"}
"Default options for HMACs.")
(defvar encrypt-defaults
{:algorithm "AES"
:key-size 128
:mode "CBC"
:padding "PKCS5Padding"}
"Default options for symmetric encryption.")
(defn secure-random-bytes
"Returns a random byte array of the specified size. Can optionally supply
an PRNG algorithm (defaults is SHA1PRNG)."
([size]
(secure-random-bytes size "SHA1PRNG"))
([size algorithm]
(let [seed (make-array Byte/TYPE size)]
(.nextBytes (SecureRandom/getInstance algorithm) seed)
seed)))
(defn gen-secret-key
"Generate a random secret key from a map of encryption options."
([]
(gen-secret-key {}))
([options]
(secure-random-bytes (/ (options :key-size) 8))))
(defn gen-uuid
"Generate a random UUID."
[]
(str (UUID/randomUUID)))
(defn- to-bytes
"Converts its argument into an array of bytes."
[x]
(cond
(string? x) (.getBytes x)
(sequential? x) (into-array Byte/TYPE x)
:else x))
(defn hmac-bytes
"Generate a HMAC byte array with the supplied key on a byte array of data.
Takes an optional map of cryptography options."
[options key data]
(let [options (merge hmac-defaults options)
algorithm (options :algorithm)
hmac (doto (Mac/getInstance algorithm)
(.init (SecretKeySpec. key algorithm)))]
(.doFinal hmac data)))
(defn hmac
"Generate a Basc64-encoded HMAC with the supplied key on a byte array or
string of data. Takes an optional map of cryptography options."
[options key data]
(base64-encode-bytes (hmac-bytes options key (to-bytes data))))
(defn- make-algorithm
"Return an algorithm string suitable for JCE from a map of options."
[options]
(str (options :algorithm) "/" (options :mode) "/" (options :padding)))
(defn- make-cipher
"Create an AES Cipher instance."
[options]
(Cipher/getInstance (make-algorithm options)))
(defn encrypt-bytes
"Encrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
secret-key (SecretKeySpec. key (options :algorithm))
iv (secure-random-bytes (.getBlockSize cipher))]
(.init cipher Cipher/ENCRYPT_MODE secret-key (IvParameterSpec. iv))
(to-bytes (concat iv (.doFinal cipher data)))))
(defn decrypt-bytes
"Decrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
[iv data] (split-at (.getBlockSize cipher) data)
iv-spec (IvParameterSpec. (to-bytes iv))
secret-key (SecretKeySpec. key (options :algorithm))]
(.init cipher Cipher/DECRYPT_MODE secret-key iv-spec)
(.doFinal cipher (to-bytes data))))
(defn encrypt
"Encrypts a string or byte array with the given key and encryption options."
[options key data]
(base64-encode-bytes (encrypt-bytes options key (to-bytes data))))
(defn decrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[options key data]
(String. (decrypt-bytes options key (base64-decode-bytes data))))
(defn seal
"Seal a data structure into a cryptographically secure string. Ensures no-one
looks at or tampers with the data inside."
[key data]
(let [data (encrypt {} key (marshal data))]
(str data "--" (hmac {} key data))))
(defn unseal
"Read a cryptographically sealed data structure."
[key data]
(let [[data mac] (.split data "--")]
(if (= mac (hmac {} key data))
(unmarshal (decrypt {} key data)))))
| 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 compojure.crypto
"Functions for cryptographically signing, verifying and encrypting data."
(:use compojure.encodings
clojure.contrib.def
clojure.contrib.java-utils)
(:import java.security.SecureRandom
[javax.crypto Cipher KeyGenerator Mac]
[javax.crypto.spec SecretKeySpec IvParameterSpec]
java.util.UUID))
(defvar hmac-defaults
{:algorithm "HmacSHA256"}
"Default options for HMACs.")
(defvar encrypt-defaults
{:algorithm "AES"
:key-size 128
:mode "CBC"
:padding "PKCS5Padding"}
"Default options for symmetric encryption.")
(defn secure-random-bytes
"Returns a random byte array of the specified size. Can optionally supply
an PRNG algorithm (defaults is SHA1PRNG)."
([size]
(secure-random-bytes size "SHA1PRNG"))
([size algorithm]
(let [seed (make-array Byte/TYPE size)]
(.nextBytes (SecureRandom/getInstance algorithm) seed)
seed)))
(defn gen-secret-key
"Generate a random secret key from a map of encryption options."
([]
(gen-secret-key {}))
([options]
(secure-random-bytes (/ (options :key-size) 8))))
(defn gen-uuid
"Generate a random UUID."
[]
(str (UUID/randomUUID)))
(defn- to-bytes
"Converts its argument into an array of bytes."
[x]
(cond
(string? x) (.getBytes x)
(sequential? x) (into-array Byte/TYPE x)
:else x))
(defn hmac-bytes
"Generate a HMAC byte array with the supplied key on a byte array of data.
Takes an optional map of cryptography options."
[options key data]
(let [options (merge hmac-defaults options)
algorithm (options :algorithm)
hmac (doto (Mac/getInstance algorithm)
(.init (SecretKeySpec. key algorithm)))]
(.doFinal hmac data)))
(defn hmac
"Generate a Basc64-encoded HMAC with the supplied key on a byte array or
string of data. Takes an optional map of cryptography options."
[options key data]
(base64-encode-bytes (hmac-bytes options key (to-bytes data))))
(defn- make-algorithm
"Return an algorithm string suitable for JCE from a map of options."
[options]
(str (options :algorithm) "/" (options :mode) "/" (options :padding)))
(defn- make-cipher
"Create an AES Cipher instance."
[options]
(Cipher/getInstance (make-algorithm options)))
(defn encrypt-bytes
"Encrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
secret-key (SecretKeySpec. key (options :algorithm))
iv (secure-random-bytes (.getBlockSize cipher))]
(.init cipher Cipher/ENCRYPT_MODE secret-key (IvParameterSpec. iv))
(to-bytes (concat iv (.doFinal cipher data)))))
(defn decrypt-bytes
"Decrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
[iv data] (split-at (.getBlockSize cipher) data)
iv-spec (IvParameterSpec. (to-bytes iv))
secret-key (SecretKeySpec. key (options :algorithm))]
(.init cipher Cipher/DECRYPT_MODE secret-key iv-spec)
(.doFinal cipher (to-bytes data))))
(defn encrypt
"Encrypts a string or byte array with the given key and encryption options."
[options key data]
(base64-encode-bytes (encrypt-bytes options key (to-bytes data))))
(defn decrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[options key data]
(String. (decrypt-bytes options key (base64-decode-bytes data))))
(defn seal
"Seal a data structure into a cryptographically secure string. Ensures no-one
looks at or tampers with the data inside."
[key data]
(let [data (encrypt {} key (marshal data))]
(str data "--" (hmac {} key data))))
(defn unseal
"Read a cryptographically sealed data structure."
[key data]
(let [[data mac] (.split data "--")]
(if (= mac (hmac {} key data))
(unmarshal (decrypt {} key data)))))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald, Kristina Lisa Klinkner\" :date \"2017-01-03\"\n ",
"end": 105,
"score": 0.9998794794082642,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
},
{
"context": ":warn-on-boxed)\n(ns ^{:author \"John Alan McDonald, Kristina Lisa Klinkner\" :date \"2017-01-03\"\n :doc \"Brute force searc",
"end": 129,
"score": 0.9998769760131836,
"start": 107,
"tag": "NAME",
"value": "Kristina Lisa Klinkner"
}
] | src/main/clojure/taiga/split/object/categorical/all_subsets.clj | wahpenayo/taiga | 4 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald, Kristina Lisa Klinkner" :date "2017-01-03"
:doc "Brute force search over all 2-way partitions of the categories." }
taiga.split.object.categorical.all-subsets
(:require [zana.api :as z]
[taiga.utils :as utils]
[taiga.split.object.categorical.move :as move]
[taiga.tree.split.categorical :as categorical])
(:import [java.util Collection]
[zana.java.accumulator Accumulator]))
;;------------------------------------------------------------------------------
(defn- sum-counts ^long [^java.util.Map groups cats]
(loop [cats (seq cats)
sum (long 0)]
(if-not (empty? cats)
(recur (rest cats) (+ sum (z/count (.get groups (first cats)))))
sum)))
;;------------------------------------------------------------------------------
;; Try all possible binary partitions using a method that moves only one
;; category from right to left, or vice versa, at a time, and moves the
;; smallest cardinality categories most and highest cardinality categories
;; least.
(defn split [options]
(let [^clojure.lang.IFn cost-factory (:cost-factory options)
^clojure.lang.IFn feasible? (:feasible? options)
[^clojure.lang.Keyword kx ^clojure.lang.IFn x] (:this-predictor options)
^java.util.Map groups (z/group-by-not-nil x (:data options))]
(if (== 1 (z/count groups))
{:cost Double/POSITIVE_INFINITY}
(let [^clojure.lang.IFn y (:ground-truth options)
^Accumulator cost0 (cost-factory)
^Accumulator cost1 (cost-factory)
cats (seq (z/sort-by #(z/count (.get groups %)) (z/keys groups)))
left (set (butlast cats))
c1 (last cats)
right #{c1}]
(doseq [c left]
(let [^java.util.List group (.get groups c)
n (.size group)]
(dotimes [i n] (.add cost0 (y (.get group i))))))
(let [^java.util.List group (.get groups c1)
n (.size group)]
(dotimes [i n] (.add cost1 (y (.get group i)))))
(loop [moves (move/moves left)
left left
right right
cmin (double (utils/feasible-cost feasible? cost0 cost1))
lmin left
rmin right]
(if-not (empty? moves)
(let [move (first moves)
c (move/item move)
right? (move/right? move)
^java.util.List group (.get groups c)
n (.size group)
_ (if right?
(dotimes [i n]
(let [yi (y (.get group i))]
(.delete cost0 yi)
(.add cost1 yi)))
(dotimes [i n]
(let [yi (y (.get group i))]
(.add cost0 yi)
(.delete cost1 yi))))
cost (double (utils/feasible-cost feasible? cost0 cost1))
left (if right? (disj left c) (conj left c))
right (if right? (conj right c) (disj right c))]
(if (< cost cmin)
(recur (rest moves) left right cost left right)
(recur (rest moves) left right cmin lmin rmin)))
(if (or (>= cmin Double/POSITIVE_INFINITY)
(empty? lmin)
(empty? rmin))
{:cost cmin}
;; default (not in cats) is majority vote direction
(let [nleft (sum-counts groups lmin)
nright (sum-counts groups rmin)
cats (utils/to-set (if (> nleft nright) rmin lmin))]
{:split (categorical/make kx cats) :cost cmin}))))))))
;;------------------------------------------------------------------------------
| 2817 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>, <NAME>" :date "2017-01-03"
:doc "Brute force search over all 2-way partitions of the categories." }
taiga.split.object.categorical.all-subsets
(:require [zana.api :as z]
[taiga.utils :as utils]
[taiga.split.object.categorical.move :as move]
[taiga.tree.split.categorical :as categorical])
(:import [java.util Collection]
[zana.java.accumulator Accumulator]))
;;------------------------------------------------------------------------------
(defn- sum-counts ^long [^java.util.Map groups cats]
(loop [cats (seq cats)
sum (long 0)]
(if-not (empty? cats)
(recur (rest cats) (+ sum (z/count (.get groups (first cats)))))
sum)))
;;------------------------------------------------------------------------------
;; Try all possible binary partitions using a method that moves only one
;; category from right to left, or vice versa, at a time, and moves the
;; smallest cardinality categories most and highest cardinality categories
;; least.
(defn split [options]
(let [^clojure.lang.IFn cost-factory (:cost-factory options)
^clojure.lang.IFn feasible? (:feasible? options)
[^clojure.lang.Keyword kx ^clojure.lang.IFn x] (:this-predictor options)
^java.util.Map groups (z/group-by-not-nil x (:data options))]
(if (== 1 (z/count groups))
{:cost Double/POSITIVE_INFINITY}
(let [^clojure.lang.IFn y (:ground-truth options)
^Accumulator cost0 (cost-factory)
^Accumulator cost1 (cost-factory)
cats (seq (z/sort-by #(z/count (.get groups %)) (z/keys groups)))
left (set (butlast cats))
c1 (last cats)
right #{c1}]
(doseq [c left]
(let [^java.util.List group (.get groups c)
n (.size group)]
(dotimes [i n] (.add cost0 (y (.get group i))))))
(let [^java.util.List group (.get groups c1)
n (.size group)]
(dotimes [i n] (.add cost1 (y (.get group i)))))
(loop [moves (move/moves left)
left left
right right
cmin (double (utils/feasible-cost feasible? cost0 cost1))
lmin left
rmin right]
(if-not (empty? moves)
(let [move (first moves)
c (move/item move)
right? (move/right? move)
^java.util.List group (.get groups c)
n (.size group)
_ (if right?
(dotimes [i n]
(let [yi (y (.get group i))]
(.delete cost0 yi)
(.add cost1 yi)))
(dotimes [i n]
(let [yi (y (.get group i))]
(.add cost0 yi)
(.delete cost1 yi))))
cost (double (utils/feasible-cost feasible? cost0 cost1))
left (if right? (disj left c) (conj left c))
right (if right? (conj right c) (disj right c))]
(if (< cost cmin)
(recur (rest moves) left right cost left right)
(recur (rest moves) left right cmin lmin rmin)))
(if (or (>= cmin Double/POSITIVE_INFINITY)
(empty? lmin)
(empty? rmin))
{:cost cmin}
;; default (not in cats) is majority vote direction
(let [nleft (sum-counts groups lmin)
nright (sum-counts groups rmin)
cats (utils/to-set (if (> nleft nright) rmin lmin))]
{:split (categorical/make kx cats) :cost cmin}))))))))
;;------------------------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" :date "2017-01-03"
:doc "Brute force search over all 2-way partitions of the categories." }
taiga.split.object.categorical.all-subsets
(:require [zana.api :as z]
[taiga.utils :as utils]
[taiga.split.object.categorical.move :as move]
[taiga.tree.split.categorical :as categorical])
(:import [java.util Collection]
[zana.java.accumulator Accumulator]))
;;------------------------------------------------------------------------------
(defn- sum-counts ^long [^java.util.Map groups cats]
(loop [cats (seq cats)
sum (long 0)]
(if-not (empty? cats)
(recur (rest cats) (+ sum (z/count (.get groups (first cats)))))
sum)))
;;------------------------------------------------------------------------------
;; Try all possible binary partitions using a method that moves only one
;; category from right to left, or vice versa, at a time, and moves the
;; smallest cardinality categories most and highest cardinality categories
;; least.
(defn split [options]
(let [^clojure.lang.IFn cost-factory (:cost-factory options)
^clojure.lang.IFn feasible? (:feasible? options)
[^clojure.lang.Keyword kx ^clojure.lang.IFn x] (:this-predictor options)
^java.util.Map groups (z/group-by-not-nil x (:data options))]
(if (== 1 (z/count groups))
{:cost Double/POSITIVE_INFINITY}
(let [^clojure.lang.IFn y (:ground-truth options)
^Accumulator cost0 (cost-factory)
^Accumulator cost1 (cost-factory)
cats (seq (z/sort-by #(z/count (.get groups %)) (z/keys groups)))
left (set (butlast cats))
c1 (last cats)
right #{c1}]
(doseq [c left]
(let [^java.util.List group (.get groups c)
n (.size group)]
(dotimes [i n] (.add cost0 (y (.get group i))))))
(let [^java.util.List group (.get groups c1)
n (.size group)]
(dotimes [i n] (.add cost1 (y (.get group i)))))
(loop [moves (move/moves left)
left left
right right
cmin (double (utils/feasible-cost feasible? cost0 cost1))
lmin left
rmin right]
(if-not (empty? moves)
(let [move (first moves)
c (move/item move)
right? (move/right? move)
^java.util.List group (.get groups c)
n (.size group)
_ (if right?
(dotimes [i n]
(let [yi (y (.get group i))]
(.delete cost0 yi)
(.add cost1 yi)))
(dotimes [i n]
(let [yi (y (.get group i))]
(.add cost0 yi)
(.delete cost1 yi))))
cost (double (utils/feasible-cost feasible? cost0 cost1))
left (if right? (disj left c) (conj left c))
right (if right? (conj right c) (disj right c))]
(if (< cost cmin)
(recur (rest moves) left right cost left right)
(recur (rest moves) left right cmin lmin rmin)))
(if (or (>= cmin Double/POSITIVE_INFINITY)
(empty? lmin)
(empty? rmin))
{:cost cmin}
;; default (not in cats) is majority vote direction
(let [nleft (sum-counts groups lmin)
nright (sum-counts groups rmin)
cats (utils/to-set (if (> nleft nright) rmin lmin))]
{:split (categorical/make kx cats) :cost cmin}))))))))
;;------------------------------------------------------------------------------
|
[
{
"context": " \"Clara Example Rules\"\n :url \"https://github.com/cerner/clara-examples\"\n :license {:name \"Apache License",
"end": 125,
"score": 0.9994001388549805,
"start": 119,
"tag": "USERNAME",
"value": "cerner"
},
{
"context": "scm {:name \"git\"\n :url \"https://github.com/cerner/clara-examples.git\"}\n :pom-addition [:developers",
"end": 1454,
"score": 0.9156343936920166,
"start": 1448,
"tag": "USERNAME",
"value": "cerner"
},
{
"context": "\"}\n :pom-addition [:developers [:developer {:id \"rbrush\"}\n [:name \"Ryan Brus",
"end": 1529,
"score": 0.7003284692764282,
"start": 1523,
"tag": "USERNAME",
"value": "rbrush"
},
{
"context": "d \"rbrush\"}\n [:name \"Ryan Brush\"]\n [:url \"http://www",
"end": 1580,
"score": 0.9974195957183838,
"start": 1570,
"tag": "NAME",
"value": "Ryan Brush"
}
] | project.clj | cerner/clara-examples | 50 | (defproject com.cerner/clara-examples "0.2.0-SNAPSHOT"
:description "Clara Example Rules"
:url "https://github.com/cerner/clara-examples"
:license {:name "Apache License Version 2.0"
:url "https://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[com.google.guava/guava "15.0"] ; Explicitly pull new Guava version for dependency conflicts.
[org.clojure/clojure "1.7.0"]
[com.cerner/clara-rules "0.21.1"]
;; Dependencies for ClojureScript example.
[prismatic/dommy "1.1.0"]
[hipo "0.4.0"]
[org.clojure/clojurescript "1.7.170"]
;; Dependency for time-based rules example.
[clj-time "0.6.0"]
;; Dependency for rule DSL example.
[instaparse "1.4.1"]]
:plugins [[lein-cljsbuild "1.1.1"]]
:source-paths ["src/main/clojure"]
:test-paths ["src/test/clojure"]
:java-source-paths ["src/main/java"]
:main clara.examples
:hooks [leiningen.cljsbuild]
:cljsbuild {:builds [{:source-paths ["src/main/clojurescript"]
:jar true
:compiler {:output-to "resources/public/js/examples.js"
:optimizations :advanced}}]}
;; Austin for the ClojureScript REPL.
:profiles {:dev {:plugins [[com.cemerick/austin "0.1.6"]]}}
:scm {:name "git"
:url "https://github.com/cerner/clara-examples.git"}
:pom-addition [:developers [:developer {:id "rbrush"}
[:name "Ryan Brush"]
[:url "http://www.clara-rules.org"]]]
:repositories [["snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/"}]]
:deploy-repositories [["snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/"
:creds :gpg}]])
| 99590 | (defproject com.cerner/clara-examples "0.2.0-SNAPSHOT"
:description "Clara Example Rules"
:url "https://github.com/cerner/clara-examples"
:license {:name "Apache License Version 2.0"
:url "https://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[com.google.guava/guava "15.0"] ; Explicitly pull new Guava version for dependency conflicts.
[org.clojure/clojure "1.7.0"]
[com.cerner/clara-rules "0.21.1"]
;; Dependencies for ClojureScript example.
[prismatic/dommy "1.1.0"]
[hipo "0.4.0"]
[org.clojure/clojurescript "1.7.170"]
;; Dependency for time-based rules example.
[clj-time "0.6.0"]
;; Dependency for rule DSL example.
[instaparse "1.4.1"]]
:plugins [[lein-cljsbuild "1.1.1"]]
:source-paths ["src/main/clojure"]
:test-paths ["src/test/clojure"]
:java-source-paths ["src/main/java"]
:main clara.examples
:hooks [leiningen.cljsbuild]
:cljsbuild {:builds [{:source-paths ["src/main/clojurescript"]
:jar true
:compiler {:output-to "resources/public/js/examples.js"
:optimizations :advanced}}]}
;; Austin for the ClojureScript REPL.
:profiles {:dev {:plugins [[com.cemerick/austin "0.1.6"]]}}
:scm {:name "git"
:url "https://github.com/cerner/clara-examples.git"}
:pom-addition [:developers [:developer {:id "rbrush"}
[:name "<NAME>"]
[:url "http://www.clara-rules.org"]]]
:repositories [["snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/"}]]
:deploy-repositories [["snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/"
:creds :gpg}]])
| true | (defproject com.cerner/clara-examples "0.2.0-SNAPSHOT"
:description "Clara Example Rules"
:url "https://github.com/cerner/clara-examples"
:license {:name "Apache License Version 2.0"
:url "https://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[com.google.guava/guava "15.0"] ; Explicitly pull new Guava version for dependency conflicts.
[org.clojure/clojure "1.7.0"]
[com.cerner/clara-rules "0.21.1"]
;; Dependencies for ClojureScript example.
[prismatic/dommy "1.1.0"]
[hipo "0.4.0"]
[org.clojure/clojurescript "1.7.170"]
;; Dependency for time-based rules example.
[clj-time "0.6.0"]
;; Dependency for rule DSL example.
[instaparse "1.4.1"]]
:plugins [[lein-cljsbuild "1.1.1"]]
:source-paths ["src/main/clojure"]
:test-paths ["src/test/clojure"]
:java-source-paths ["src/main/java"]
:main clara.examples
:hooks [leiningen.cljsbuild]
:cljsbuild {:builds [{:source-paths ["src/main/clojurescript"]
:jar true
:compiler {:output-to "resources/public/js/examples.js"
:optimizations :advanced}}]}
;; Austin for the ClojureScript REPL.
:profiles {:dev {:plugins [[com.cemerick/austin "0.1.6"]]}}
:scm {:name "git"
:url "https://github.com/cerner/clara-examples.git"}
:pom-addition [:developers [:developer {:id "rbrush"}
[:name "PI:NAME:<NAME>END_PI"]
[:url "http://www.clara-rules.org"]]]
:repositories [["snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/"}]]
:deploy-repositories [["snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/"
:creds :gpg}]])
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998176693916321,
"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.9998224973678589,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/src/clj/editor/url.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.url
(:import (java.io IOException)
(java.net HttpURLConnection MalformedURLException URISyntaxException URI URL)
(java.nio.charset Charset)))
(defn reachable?
[^URI uri]
(let [url (.toURL uri)
conn (doto ^HttpURLConnection (.openConnection url)
(.setAllowUserInteraction false)
(.setInstanceFollowRedirects false)
(.setConnectTimeout 2000)
(.setReadTimeout 2000)
(.setUseCaches false))]
(try
(.connect conn)
(.getContentLength conn)
true
(catch IOException _
false)
(finally
(.disconnect conn)))))
(defn strip-path
^URI [^URI uri]
(URI. (.getScheme uri) nil (.getHost uri) (.getPort uri) nil nil nil))
(defn try-parse
^URI [^String s]
(try (.toURI (URL. s))
(catch MalformedURLException _ nil)
(catch URISyntaxException _ nil)))
(defn x-www-form-urlencoded-safe-character?
"Safe characters for x-www-form-urlencoded data, as per java.net.URLEncoder
and browser behaviour, i.e. alphanumeric plus '*', '-', '.', '_' characters."
[^long char]
(case char
(42 45 46 95) true ; "*-._"
(or (<= 48 char 57) ; 0 - 9
(<= 65 char 90) ; A - Z
(<= 97 char 122)))) ; a - z
(defn encode
"Percent-encode content into a format suitable for use in an HTTP PUT or HTTP POST.
See: https://en.wikipedia.org/wiki/Percent-encoding
This implementation provides additional flexibility compared to using the
(java.net.URLEncoder/encode ...) function, most notably the ability to encode
space characters as '%20' instead of '+'.
Ported to Clojure from this implementation:
https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.5.3//httpclient/src/main/java/org/apache/http/client/utils/URLEncodedUtils.java"
^String [safe-character? blank-as-plus? ^Charset charset ^String content]
(assert (ifn? safe-character?))
(assert (not (ifn? blank-as-plus?)))
(when (some? content)
(let [builder (StringBuilder.)
byte-buffer (.encode charset content)]
(while (.hasRemaining byte-buffer)
(let [character (bit-and (.get byte-buffer) 0xff)]
(cond
(safe-character? character)
(.append builder (char character))
(and blank-as-plus? (= 32 character))
(.append builder \+)
:else
(let [hex1 (Character/toUpperCase (Character/forDigit (bit-and (bit-shift-right character 4) 0xf) 16))
hex2 (Character/toUpperCase (Character/forDigit (bit-and character 0xf) 16))]
(.append builder \%)
(.append builder hex1)
(.append builder hex2)))))
(.toString builder))))
| 61812 | ;; 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.url
(:import (java.io IOException)
(java.net HttpURLConnection MalformedURLException URISyntaxException URI URL)
(java.nio.charset Charset)))
(defn reachable?
[^URI uri]
(let [url (.toURL uri)
conn (doto ^HttpURLConnection (.openConnection url)
(.setAllowUserInteraction false)
(.setInstanceFollowRedirects false)
(.setConnectTimeout 2000)
(.setReadTimeout 2000)
(.setUseCaches false))]
(try
(.connect conn)
(.getContentLength conn)
true
(catch IOException _
false)
(finally
(.disconnect conn)))))
(defn strip-path
^URI [^URI uri]
(URI. (.getScheme uri) nil (.getHost uri) (.getPort uri) nil nil nil))
(defn try-parse
^URI [^String s]
(try (.toURI (URL. s))
(catch MalformedURLException _ nil)
(catch URISyntaxException _ nil)))
(defn x-www-form-urlencoded-safe-character?
"Safe characters for x-www-form-urlencoded data, as per java.net.URLEncoder
and browser behaviour, i.e. alphanumeric plus '*', '-', '.', '_' characters."
[^long char]
(case char
(42 45 46 95) true ; "*-._"
(or (<= 48 char 57) ; 0 - 9
(<= 65 char 90) ; A - Z
(<= 97 char 122)))) ; a - z
(defn encode
"Percent-encode content into a format suitable for use in an HTTP PUT or HTTP POST.
See: https://en.wikipedia.org/wiki/Percent-encoding
This implementation provides additional flexibility compared to using the
(java.net.URLEncoder/encode ...) function, most notably the ability to encode
space characters as '%20' instead of '+'.
Ported to Clojure from this implementation:
https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.5.3//httpclient/src/main/java/org/apache/http/client/utils/URLEncodedUtils.java"
^String [safe-character? blank-as-plus? ^Charset charset ^String content]
(assert (ifn? safe-character?))
(assert (not (ifn? blank-as-plus?)))
(when (some? content)
(let [builder (StringBuilder.)
byte-buffer (.encode charset content)]
(while (.hasRemaining byte-buffer)
(let [character (bit-and (.get byte-buffer) 0xff)]
(cond
(safe-character? character)
(.append builder (char character))
(and blank-as-plus? (= 32 character))
(.append builder \+)
:else
(let [hex1 (Character/toUpperCase (Character/forDigit (bit-and (bit-shift-right character 4) 0xf) 16))
hex2 (Character/toUpperCase (Character/forDigit (bit-and character 0xf) 16))]
(.append builder \%)
(.append builder hex1)
(.append builder hex2)))))
(.toString builder))))
| 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.url
(:import (java.io IOException)
(java.net HttpURLConnection MalformedURLException URISyntaxException URI URL)
(java.nio.charset Charset)))
(defn reachable?
[^URI uri]
(let [url (.toURL uri)
conn (doto ^HttpURLConnection (.openConnection url)
(.setAllowUserInteraction false)
(.setInstanceFollowRedirects false)
(.setConnectTimeout 2000)
(.setReadTimeout 2000)
(.setUseCaches false))]
(try
(.connect conn)
(.getContentLength conn)
true
(catch IOException _
false)
(finally
(.disconnect conn)))))
(defn strip-path
^URI [^URI uri]
(URI. (.getScheme uri) nil (.getHost uri) (.getPort uri) nil nil nil))
(defn try-parse
^URI [^String s]
(try (.toURI (URL. s))
(catch MalformedURLException _ nil)
(catch URISyntaxException _ nil)))
(defn x-www-form-urlencoded-safe-character?
"Safe characters for x-www-form-urlencoded data, as per java.net.URLEncoder
and browser behaviour, i.e. alphanumeric plus '*', '-', '.', '_' characters."
[^long char]
(case char
(42 45 46 95) true ; "*-._"
(or (<= 48 char 57) ; 0 - 9
(<= 65 char 90) ; A - Z
(<= 97 char 122)))) ; a - z
(defn encode
"Percent-encode content into a format suitable for use in an HTTP PUT or HTTP POST.
See: https://en.wikipedia.org/wiki/Percent-encoding
This implementation provides additional flexibility compared to using the
(java.net.URLEncoder/encode ...) function, most notably the ability to encode
space characters as '%20' instead of '+'.
Ported to Clojure from this implementation:
https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.5.3//httpclient/src/main/java/org/apache/http/client/utils/URLEncodedUtils.java"
^String [safe-character? blank-as-plus? ^Charset charset ^String content]
(assert (ifn? safe-character?))
(assert (not (ifn? blank-as-plus?)))
(when (some? content)
(let [builder (StringBuilder.)
byte-buffer (.encode charset content)]
(while (.hasRemaining byte-buffer)
(let [character (bit-and (.get byte-buffer) 0xff)]
(cond
(safe-character? character)
(.append builder (char character))
(and blank-as-plus? (= 32 character))
(.append builder \+)
:else
(let [hex1 (Character/toUpperCase (Character/forDigit (bit-and (bit-shift-right character 4) 0xf) 16))
hex2 (Character/toUpperCase (Character/forDigit (bit-and character 0xf) 16))]
(.append builder \%)
(.append builder hex1)
(.append builder hex2)))))
(.toString builder))))
|
[
{
"context": ":db (apply str (drop 1 (.getPath uri)))\n :user username\n :password password\n :host (.getHost uri)",
"end": 1227,
"score": 0.606134831905365,
"start": 1219,
"tag": "USERNAME",
"value": "username"
},
{
"context": ".getPath uri)))\n :user username\n :password password\n :host (.getHost uri)\n :port (.getPort ur",
"end": 1251,
"score": 0.9978366494178772,
"start": 1243,
"tag": "PASSWORD",
"value": "password"
}
] | src/zoo_storm/database.clj | zooniverse/zoo-event-storm | 0 | (ns zoo-storm.database
(:require [korma.core :refer :all]
[korma.db :refer [postgres create-db with-db]]
[paneer.core :as p]
[paneer.db :as pdb]
[clojure.string :refer [split]]))
(defn- table-exists?
[db table-name]
(not (empty? (with-db db
(select "information_schema.columns"
(where {:table_name table-name}))))))
(defn create-table-if-not-exists
[db tbl]
(if-not (table-exists? db tbl)
(-> (p/create*)
(p/table tbl)
(p/column :id :bigserial "PRIMARY KEY")
(p/varchar :user_id 24)
(p/varchar :user_ip 15)
(p/text :lang)
(p/text :project)
(p/text :user_agent)
(p/text :user_name)
(p/text :subjects)
(p/column :data :json)
(p/timestamp :created_at)
(p/varchar :country_code 2)
(p/varchar :country_name 50)
(p/varchar :city_name 50)
(p/float :latitude)
(p/float :longitude)
(pdb/execute :db db))))
(defn- uri-to-db-map
[uri]
(let [uri (java.net.URI. uri)
[username password] (split (.getUserInfo uri) #":")]
{:db (apply str (drop 1 (.getPath uri)))
:user username
:password password
:host (.getHost uri)
:port (.getPort uri)}))
(defn create-db-connection
[pg-uri]
(-> (uri-to-db-map pg-uri) postgres create-db))
| 4789 | (ns zoo-storm.database
(:require [korma.core :refer :all]
[korma.db :refer [postgres create-db with-db]]
[paneer.core :as p]
[paneer.db :as pdb]
[clojure.string :refer [split]]))
(defn- table-exists?
[db table-name]
(not (empty? (with-db db
(select "information_schema.columns"
(where {:table_name table-name}))))))
(defn create-table-if-not-exists
[db tbl]
(if-not (table-exists? db tbl)
(-> (p/create*)
(p/table tbl)
(p/column :id :bigserial "PRIMARY KEY")
(p/varchar :user_id 24)
(p/varchar :user_ip 15)
(p/text :lang)
(p/text :project)
(p/text :user_agent)
(p/text :user_name)
(p/text :subjects)
(p/column :data :json)
(p/timestamp :created_at)
(p/varchar :country_code 2)
(p/varchar :country_name 50)
(p/varchar :city_name 50)
(p/float :latitude)
(p/float :longitude)
(pdb/execute :db db))))
(defn- uri-to-db-map
[uri]
(let [uri (java.net.URI. uri)
[username password] (split (.getUserInfo uri) #":")]
{:db (apply str (drop 1 (.getPath uri)))
:user username
:password <PASSWORD>
:host (.getHost uri)
:port (.getPort uri)}))
(defn create-db-connection
[pg-uri]
(-> (uri-to-db-map pg-uri) postgres create-db))
| true | (ns zoo-storm.database
(:require [korma.core :refer :all]
[korma.db :refer [postgres create-db with-db]]
[paneer.core :as p]
[paneer.db :as pdb]
[clojure.string :refer [split]]))
(defn- table-exists?
[db table-name]
(not (empty? (with-db db
(select "information_schema.columns"
(where {:table_name table-name}))))))
(defn create-table-if-not-exists
[db tbl]
(if-not (table-exists? db tbl)
(-> (p/create*)
(p/table tbl)
(p/column :id :bigserial "PRIMARY KEY")
(p/varchar :user_id 24)
(p/varchar :user_ip 15)
(p/text :lang)
(p/text :project)
(p/text :user_agent)
(p/text :user_name)
(p/text :subjects)
(p/column :data :json)
(p/timestamp :created_at)
(p/varchar :country_code 2)
(p/varchar :country_name 50)
(p/varchar :city_name 50)
(p/float :latitude)
(p/float :longitude)
(pdb/execute :db db))))
(defn- uri-to-db-map
[uri]
(let [uri (java.net.URI. uri)
[username password] (split (.getUserInfo uri) #":")]
{:db (apply str (drop 1 (.getPath uri)))
:user username
:password PI:PASSWORD:<PASSWORD>END_PI
:host (.getHost uri)
:port (.getPort uri)}))
(defn create-db-connection
[pg-uri]
(-> (uri-to-db-map pg-uri) postgres create-db))
|
[
{
"context": "dern Clojurescript Tutofrials](https://github.com/magomimmo/modern-cljs)\n- [Clojure for the Brave and True: c",
"end": 272,
"score": 0.9972835183143616,
"start": 263,
"tag": "USERNAME",
"value": "magomimmo"
},
{
"context": "wiki/Basic-Tutorial)\")\n\n(defcard-doc\n \"# Thanks\n\nJon Eisen\n\n**I'm a freelancer, Hire me!**\n\n- Twitter: @jm_e",
"end": 536,
"score": 0.9998745918273926,
"start": 527,
"tag": "NAME",
"value": "Jon Eisen"
},
{
"context": " Eisen\n\n**I'm a freelancer, Hire me!**\n\n- Twitter: @jm_eisen\n- Blog: http://joneisen.me\n- Email: jon@joneisen.",
"end": 590,
"score": 0.9992434978485107,
"start": 581,
"tag": "USERNAME",
"value": "@jm_eisen"
},
{
"context": "ter: @jm_eisen\n- Blog: http://joneisen.me\n- Email: jon@joneisen.works\")\n",
"end": 645,
"score": 0.9999182224273682,
"start": 627,
"tag": "EMAIL",
"value": "jon@joneisen.works"
}
] | src/cljs_demo/closing.cljs | yanatan16/talk-clojurescript-for-javascript-devs | 3 | (ns cljs-demo.closing
(:require [devcards.core :as dc :refer-macros [defcard-doc]]))
(defcard-doc
"## Resources
- [Clojurescript Quick Start](https://github.com/clojure/clojurescript/wiki/Quick-Start)
- [Modern Clojurescript Tutofrials](https://github.com/magomimmo/modern-cljs)
- [Clojure for the Brave and True: core.async](http://www.braveclojure.com/core-async/)
- [Reagent TodoMVC](http://todomvc.com/examples/reagent/)
- [Om Tutorial](https://github.com/omcljs/om/wiki/Basic-Tutorial)")
(defcard-doc
"# Thanks
Jon Eisen
**I'm a freelancer, Hire me!**
- Twitter: @jm_eisen
- Blog: http://joneisen.me
- Email: jon@joneisen.works")
| 96970 | (ns cljs-demo.closing
(:require [devcards.core :as dc :refer-macros [defcard-doc]]))
(defcard-doc
"## Resources
- [Clojurescript Quick Start](https://github.com/clojure/clojurescript/wiki/Quick-Start)
- [Modern Clojurescript Tutofrials](https://github.com/magomimmo/modern-cljs)
- [Clojure for the Brave and True: core.async](http://www.braveclojure.com/core-async/)
- [Reagent TodoMVC](http://todomvc.com/examples/reagent/)
- [Om Tutorial](https://github.com/omcljs/om/wiki/Basic-Tutorial)")
(defcard-doc
"# Thanks
<NAME>
**I'm a freelancer, Hire me!**
- Twitter: @jm_eisen
- Blog: http://joneisen.me
- Email: <EMAIL>")
| true | (ns cljs-demo.closing
(:require [devcards.core :as dc :refer-macros [defcard-doc]]))
(defcard-doc
"## Resources
- [Clojurescript Quick Start](https://github.com/clojure/clojurescript/wiki/Quick-Start)
- [Modern Clojurescript Tutofrials](https://github.com/magomimmo/modern-cljs)
- [Clojure for the Brave and True: core.async](http://www.braveclojure.com/core-async/)
- [Reagent TodoMVC](http://todomvc.com/examples/reagent/)
- [Om Tutorial](https://github.com/omcljs/om/wiki/Basic-Tutorial)")
(defcard-doc
"# Thanks
PI:NAME:<NAME>END_PI
**I'm a freelancer, Hire me!**
- Twitter: @jm_eisen
- Blog: http://joneisen.me
- Email: PI:EMAIL:<EMAIL>END_PI")
|
[
{
"context": " 12}\n (e/ui-field {:id \"ip1\" :placeholder \"First name\" :helper \"First name is required\"} \"\"))\n\n (l",
"end": 1260,
"score": 0.9362666606903076,
"start": 1250,
"tag": "NAME",
"value": "First name"
},
{
"context": "f}\n (e/ui-field {:id \"ip2\" :placeholder \"Last name\" :helper \"Last name is required\"} \"\")))\n\n (l",
"end": 1428,
"score": 0.9349128603935242,
"start": 1419,
"tag": "NAME",
"value": "Last name"
},
{
"context": " 12}\n (e/ui-field {:id \"ip1\" :placeholder \"First name\" :required true :helper \"First name is required\"}",
"end": 3161,
"score": 0.9073365330696106,
"start": 3151,
"tag": "NAME",
"value": "First name"
},
{
"context": "f}\n (e/ui-field {:id \"ip2\" :placeholder \"Last name\" :required true :helper \"Last name is required\" :",
"end": 3344,
"score": 0.8479017615318298,
"start": 3335,
"tag": "NAME",
"value": "Last name"
},
{
"context": "ired true :helper \"Last name is required\" :value \"Connors\"} \"\")))\n\n (l/col {:width 6}\n (l/ui-ve",
"end": 3408,
"score": 0.7530207633972168,
"start": 3401,
"tag": "NAME",
"value": "Connors"
}
] | src/css-guide/styles/patterns.cljs | AlloyCSS/untangled-components | 0 | (ns styles.patterns
(:require [om.next :as om :refer-macros [defui]]
[styles.util :as util :refer [to-cljs] :refer-macros [source->react defexample defarticle defview defviewport]]
[untangled.icons :as icons]
[untangled.ui.layout :as l]
[untangled.ui.elements :as e]
[om.dom :as dom]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; START OF EXAMPLES
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defarticle errors
"# Errors
## Errors occur when an app fails to complete an expected action.")
(defarticle errors-usage
"### Usage
### User input errors"
)
(defviewport errors-form
"A basic form"
(dom/span nil
(e/ui-toolbar {:kind :primary :raised true}
(e/ui-toolbar-row {}
"Application"
(e/ui-toolbar-spacer {})
(dom/span #js {:className "c-toolbar__actions"}
(e/ui-icon-button {:glyph :more_vert}))
(e/ui-toolbar-button {:glyph :arrow_back})))
(l/row {}
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Personal info")))
(l/col {:width 12}
(e/ui-field {:id "ip1" :placeholder "First name" :helper "First name is required"} ""))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip2" :placeholder "Last name" :helper "Last name is required"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip3" :placeholder "Birthday" :helper "MM/DD/YYYY" :pattern ".{10,}"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip4" :placeholder "Social Security" :helper "### - ## - ####"} "")))
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Residence address")))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip5" :placeholder "Address"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip6" :placeholder "City"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "State")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip7" :placeholder "Postal code"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "Country"))))))
(defviewport errors-form-filled
"Filled out form"
(dom/span nil
(e/ui-toolbar {:kind :primary :raised true}
(e/ui-toolbar-row {}
"Application"
(e/ui-toolbar-spacer {})
(dom/span #js {:className "c-toolbar__actions"}
(e/ui-icon-button {:glyph :more_vert}))
(e/ui-toolbar-button {:glyph :arrow_back})))
(l/row {}
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Personal info")))
(l/col {:width 12}
(e/ui-field {:id "ip1" :placeholder "First name" :required true :helper "First name is required"} ""))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip2" :placeholder "Last name" :required true :helper "Last name is required" :value "Connors"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip3" :placeholder "Birthday" :required true :helper "MM/DD/YYYY" :pattern ".{10,}" :value "01/01/90"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip4" :placeholder "Social Security" :required true :helper "### - ## - ####"} "")))
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Residence address")))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip5" :placeholder "Address" :value "2000 Main Street, Apartment J"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip6" :placeholder "City" :value "San Francisco"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "CA")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip7" :placeholder "Postal code" :value "94112"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "United States"))))))
(defexample empty-states
"# Empty States"
(dom/div #js {:style #js {:position "relative" :height "400px"}}
(dom/div #js {:className (str "u-absolute--middle-center")}
(dom/span #js {:className "c-icon c-icon--huge" :disabled true}
(icons/icon :widgets))
(dom/h1 #js {} "No widgets yet")
(dom/p #js {:className "c-message--neutral"} "Create a widget to get started"))))
(defexample pagination-dots
"# Pagination"
(let [current (om/get-state this :current)
selections ["1" "2" "3"]
]
(dom/div #js {:className "c-pagination-dots c-pagination-dots--move"}
(dom/ul nil
(map (fn [s]
(dom/li #js {:className (str "c-pagination-dots__dot" (when (= current s) " is-current"))
:key (str "dot-" s)}
(dom/span #js {:onClick #(om/update-state! this assoc :current s)} s))
) selections)
(dom/li nil "") ;; Dummy dot
)))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; START OF SECTIONS (within a feature set...e.g. components)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NOTE: This is where you add the sections for index
(def sections
(vec (sort-by :title
[
; NOTE: :examples is a list of example names, rendered in order given
{:id :postfixing
:title "Errors"
:examples [
errors
errors-usage
errors-form
errors-form-filled
]}
{:id :empty-states
:title "Empty states"
:examples [
empty-states
]}
{:id :pagination
:title "Pagination"
:examples [
pagination-dots
]}
])))
| 53093 | (ns styles.patterns
(:require [om.next :as om :refer-macros [defui]]
[styles.util :as util :refer [to-cljs] :refer-macros [source->react defexample defarticle defview defviewport]]
[untangled.icons :as icons]
[untangled.ui.layout :as l]
[untangled.ui.elements :as e]
[om.dom :as dom]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; START OF EXAMPLES
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defarticle errors
"# Errors
## Errors occur when an app fails to complete an expected action.")
(defarticle errors-usage
"### Usage
### User input errors"
)
(defviewport errors-form
"A basic form"
(dom/span nil
(e/ui-toolbar {:kind :primary :raised true}
(e/ui-toolbar-row {}
"Application"
(e/ui-toolbar-spacer {})
(dom/span #js {:className "c-toolbar__actions"}
(e/ui-icon-button {:glyph :more_vert}))
(e/ui-toolbar-button {:glyph :arrow_back})))
(l/row {}
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Personal info")))
(l/col {:width 12}
(e/ui-field {:id "ip1" :placeholder "<NAME>" :helper "First name is required"} ""))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip2" :placeholder "<NAME>" :helper "Last name is required"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip3" :placeholder "Birthday" :helper "MM/DD/YYYY" :pattern ".{10,}"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip4" :placeholder "Social Security" :helper "### - ## - ####"} "")))
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Residence address")))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip5" :placeholder "Address"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip6" :placeholder "City"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "State")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip7" :placeholder "Postal code"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "Country"))))))
(defviewport errors-form-filled
"Filled out form"
(dom/span nil
(e/ui-toolbar {:kind :primary :raised true}
(e/ui-toolbar-row {}
"Application"
(e/ui-toolbar-spacer {})
(dom/span #js {:className "c-toolbar__actions"}
(e/ui-icon-button {:glyph :more_vert}))
(e/ui-toolbar-button {:glyph :arrow_back})))
(l/row {}
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Personal info")))
(l/col {:width 12}
(e/ui-field {:id "ip1" :placeholder "<NAME>" :required true :helper "First name is required"} ""))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip2" :placeholder "<NAME>" :required true :helper "Last name is required" :value "<NAME>"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip3" :placeholder "Birthday" :required true :helper "MM/DD/YYYY" :pattern ".{10,}" :value "01/01/90"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip4" :placeholder "Social Security" :required true :helper "### - ## - ####"} "")))
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Residence address")))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip5" :placeholder "Address" :value "2000 Main Street, Apartment J"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip6" :placeholder "City" :value "San Francisco"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "CA")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip7" :placeholder "Postal code" :value "94112"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "United States"))))))
(defexample empty-states
"# Empty States"
(dom/div #js {:style #js {:position "relative" :height "400px"}}
(dom/div #js {:className (str "u-absolute--middle-center")}
(dom/span #js {:className "c-icon c-icon--huge" :disabled true}
(icons/icon :widgets))
(dom/h1 #js {} "No widgets yet")
(dom/p #js {:className "c-message--neutral"} "Create a widget to get started"))))
(defexample pagination-dots
"# Pagination"
(let [current (om/get-state this :current)
selections ["1" "2" "3"]
]
(dom/div #js {:className "c-pagination-dots c-pagination-dots--move"}
(dom/ul nil
(map (fn [s]
(dom/li #js {:className (str "c-pagination-dots__dot" (when (= current s) " is-current"))
:key (str "dot-" s)}
(dom/span #js {:onClick #(om/update-state! this assoc :current s)} s))
) selections)
(dom/li nil "") ;; Dummy dot
)))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; START OF SECTIONS (within a feature set...e.g. components)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NOTE: This is where you add the sections for index
(def sections
(vec (sort-by :title
[
; NOTE: :examples is a list of example names, rendered in order given
{:id :postfixing
:title "Errors"
:examples [
errors
errors-usage
errors-form
errors-form-filled
]}
{:id :empty-states
:title "Empty states"
:examples [
empty-states
]}
{:id :pagination
:title "Pagination"
:examples [
pagination-dots
]}
])))
| true | (ns styles.patterns
(:require [om.next :as om :refer-macros [defui]]
[styles.util :as util :refer [to-cljs] :refer-macros [source->react defexample defarticle defview defviewport]]
[untangled.icons :as icons]
[untangled.ui.layout :as l]
[untangled.ui.elements :as e]
[om.dom :as dom]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; START OF EXAMPLES
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defarticle errors
"# Errors
## Errors occur when an app fails to complete an expected action.")
(defarticle errors-usage
"### Usage
### User input errors"
)
(defviewport errors-form
"A basic form"
(dom/span nil
(e/ui-toolbar {:kind :primary :raised true}
(e/ui-toolbar-row {}
"Application"
(e/ui-toolbar-spacer {})
(dom/span #js {:className "c-toolbar__actions"}
(e/ui-icon-button {:glyph :more_vert}))
(e/ui-toolbar-button {:glyph :arrow_back})))
(l/row {}
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Personal info")))
(l/col {:width 12}
(e/ui-field {:id "ip1" :placeholder "PI:NAME:<NAME>END_PI" :helper "First name is required"} ""))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip2" :placeholder "PI:NAME:<NAME>END_PI" :helper "Last name is required"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip3" :placeholder "Birthday" :helper "MM/DD/YYYY" :pattern ".{10,}"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip4" :placeholder "Social Security" :helper "### - ## - ####"} "")))
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Residence address")))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip5" :placeholder "Address"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip6" :placeholder "City"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "State")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip7" :placeholder "Postal code"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "Country"))))))
(defviewport errors-form-filled
"Filled out form"
(dom/span nil
(e/ui-toolbar {:kind :primary :raised true}
(e/ui-toolbar-row {}
"Application"
(e/ui-toolbar-spacer {})
(dom/span #js {:className "c-toolbar__actions"}
(e/ui-icon-button {:glyph :more_vert}))
(e/ui-toolbar-button {:glyph :arrow_back})))
(l/row {}
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Personal info")))
(l/col {:width 12}
(e/ui-field {:id "ip1" :placeholder "PI:NAME:<NAME>END_PI" :required true :helper "First name is required"} ""))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip2" :placeholder "PI:NAME:<NAME>END_PI" :required true :helper "Last name is required" :value "PI:NAME:<NAME>END_PI"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip3" :placeholder "Birthday" :required true :helper "MM/DD/YYYY" :pattern ".{10,}" :value "01/01/90"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip4" :placeholder "Social Security" :required true :helper "### - ## - ####"} "")))
(l/col {:width 12}
(l/ui-vertical-margin {:before :half}
(dom/h1 nil "Residence address")))
(l/col {:width 12}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip5" :placeholder "Address" :value "2000 Main Street, Apartment J"} "")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip6" :placeholder "City" :value "San Francisco"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "CA")))
(l/col {:width 6}
(l/ui-vertical-margin {:after :half}
(e/ui-field {:id "ip7" :placeholder "Postal code" :value "94112"} "")))
(l/col {:width 6}
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button"} "United States"))))))
(defexample empty-states
"# Empty States"
(dom/div #js {:style #js {:position "relative" :height "400px"}}
(dom/div #js {:className (str "u-absolute--middle-center")}
(dom/span #js {:className "c-icon c-icon--huge" :disabled true}
(icons/icon :widgets))
(dom/h1 #js {} "No widgets yet")
(dom/p #js {:className "c-message--neutral"} "Create a widget to get started"))))
(defexample pagination-dots
"# Pagination"
(let [current (om/get-state this :current)
selections ["1" "2" "3"]
]
(dom/div #js {:className "c-pagination-dots c-pagination-dots--move"}
(dom/ul nil
(map (fn [s]
(dom/li #js {:className (str "c-pagination-dots__dot" (when (= current s) " is-current"))
:key (str "dot-" s)}
(dom/span #js {:onClick #(om/update-state! this assoc :current s)} s))
) selections)
(dom/li nil "") ;; Dummy dot
)))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; START OF SECTIONS (within a feature set...e.g. components)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NOTE: This is where you add the sections for index
(def sections
(vec (sort-by :title
[
; NOTE: :examples is a list of example names, rendered in order given
{:id :postfixing
:title "Errors"
:examples [
errors
errors-usage
errors-form
errors-form-filled
]}
{:id :empty-states
:title "Empty states"
:examples [
empty-states
]}
{:id :pagination
:title "Pagination"
:examples [
pagination-dots
]}
])))
|
[
{
"context": "\n\n(deftest dataxml-test\n (let [r {:id \"1\" :name \"Jan\" :lastname \"Abacki\"}\n s \"<?xml version=\\\"1",
"end": 245,
"score": 0.999284029006958,
"start": 242,
"tag": "NAME",
"value": "Jan"
},
{
"context": "ml-test\n (let [r {:id \"1\" :name \"Jan\" :lastname \"Abacki\"}\n s \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF",
"end": 264,
"score": 0.8971607089042664,
"start": 258,
"tag": "NAME",
"value": "Abacki"
},
{
"context": "=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><row id=\\\"1\\\" name=\\\"Jan\\\" lastname=\\\"Abacki\\\"></row>\"]\n (testing \"XML ",
"end": 344,
"score": 0.9948314428329468,
"start": 341,
"tag": "NAME",
"value": "Jan"
},
{
"context": "=\\\"UTF-8\\\"?><row id=\\\"1\\\" name=\\\"Jan\\\" lastname=\\\"Abacki\\\"></row>\"]\n (testing \"XML string creation\" (is",
"end": 364,
"score": 0.7522141933441162,
"start": 358,
"tag": "NAME",
"value": "Abacki"
},
{
"context": "deftest xml-test\n (let [r {:tag :Cell :content [\"Abacki\"]}\n s \"<Cell>\\nAbacki\\n</Cell>\\n\"]\n (te",
"end": 550,
"score": 0.6296696066856384,
"start": 544,
"tag": "NAME",
"value": "Abacki"
},
{
"context": "deftest agrest-test-map\n (let [r {:id \"1\" :name \"Jan\" :lastname \"Abacki\"}\n o {:tag :Row\n ",
"end": 756,
"score": 0.9995403289794922,
"start": 753,
"tag": "NAME",
"value": "Jan"
},
{
"context": "est-map\n (let [r {:id \"1\" :name \"Jan\" :lastname \"Abacki\"}\n o {:tag :Row\n :content [{:tag",
"end": 775,
"score": 0.8001017570495605,
"start": 769,
"tag": "NAME",
"value": "Abacki"
},
{
"context": " {:tag :Cell :content [{:tag :Data :content [\"Jan\"]}]}\n {:tag :Cell :content [{",
"end": 941,
"score": 0.9973686933517456,
"start": 938,
"tag": "NAME",
"value": "Jan"
},
{
"context": " {:tag :Cell :content [{:tag :Data :content [\"Abacki\"]}]}]}]\n (testing \"map for office creation\" (i",
"end": 1019,
"score": 0.8627633452415466,
"start": 1013,
"tag": "NAME",
"value": "Abacki"
},
{
"context": " {:tag :Cell :content [{:tag :Data :content [\"Jan\"]}]}\n {:tag :Cell :content [{",
"end": 1305,
"score": 0.9980496764183044,
"start": 1302,
"tag": "NAME",
"value": "Jan"
},
{
"context": " {:tag :Cell :content [{:tag :Data :content [\"Abacki\"]}]}]}\n x (str \"<Row>\\n<Cell>\\n<Data>\\n1\\n",
"end": 1383,
"score": 0.9408068060874939,
"start": 1377,
"tag": "NAME",
"value": "Abacki"
}
] | src/test/clojure/pl/tomaszgigiel/agrest/xml_test.clj | tomaszgigiel/agrest | 0 | (ns pl.tomaszgigiel.agrest.xml-test
(:use [clojure.test])
(:require [clojure.data.xml :as dataxml])
(:require [clojure.xml :as xml])
(:require [pl.tomaszgigiel.agrest.xml :as agrest]))
(deftest dataxml-test
(let [r {:id "1" :name "Jan" :lastname "Abacki"}
s "<?xml version=\"1.0\" encoding=\"UTF-8\"?><row id=\"1\" name=\"Jan\" lastname=\"Abacki\"></row>"]
(testing "XML string creation" (is (= s (dataxml/emit-str (dataxml/element :row r))) "Expected string XML."))))
(deftest xml-test
(let [r {:tag :Cell :content ["Abacki"]}
s "<Cell>\nAbacki\n</Cell>\n"]
(testing "XML string creation" (is (= s (with-out-str (xml/emit-element r)))) "Expected string XML.")))
(deftest agrest-test-map
(let [r {:id "1" :name "Jan" :lastname "Abacki"}
o {:tag :Row
:content [{:tag :Cell :content [{:tag :Data :content ["1"]}]}
{:tag :Cell :content [{:tag :Data :content ["Jan"]}]}
{:tag :Cell :content [{:tag :Data :content ["Abacki"]}]}]}]
(testing "map for office creation" (is (= o (agrest/recordset-to-office-map r))))))
(deftest agrest-test-xml
(let [r {:tag :Row
:content [{:tag :Cell :content [{:tag :Data :content ["1"]}]}
{:tag :Cell :content [{:tag :Data :content ["Jan"]}]}
{:tag :Cell :content [{:tag :Data :content ["Abacki"]}]}]}
x (str "<Row>\n<Cell>\n<Data>\n1\n</Data>\n</Cell>\n<Cell>\n<Data>\nJan\n</Data>\n</Cell>\n<Cell>\n<Data>\nAbacki\n</Data>\n</Cell>\n</Row>\n")]
(testing "office xml creation" (is (= x (agrest/office-map-to-xml r))))))
(deftest agrest-test-flatten-xml
(let [a "<Row>\n<Cell>\n<Data>\n1\n</Data>\n</Cell>\n<Cell>\n<Data>\nJan\n</Data>\n</Cell>\n<Cell>\n<Data>\nAbacki\n</Data>\n</Cell>\n</Row>\n"
b "<Row><Cell><Data>1</Data></Cell><Cell><Data>Jan</Data></Cell><Cell><Data>Abacki</Data></Cell></Row>"]
(testing "office xml creation" (is (= b (agrest/flatten-xml a))))))
| 53049 | (ns pl.tomaszgigiel.agrest.xml-test
(:use [clojure.test])
(:require [clojure.data.xml :as dataxml])
(:require [clojure.xml :as xml])
(:require [pl.tomaszgigiel.agrest.xml :as agrest]))
(deftest dataxml-test
(let [r {:id "1" :name "<NAME>" :lastname "<NAME>"}
s "<?xml version=\"1.0\" encoding=\"UTF-8\"?><row id=\"1\" name=\"<NAME>\" lastname=\"<NAME>\"></row>"]
(testing "XML string creation" (is (= s (dataxml/emit-str (dataxml/element :row r))) "Expected string XML."))))
(deftest xml-test
(let [r {:tag :Cell :content ["<NAME>"]}
s "<Cell>\nAbacki\n</Cell>\n"]
(testing "XML string creation" (is (= s (with-out-str (xml/emit-element r)))) "Expected string XML.")))
(deftest agrest-test-map
(let [r {:id "1" :name "<NAME>" :lastname "<NAME>"}
o {:tag :Row
:content [{:tag :Cell :content [{:tag :Data :content ["1"]}]}
{:tag :Cell :content [{:tag :Data :content ["<NAME>"]}]}
{:tag :Cell :content [{:tag :Data :content ["<NAME>"]}]}]}]
(testing "map for office creation" (is (= o (agrest/recordset-to-office-map r))))))
(deftest agrest-test-xml
(let [r {:tag :Row
:content [{:tag :Cell :content [{:tag :Data :content ["1"]}]}
{:tag :Cell :content [{:tag :Data :content ["<NAME>"]}]}
{:tag :Cell :content [{:tag :Data :content ["<NAME>"]}]}]}
x (str "<Row>\n<Cell>\n<Data>\n1\n</Data>\n</Cell>\n<Cell>\n<Data>\nJan\n</Data>\n</Cell>\n<Cell>\n<Data>\nAbacki\n</Data>\n</Cell>\n</Row>\n")]
(testing "office xml creation" (is (= x (agrest/office-map-to-xml r))))))
(deftest agrest-test-flatten-xml
(let [a "<Row>\n<Cell>\n<Data>\n1\n</Data>\n</Cell>\n<Cell>\n<Data>\nJan\n</Data>\n</Cell>\n<Cell>\n<Data>\nAbacki\n</Data>\n</Cell>\n</Row>\n"
b "<Row><Cell><Data>1</Data></Cell><Cell><Data>Jan</Data></Cell><Cell><Data>Abacki</Data></Cell></Row>"]
(testing "office xml creation" (is (= b (agrest/flatten-xml a))))))
| true | (ns pl.tomaszgigiel.agrest.xml-test
(:use [clojure.test])
(:require [clojure.data.xml :as dataxml])
(:require [clojure.xml :as xml])
(:require [pl.tomaszgigiel.agrest.xml :as agrest]))
(deftest dataxml-test
(let [r {:id "1" :name "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI"}
s "<?xml version=\"1.0\" encoding=\"UTF-8\"?><row id=\"1\" name=\"PI:NAME:<NAME>END_PI\" lastname=\"PI:NAME:<NAME>END_PI\"></row>"]
(testing "XML string creation" (is (= s (dataxml/emit-str (dataxml/element :row r))) "Expected string XML."))))
(deftest xml-test
(let [r {:tag :Cell :content ["PI:NAME:<NAME>END_PI"]}
s "<Cell>\nAbacki\n</Cell>\n"]
(testing "XML string creation" (is (= s (with-out-str (xml/emit-element r)))) "Expected string XML.")))
(deftest agrest-test-map
(let [r {:id "1" :name "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI"}
o {:tag :Row
:content [{:tag :Cell :content [{:tag :Data :content ["1"]}]}
{:tag :Cell :content [{:tag :Data :content ["PI:NAME:<NAME>END_PI"]}]}
{:tag :Cell :content [{:tag :Data :content ["PI:NAME:<NAME>END_PI"]}]}]}]
(testing "map for office creation" (is (= o (agrest/recordset-to-office-map r))))))
(deftest agrest-test-xml
(let [r {:tag :Row
:content [{:tag :Cell :content [{:tag :Data :content ["1"]}]}
{:tag :Cell :content [{:tag :Data :content ["PI:NAME:<NAME>END_PI"]}]}
{:tag :Cell :content [{:tag :Data :content ["PI:NAME:<NAME>END_PI"]}]}]}
x (str "<Row>\n<Cell>\n<Data>\n1\n</Data>\n</Cell>\n<Cell>\n<Data>\nJan\n</Data>\n</Cell>\n<Cell>\n<Data>\nAbacki\n</Data>\n</Cell>\n</Row>\n")]
(testing "office xml creation" (is (= x (agrest/office-map-to-xml r))))))
(deftest agrest-test-flatten-xml
(let [a "<Row>\n<Cell>\n<Data>\n1\n</Data>\n</Cell>\n<Cell>\n<Data>\nJan\n</Data>\n</Cell>\n<Cell>\n<Data>\nAbacki\n</Data>\n</Cell>\n</Row>\n"
b "<Row><Cell><Data>1</Data></Cell><Cell><Data>Jan</Data></Cell><Cell><Data>Abacki</Data></Cell></Row>"]
(testing "office xml creation" (is (= b (agrest/flatten-xml a))))))
|
[
{
"context": ";; Copyright (c) Andrew A. Raines\n;;\n;; Permission is hereby granted, free of charg",
"end": 33,
"score": 0.9998827576637268,
"start": 17,
"tag": "NAME",
"value": "Andrew A. Raines"
},
{
"context": "reload))\n\n(defn props [attrs]\n (let [msg {:from \"foo@bar.dom\"\n :to \"baz@bar.dom\"\n :sub",
"end": 1261,
"score": 0.9998882412910461,
"start": 1250,
"tag": "EMAIL",
"value": "foo@bar.dom"
},
{
"context": " (let [msg {:from \"foo@bar.dom\"\n :to \"baz@bar.dom\"\n :subject \"Test\"\n :body ",
"end": 1292,
"score": 0.9998916387557983,
"start": 1281,
"tag": "EMAIL",
"value": "baz@bar.dom"
},
{
"context": "dom\"\n :user \"foo\"\n :pass \"pass\"}\n {\"mail.smtp.user\" \"foo\"\n ",
"end": 1936,
"score": 0.998440146446228,
"start": 1932,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "dom\"\n :user \"foo\"\n :pass \"pass\"\n :tls :y}\n {\"mail.smtp.us",
"end": 2330,
"score": 0.9994224309921265,
"start": 2326,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "dom\"\n :user \"foo\"\n :pass \"pass\"\n :ssl :y}\n {\"mail.smtp.us",
"end": 2842,
"score": 0.9994446039199829,
"start": 2838,
"tag": "PASSWORD",
"value": "pass"
}
] | test/postal/test/smtp.clj | poenneby/postal | 371 | ;; Copyright (c) Andrew A. Raines
;;
;; 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 postal.test.smtp
(:use [clojure.test])
(:require [postal.smtp :as smtp] :reload))
(defn props [attrs]
(let [msg {:from "foo@bar.dom"
:to "baz@bar.dom"
:subject "Test"
:body "Hello."}]
(binding [smtp/smtp-send* (fn [^javax.mail.Session session & _] (into {} (.getProperties session)))]
(smtp/smtp-send attrs [msg]))))
(defmacro is-props [input want]
`(is (= (props ~input) ~want)))
(deftest t-props
(is-props {:host "smtp.bar.dom"}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user "foo"
:pass "pass"}
{"mail.smtp.user" "foo"
"mail.smtp.port" 25
"mail.smtp.auth" "true"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.user" "foo"
"mail.smtps.port" 25
"mail.smtps.auth" "true"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user "foo"
:pass "pass"
:tls :y}
{"mail.smtp.user" "foo"
"mail.smtp.port" 25
"mail.smtp.auth" "true"
"mail.smtp.starttls.enable" "true"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.user" "foo"
"mail.smtps.port" 25
"mail.smtps.auth" "true"
"mail.smtps.starttls.enable" "true"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user "foo"
:pass "pass"
:ssl :y}
{"mail.smtp.user" "foo"
"mail.smtp.port" 465
"mail.smtp.auth" "true"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.user" "foo"
"mail.smtps.port" 465
"mail.smtps.auth" "true"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user nil
:pass nil}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:localaddress "1.2.3.4"
:localhost "mail.bar.dom"}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtp.localaddress" "1.2.3.4"
"mail.smtp.localhost" "mail.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"
"mail.smtps.localaddress" "1.2.3.4"
"mail.smtps.localhost" "mail.bar.dom"})
(is-props {:host "smtp.bar.dom"
"mail.smtp.localaddress" "1.2.3.4"
"mail.smtp.localhost" "mail.bar.dom"}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"
"mail.smtp.localaddress" "1.2.3.4"
"mail.smtp.localhost" "mail.bar.dom"}))
| 43969 | ;; Copyright (c) <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 postal.test.smtp
(:use [clojure.test])
(:require [postal.smtp :as smtp] :reload))
(defn props [attrs]
(let [msg {:from "<EMAIL>"
:to "<EMAIL>"
:subject "Test"
:body "Hello."}]
(binding [smtp/smtp-send* (fn [^javax.mail.Session session & _] (into {} (.getProperties session)))]
(smtp/smtp-send attrs [msg]))))
(defmacro is-props [input want]
`(is (= (props ~input) ~want)))
(deftest t-props
(is-props {:host "smtp.bar.dom"}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user "foo"
:pass "<PASSWORD>"}
{"mail.smtp.user" "foo"
"mail.smtp.port" 25
"mail.smtp.auth" "true"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.user" "foo"
"mail.smtps.port" 25
"mail.smtps.auth" "true"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user "foo"
:pass "<PASSWORD>"
:tls :y}
{"mail.smtp.user" "foo"
"mail.smtp.port" 25
"mail.smtp.auth" "true"
"mail.smtp.starttls.enable" "true"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.user" "foo"
"mail.smtps.port" 25
"mail.smtps.auth" "true"
"mail.smtps.starttls.enable" "true"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user "foo"
:pass "<PASSWORD>"
:ssl :y}
{"mail.smtp.user" "foo"
"mail.smtp.port" 465
"mail.smtp.auth" "true"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.user" "foo"
"mail.smtps.port" 465
"mail.smtps.auth" "true"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user nil
:pass nil}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:localaddress "1.2.3.4"
:localhost "mail.bar.dom"}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtp.localaddress" "1.2.3.4"
"mail.smtp.localhost" "mail.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"
"mail.smtps.localaddress" "1.2.3.4"
"mail.smtps.localhost" "mail.bar.dom"})
(is-props {:host "smtp.bar.dom"
"mail.smtp.localaddress" "1.2.3.4"
"mail.smtp.localhost" "mail.bar.dom"}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"
"mail.smtp.localaddress" "1.2.3.4"
"mail.smtp.localhost" "mail.bar.dom"}))
| true | ;; Copyright (c) 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 postal.test.smtp
(:use [clojure.test])
(:require [postal.smtp :as smtp] :reload))
(defn props [attrs]
(let [msg {:from "PI:EMAIL:<EMAIL>END_PI"
:to "PI:EMAIL:<EMAIL>END_PI"
:subject "Test"
:body "Hello."}]
(binding [smtp/smtp-send* (fn [^javax.mail.Session session & _] (into {} (.getProperties session)))]
(smtp/smtp-send attrs [msg]))))
(defmacro is-props [input want]
`(is (= (props ~input) ~want)))
(deftest t-props
(is-props {:host "smtp.bar.dom"}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user "foo"
:pass "PI:PASSWORD:<PASSWORD>END_PI"}
{"mail.smtp.user" "foo"
"mail.smtp.port" 25
"mail.smtp.auth" "true"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.user" "foo"
"mail.smtps.port" 25
"mail.smtps.auth" "true"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user "foo"
:pass "PI:PASSWORD:<PASSWORD>END_PI"
:tls :y}
{"mail.smtp.user" "foo"
"mail.smtp.port" 25
"mail.smtp.auth" "true"
"mail.smtp.starttls.enable" "true"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.user" "foo"
"mail.smtps.port" 25
"mail.smtps.auth" "true"
"mail.smtps.starttls.enable" "true"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user "foo"
:pass "PI:PASSWORD:<PASSWORD>END_PI"
:ssl :y}
{"mail.smtp.user" "foo"
"mail.smtp.port" 465
"mail.smtp.auth" "true"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.user" "foo"
"mail.smtps.port" 465
"mail.smtps.auth" "true"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:user nil
:pass nil}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"})
(is-props {:host "smtp.bar.dom"
:localaddress "1.2.3.4"
:localhost "mail.bar.dom"}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtp.localaddress" "1.2.3.4"
"mail.smtp.localhost" "mail.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"
"mail.smtps.localaddress" "1.2.3.4"
"mail.smtps.localhost" "mail.bar.dom"})
(is-props {:host "smtp.bar.dom"
"mail.smtp.localaddress" "1.2.3.4"
"mail.smtp.localhost" "mail.bar.dom"}
{"mail.smtp.port" 25
"mail.smtp.auth" "false"
"mail.smtp.host" "smtp.bar.dom"
"mail.smtps.port" 25
"mail.smtps.auth" "false"
"mail.smtps.host" "smtp.bar.dom"
"mail.smtp.localaddress" "1.2.3.4"
"mail.smtp.localhost" "mail.bar.dom"}))
|
[
{
"context": "erson-or-dog-schema)\n data #:person{:name \"Apollo\" :age 30}\n bad-data #:person{:name \"Apollo",
"end": 1741,
"score": 0.9997997283935547,
"start": 1735,
"tag": "NAME",
"value": "Apollo"
},
{
"context": "Apollo\" :age 30}\n bad-data #:person{:name \"Apollo\" :age \"not an integer\"}]\n (is (= nil (s/check ",
"end": 1791,
"score": 0.9997847080230713,
"start": 1785,
"tag": "NAME",
"value": "Apollo"
},
{
"context": "lt/rec-w-maybe-field-schema)\n data {:name \"Boomer\"}]\n (is (= nil (s/check ps data)))))\n\n(deftest",
"end": 2032,
"score": 0.7891597747802734,
"start": 2026,
"tag": "NAME",
"value": "Boomer"
},
{
"context": "lt/rec-w-maybe-field-schema)\n data {:name \"Boomer\"\n :age nil}]\n (is (= nil (s/check",
"end": 2199,
"score": 0.9871299862861633,
"start": 2193,
"tag": "NAME",
"value": "Boomer"
}
] | test/deercreeklabs/unit/plumatic_test.cljc | GriffinScribe-LLC/lancaster | 42 | (ns deercreeklabs.unit.plumatic-test
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is use-fixtures]]
[deercreeklabs.baracus :as ba]
[deercreeklabs.lancaster :as l]
[deercreeklabs.lancaster.utils :as u]
[deercreeklabs.unit.lancaster-test :as lt]
[schema.core :as s :include-macros true])
#?(:clj
(:import
(clojure.lang ExceptionInfo))))
(deftest test-plumatic-primitives
(is (= u/Nil (l/plumatic-schema l/null-schema)))
(is (= s/Bool (l/plumatic-schema l/boolean-schema)))
(is (= s/Int (l/plumatic-schema l/int-schema)))
(is (= u/LongOrInt (l/plumatic-schema l/long-schema)))
(is (= s/Num (l/plumatic-schema l/float-schema)))
(is (= s/Num (l/plumatic-schema l/double-schema)))
(is (= u/StringOrBytes (l/plumatic-schema l/string-schema)))
(is (= u/StringOrBytes (l/plumatic-schema l/bytes-schema))))
(deftest test-plumatic-records
(is (= nil (s/check (l/plumatic-schema lt/add-to-cart-req-schema)
{:sku 1})))
(is (not= nil (s/check (l/plumatic-schema lt/add-to-cart-req-schema)
{})))
(is (= nil (s/check (l/plumatic-schema lt/rec-w-array-and-enum-schema)
{:names []})))
(is (= nil (s/check (l/plumatic-schema lt/rec-w-array-and-enum-schema)
{:names []}))))
(deftest test-plumatic-union
(let [expected (s/conditional
int? s/Int
map? (l/plumatic-schema lt/add-to-cart-req-schema)
u/valid-bytes-or-string? u/StringOrBytes)]
(is (= expected (l/plumatic-schema lt/union-schema)))))
(deftest test-plumatic-union-mult-rec
(let [pl-sch (l/plumatic-schema lt/person-or-dog-schema)
data #:person{:name "Apollo" :age 30}
bad-data #:person{:name "Apollo" :age "not an integer"}]
(is (= nil (s/check pl-sch data)))
(is (not= nil (s/check pl-sch bad-data)))))
(deftest test-plumatic-maybe-missing-key
(let [ps (l/plumatic-schema lt/rec-w-maybe-field-schema)
data {:name "Boomer"}]
(is (= nil (s/check ps data)))))
(deftest test-plumatic-maybe-nil-value
(let [ps (l/plumatic-schema lt/rec-w-maybe-field-schema)
data {:name "Boomer"
:age nil}]
(is (= nil (s/check ps data)))))
| 56355 | (ns deercreeklabs.unit.plumatic-test
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is use-fixtures]]
[deercreeklabs.baracus :as ba]
[deercreeklabs.lancaster :as l]
[deercreeklabs.lancaster.utils :as u]
[deercreeklabs.unit.lancaster-test :as lt]
[schema.core :as s :include-macros true])
#?(:clj
(:import
(clojure.lang ExceptionInfo))))
(deftest test-plumatic-primitives
(is (= u/Nil (l/plumatic-schema l/null-schema)))
(is (= s/Bool (l/plumatic-schema l/boolean-schema)))
(is (= s/Int (l/plumatic-schema l/int-schema)))
(is (= u/LongOrInt (l/plumatic-schema l/long-schema)))
(is (= s/Num (l/plumatic-schema l/float-schema)))
(is (= s/Num (l/plumatic-schema l/double-schema)))
(is (= u/StringOrBytes (l/plumatic-schema l/string-schema)))
(is (= u/StringOrBytes (l/plumatic-schema l/bytes-schema))))
(deftest test-plumatic-records
(is (= nil (s/check (l/plumatic-schema lt/add-to-cart-req-schema)
{:sku 1})))
(is (not= nil (s/check (l/plumatic-schema lt/add-to-cart-req-schema)
{})))
(is (= nil (s/check (l/plumatic-schema lt/rec-w-array-and-enum-schema)
{:names []})))
(is (= nil (s/check (l/plumatic-schema lt/rec-w-array-and-enum-schema)
{:names []}))))
(deftest test-plumatic-union
(let [expected (s/conditional
int? s/Int
map? (l/plumatic-schema lt/add-to-cart-req-schema)
u/valid-bytes-or-string? u/StringOrBytes)]
(is (= expected (l/plumatic-schema lt/union-schema)))))
(deftest test-plumatic-union-mult-rec
(let [pl-sch (l/plumatic-schema lt/person-or-dog-schema)
data #:person{:name "<NAME>" :age 30}
bad-data #:person{:name "<NAME>" :age "not an integer"}]
(is (= nil (s/check pl-sch data)))
(is (not= nil (s/check pl-sch bad-data)))))
(deftest test-plumatic-maybe-missing-key
(let [ps (l/plumatic-schema lt/rec-w-maybe-field-schema)
data {:name "<NAME>"}]
(is (= nil (s/check ps data)))))
(deftest test-plumatic-maybe-nil-value
(let [ps (l/plumatic-schema lt/rec-w-maybe-field-schema)
data {:name "<NAME>"
:age nil}]
(is (= nil (s/check ps data)))))
| true | (ns deercreeklabs.unit.plumatic-test
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is use-fixtures]]
[deercreeklabs.baracus :as ba]
[deercreeklabs.lancaster :as l]
[deercreeklabs.lancaster.utils :as u]
[deercreeklabs.unit.lancaster-test :as lt]
[schema.core :as s :include-macros true])
#?(:clj
(:import
(clojure.lang ExceptionInfo))))
(deftest test-plumatic-primitives
(is (= u/Nil (l/plumatic-schema l/null-schema)))
(is (= s/Bool (l/plumatic-schema l/boolean-schema)))
(is (= s/Int (l/plumatic-schema l/int-schema)))
(is (= u/LongOrInt (l/plumatic-schema l/long-schema)))
(is (= s/Num (l/plumatic-schema l/float-schema)))
(is (= s/Num (l/plumatic-schema l/double-schema)))
(is (= u/StringOrBytes (l/plumatic-schema l/string-schema)))
(is (= u/StringOrBytes (l/plumatic-schema l/bytes-schema))))
(deftest test-plumatic-records
(is (= nil (s/check (l/plumatic-schema lt/add-to-cart-req-schema)
{:sku 1})))
(is (not= nil (s/check (l/plumatic-schema lt/add-to-cart-req-schema)
{})))
(is (= nil (s/check (l/plumatic-schema lt/rec-w-array-and-enum-schema)
{:names []})))
(is (= nil (s/check (l/plumatic-schema lt/rec-w-array-and-enum-schema)
{:names []}))))
(deftest test-plumatic-union
(let [expected (s/conditional
int? s/Int
map? (l/plumatic-schema lt/add-to-cart-req-schema)
u/valid-bytes-or-string? u/StringOrBytes)]
(is (= expected (l/plumatic-schema lt/union-schema)))))
(deftest test-plumatic-union-mult-rec
(let [pl-sch (l/plumatic-schema lt/person-or-dog-schema)
data #:person{:name "PI:NAME:<NAME>END_PI" :age 30}
bad-data #:person{:name "PI:NAME:<NAME>END_PI" :age "not an integer"}]
(is (= nil (s/check pl-sch data)))
(is (not= nil (s/check pl-sch bad-data)))))
(deftest test-plumatic-maybe-missing-key
(let [ps (l/plumatic-schema lt/rec-w-maybe-field-schema)
data {:name "PI:NAME:<NAME>END_PI"}]
(is (= nil (s/check ps data)))))
(deftest test-plumatic-maybe-nil-value
(let [ps (l/plumatic-schema lt/rec-w-maybe-field-schema)
data {:name "PI:NAME:<NAME>END_PI"
:age nil}]
(is (= nil (s/check ps data)))))
|
[
{
"context": " 17)\n 1. SizeInBytes => int16\n 2. api_key => INT16 (0) 17\n 3. api_version => INT16 (0)\n ",
"end": 6610,
"score": 0.95729660987854,
"start": 6605,
"tag": "KEY",
"value": "INT16"
},
{
"context": "izeInBytes => int16\n 2. api_key => INT16 (0) 17\n 3. api_version => INT16 (0)\n 4. cor",
"end": 6619,
"score": 0.6014618277549744,
"start": 6617,
"tag": "KEY",
"value": "0)"
},
{
"context": "ytes => int16\n 2. api_key => INT16 (0) 17\n 3. api_version => INT16 (0)\n 4. correlati",
"end": 6625,
"score": 0.9432206749916077,
"start": 6623,
"tag": "KEY",
"value": "17"
}
] | kafka-clj/src/kafka_clj/jaas.clj | gerritjvv/kafka-fast | 152 | (ns
^{:doc "USAGE:
Use for JAAS Kerberos Plain Text
(def tcp-client (... create tcp client ...)
(def c (jaas/jaas-login \"KafkaClient\"))
(def sasl-client (jaas/sasl-client c (jaas/principal-name c) broker-host))
(jaas/sasl-handshake! tcp-client sasl-client timeout-ms)
System environment config must be set, see the project.clj file for this project.
Properties required are:
-Djava.security.auth.login.config=/vagrant/vagrant/config/kafka_client_jaas.conf
-Djava.security.krb5.conf=/vagrant/vagrant/config/krb5.conf
"}
kafka-clj.jaas
(:import (javax.security.auth.login LoginContext)
(javax.security.auth Subject)
(java.security PrivilegedExceptionAction Principal)
(javax.security.sasl Sasl SaslClient)
(javax.security.auth.callback CallbackHandler)
(java.util.concurrent TimeoutException)
(io.netty.buffer ByteBuf Unpooled)
(javax.security.auth.kerberos KerberosTicket)
(java.io InputStream ByteArrayInputStream ByteArrayOutputStream)
(sun.misc HexDumpEncoder)
(kafka_clj.util Util))
(:require [clojure.tools.logging :refer [info error debug]]
[kafka-clj.tcp-api :as tcp-api]
[kafka-clj.protocol :as protocol]
[tcp-driver.driver :as tcp-driver]
[tcp-driver.io.stream :as tcp-stream]
[kafka-clj.buff-utils :as buff-utils]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;; helper functions
(defonce ^:constant MECHS (into-array String ["GSSAPI"]))
(defonce ^:constant ^Long HALF-MINUTE-MS (* 30 1000))
(defn timeout? [timeout-ms current-ms]
(> (- (System/currentTimeMillis) (long current-ms)) (long timeout-ms)))
(defn with-auth [^LoginContext ctx f]
(Subject/doAs ^Subject (.getSubject ctx)
(reify PrivilegedExceptionAction
(run [_]
(f)))))
(defn readp-resp [conn timeout-ms]
(let [len (tcp-stream/read-int conn timeout-ms)]
(tcp-stream/read-bytes conn len timeout-ms)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; public functions
(defn kafka-service-name
"Search for sasl.kerberos.service.name is defined in either conf, System.properties its used,
otherwise the default kafka name is used"
[conf]
(or
(:sasl.kerberos.service.name conf)
(System/getProperty "sasl.kerberos.service.name")
"kafka"))
(defn jaas-login ^LoginContext
[jaas-name]
(debug "trying jaas login for name " jaas-name)
(let [login (LoginContext. (str jaas-name))]
(.login login)
(debug "login complete: have " login)
login))
(defn jaas-expire-time
"For all KerberosTicket(s) in the LoginContext the min auth time value is returned"
[^LoginContext ctx]
(let [^Subject subject (.getSubject ctx)]
(if subject
(apply
min
(map
#(.getTime (.getEndTime ^KerberosTicket %))
(.getPrivateCredentials subject KerberosTicket)))
Long/MAX_VALUE)))
(defn jaas-expired?
"True if the expire time is withing 30 seconds of the current time"
[^LoginContext ctx]
(debug "jaas-expired: expire-time " (long (jaas-expire-time ctx)) " curr-time " (System/currentTimeMillis))
(<
(- (long (jaas-expire-time ctx))
(System/currentTimeMillis))
HALF-MINUTE-MS))
(defn jaas-logout [^LoginContext ctx]
(.logout ctx))
(defn ^Principal principal-name
"Return the unparsed principal name e.g kafka/broker1.kafkafast@KAFKAFAST
A context can have multiple principals, this method returns the first principal found"
[^LoginContext ctx]
(.getName ^Principal (first (.getPrincipals ^Subject (.getSubject ctx)))))
;;with auth
(defn ^SaslClient sasl-client
"See https://docs.oracle.com/javase/8/docs/api/javax/security/sasl/Sasl.html
servicePrincipal: should be in the format kafka/{host} see kafka-principal-name
host: the kafka broker"
[conf ^LoginContext ctx host]
(let []
(with-auth ctx (fn []
(Sasl/createSaslClient MECHS
(principal-name ctx)
(str (kafka-service-name conf)) ;;the sasl client will construct kafka/{host}@{REALM}
(str host)
{}
(reify CallbackHandler
(handle [_ callbacks]
(debug "Callback " callbacks))))))))
(defn as-hex [^"[B" bts]
(when bts
(let [cnt (Math/min (int 16) (int (count bts)))
arr-out (ByteArrayOutputStream.)
bts-in (ByteArrayInputStream. bts (int 0) (int cnt))]
(.encodeBuffer (HexDumpEncoder.) bts-in arr-out)
(.toString arr-out))))
(defn send-read-data
"Write [int size][client-resp] then read [int size][server resp]"
[conn ^"[B" client-resp should-read timeout-ms]
(debug "gssapi send to broker : " (as-hex client-resp))
(tcp-stream/write-int conn (count client-resp))
(tcp-stream/write-bytes conn client-resp)
(tcp-stream/flush-out conn)
(when should-read
(let [resp (readp-resp conn timeout-ms)]
(debug "gssapi read from broker : " (as-hex resp))
resp)))
(defn handshake-loop! [conn ^SaslClient sasl-client timeout-ms]
{:pre [conn sasl-client (number? timeout-ms)]}
(let [current-ms (System/currentTimeMillis)]
(loop [server-resp (byte-array []) initial true]
(cond
(timeout? timeout-ms current-ms) (throw (TimeoutException. (str "Could not handshake with sasl client " sasl-client " in " timeout-ms "ms")))
(.isComplete sasl-client) true
:else (let [client-resp (if (and
initial
(not (.hasInitialResponse sasl-client)))
(byte-array []) ;;send initial empty byte array token
(.evaluateChallenge sasl-client server-resp)) ;otherwise eval and send response back
]
(if client-resp ;;if any client-resp data, send, but only if sasl-client is not complete
(recur (send-read-data conn client-resp (not (.isComplete sasl-client)) timeout-ms) false)
(recur server-resp false)))))))
(defn handshake-request!
"
SaslHandshake API (Key: 17)
1. SizeInBytes => int16
2. api_key => INT16 (0) 17
3. api_version => INT16 (0)
4. correlation_id => INT32
5. client_id => NULLABLE_STRING
6. mechanism => String \"GSSAPI\" or \"PLAIN\";
"
[conn]
(let [corr-id (protocol/unique-corrid!)
buff (Unpooled/buffer)
_ (do
(buff-utils/with-size buff
(fn [^ByteBuf buff]
(.writeShort buff (short protocol/API_KEY_SASL_HANDSHAKE))
(.writeShort buff (short protocol/API_VERSION))
(.writeInt buff (int corr-id))
(buff-utils/write-short-string buff nil)
(buff-utils/write-short-string buff (str (first MECHS))))))]
(info "Write request: " (short protocol/API_KEY_SASL_HANDSHAKE)
" version " (int protocol/API_VERSION)
" mechs " (str (first MECHS))
" corr-id " corr-id)
(tcp-stream/write-bytes conn (Util/toBytes ^ByteBuf buff))
(tcp-stream/flush-out conn)))
(defn handshake-response!
";Response:
1. SizeInBytes => int16
2. correlation_id => INT32
3. error_code => INT16
0 => None, 34 => InvalidSaslState, 35 => UnsupportedVersion
4. enabled_mechanisms => [STRING]"
[conn timeout-ms]
(let [len (tcp-stream/read-int conn timeout-ms)
^ByteBuf buff (Unpooled/wrappedBuffer ^"[B" (tcp-stream/read-bytes conn len timeout-ms))
corr-id (.readInt buff)
error-code (.readShort buff)
mechs (buff-utils/read-string-array buff)]
(info "handshake-response: error-code: " error-code " mechs " mechs " corr-id " corr-id)
(if (zero? error-code)
true
(throw (RuntimeException. (str "Handshake error: " error-code " mechanims: " mechs))))))
(defn sasl-handshake!
"client: kafka-clj/tcp client
sasl-client: jaas/sasl-client
timeout-ms: timeout in milliseconds"
[conn ^SaslClient sasl-client timeout-ms & {:keys [kafka-version] :or {kafka-version "0.10.0"}}]
(debug "sasl-handshake!: >>>>>>>>>>>>>>>>>>>>>>>>kafka-version: " kafka-version)
(when (not (.contains (str kafka-version) "0.9"))
(handshake-request! conn)
(handshake-response! conn timeout-ms))
;;no exception means handshake is complete
(handshake-loop! conn sasl-client timeout-ms))
| 21975 | (ns
^{:doc "USAGE:
Use for JAAS Kerberos Plain Text
(def tcp-client (... create tcp client ...)
(def c (jaas/jaas-login \"KafkaClient\"))
(def sasl-client (jaas/sasl-client c (jaas/principal-name c) broker-host))
(jaas/sasl-handshake! tcp-client sasl-client timeout-ms)
System environment config must be set, see the project.clj file for this project.
Properties required are:
-Djava.security.auth.login.config=/vagrant/vagrant/config/kafka_client_jaas.conf
-Djava.security.krb5.conf=/vagrant/vagrant/config/krb5.conf
"}
kafka-clj.jaas
(:import (javax.security.auth.login LoginContext)
(javax.security.auth Subject)
(java.security PrivilegedExceptionAction Principal)
(javax.security.sasl Sasl SaslClient)
(javax.security.auth.callback CallbackHandler)
(java.util.concurrent TimeoutException)
(io.netty.buffer ByteBuf Unpooled)
(javax.security.auth.kerberos KerberosTicket)
(java.io InputStream ByteArrayInputStream ByteArrayOutputStream)
(sun.misc HexDumpEncoder)
(kafka_clj.util Util))
(:require [clojure.tools.logging :refer [info error debug]]
[kafka-clj.tcp-api :as tcp-api]
[kafka-clj.protocol :as protocol]
[tcp-driver.driver :as tcp-driver]
[tcp-driver.io.stream :as tcp-stream]
[kafka-clj.buff-utils :as buff-utils]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;; helper functions
(defonce ^:constant MECHS (into-array String ["GSSAPI"]))
(defonce ^:constant ^Long HALF-MINUTE-MS (* 30 1000))
(defn timeout? [timeout-ms current-ms]
(> (- (System/currentTimeMillis) (long current-ms)) (long timeout-ms)))
(defn with-auth [^LoginContext ctx f]
(Subject/doAs ^Subject (.getSubject ctx)
(reify PrivilegedExceptionAction
(run [_]
(f)))))
(defn readp-resp [conn timeout-ms]
(let [len (tcp-stream/read-int conn timeout-ms)]
(tcp-stream/read-bytes conn len timeout-ms)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; public functions
(defn kafka-service-name
"Search for sasl.kerberos.service.name is defined in either conf, System.properties its used,
otherwise the default kafka name is used"
[conf]
(or
(:sasl.kerberos.service.name conf)
(System/getProperty "sasl.kerberos.service.name")
"kafka"))
(defn jaas-login ^LoginContext
[jaas-name]
(debug "trying jaas login for name " jaas-name)
(let [login (LoginContext. (str jaas-name))]
(.login login)
(debug "login complete: have " login)
login))
(defn jaas-expire-time
"For all KerberosTicket(s) in the LoginContext the min auth time value is returned"
[^LoginContext ctx]
(let [^Subject subject (.getSubject ctx)]
(if subject
(apply
min
(map
#(.getTime (.getEndTime ^KerberosTicket %))
(.getPrivateCredentials subject KerberosTicket)))
Long/MAX_VALUE)))
(defn jaas-expired?
"True if the expire time is withing 30 seconds of the current time"
[^LoginContext ctx]
(debug "jaas-expired: expire-time " (long (jaas-expire-time ctx)) " curr-time " (System/currentTimeMillis))
(<
(- (long (jaas-expire-time ctx))
(System/currentTimeMillis))
HALF-MINUTE-MS))
(defn jaas-logout [^LoginContext ctx]
(.logout ctx))
(defn ^Principal principal-name
"Return the unparsed principal name e.g kafka/broker1.kafkafast@KAFKAFAST
A context can have multiple principals, this method returns the first principal found"
[^LoginContext ctx]
(.getName ^Principal (first (.getPrincipals ^Subject (.getSubject ctx)))))
;;with auth
(defn ^SaslClient sasl-client
"See https://docs.oracle.com/javase/8/docs/api/javax/security/sasl/Sasl.html
servicePrincipal: should be in the format kafka/{host} see kafka-principal-name
host: the kafka broker"
[conf ^LoginContext ctx host]
(let []
(with-auth ctx (fn []
(Sasl/createSaslClient MECHS
(principal-name ctx)
(str (kafka-service-name conf)) ;;the sasl client will construct kafka/{host}@{REALM}
(str host)
{}
(reify CallbackHandler
(handle [_ callbacks]
(debug "Callback " callbacks))))))))
(defn as-hex [^"[B" bts]
(when bts
(let [cnt (Math/min (int 16) (int (count bts)))
arr-out (ByteArrayOutputStream.)
bts-in (ByteArrayInputStream. bts (int 0) (int cnt))]
(.encodeBuffer (HexDumpEncoder.) bts-in arr-out)
(.toString arr-out))))
(defn send-read-data
"Write [int size][client-resp] then read [int size][server resp]"
[conn ^"[B" client-resp should-read timeout-ms]
(debug "gssapi send to broker : " (as-hex client-resp))
(tcp-stream/write-int conn (count client-resp))
(tcp-stream/write-bytes conn client-resp)
(tcp-stream/flush-out conn)
(when should-read
(let [resp (readp-resp conn timeout-ms)]
(debug "gssapi read from broker : " (as-hex resp))
resp)))
(defn handshake-loop! [conn ^SaslClient sasl-client timeout-ms]
{:pre [conn sasl-client (number? timeout-ms)]}
(let [current-ms (System/currentTimeMillis)]
(loop [server-resp (byte-array []) initial true]
(cond
(timeout? timeout-ms current-ms) (throw (TimeoutException. (str "Could not handshake with sasl client " sasl-client " in " timeout-ms "ms")))
(.isComplete sasl-client) true
:else (let [client-resp (if (and
initial
(not (.hasInitialResponse sasl-client)))
(byte-array []) ;;send initial empty byte array token
(.evaluateChallenge sasl-client server-resp)) ;otherwise eval and send response back
]
(if client-resp ;;if any client-resp data, send, but only if sasl-client is not complete
(recur (send-read-data conn client-resp (not (.isComplete sasl-client)) timeout-ms) false)
(recur server-resp false)))))))
(defn handshake-request!
"
SaslHandshake API (Key: 17)
1. SizeInBytes => int16
2. api_key => <KEY> (<KEY> <KEY>
3. api_version => INT16 (0)
4. correlation_id => INT32
5. client_id => NULLABLE_STRING
6. mechanism => String \"GSSAPI\" or \"PLAIN\";
"
[conn]
(let [corr-id (protocol/unique-corrid!)
buff (Unpooled/buffer)
_ (do
(buff-utils/with-size buff
(fn [^ByteBuf buff]
(.writeShort buff (short protocol/API_KEY_SASL_HANDSHAKE))
(.writeShort buff (short protocol/API_VERSION))
(.writeInt buff (int corr-id))
(buff-utils/write-short-string buff nil)
(buff-utils/write-short-string buff (str (first MECHS))))))]
(info "Write request: " (short protocol/API_KEY_SASL_HANDSHAKE)
" version " (int protocol/API_VERSION)
" mechs " (str (first MECHS))
" corr-id " corr-id)
(tcp-stream/write-bytes conn (Util/toBytes ^ByteBuf buff))
(tcp-stream/flush-out conn)))
(defn handshake-response!
";Response:
1. SizeInBytes => int16
2. correlation_id => INT32
3. error_code => INT16
0 => None, 34 => InvalidSaslState, 35 => UnsupportedVersion
4. enabled_mechanisms => [STRING]"
[conn timeout-ms]
(let [len (tcp-stream/read-int conn timeout-ms)
^ByteBuf buff (Unpooled/wrappedBuffer ^"[B" (tcp-stream/read-bytes conn len timeout-ms))
corr-id (.readInt buff)
error-code (.readShort buff)
mechs (buff-utils/read-string-array buff)]
(info "handshake-response: error-code: " error-code " mechs " mechs " corr-id " corr-id)
(if (zero? error-code)
true
(throw (RuntimeException. (str "Handshake error: " error-code " mechanims: " mechs))))))
(defn sasl-handshake!
"client: kafka-clj/tcp client
sasl-client: jaas/sasl-client
timeout-ms: timeout in milliseconds"
[conn ^SaslClient sasl-client timeout-ms & {:keys [kafka-version] :or {kafka-version "0.10.0"}}]
(debug "sasl-handshake!: >>>>>>>>>>>>>>>>>>>>>>>>kafka-version: " kafka-version)
(when (not (.contains (str kafka-version) "0.9"))
(handshake-request! conn)
(handshake-response! conn timeout-ms))
;;no exception means handshake is complete
(handshake-loop! conn sasl-client timeout-ms))
| true | (ns
^{:doc "USAGE:
Use for JAAS Kerberos Plain Text
(def tcp-client (... create tcp client ...)
(def c (jaas/jaas-login \"KafkaClient\"))
(def sasl-client (jaas/sasl-client c (jaas/principal-name c) broker-host))
(jaas/sasl-handshake! tcp-client sasl-client timeout-ms)
System environment config must be set, see the project.clj file for this project.
Properties required are:
-Djava.security.auth.login.config=/vagrant/vagrant/config/kafka_client_jaas.conf
-Djava.security.krb5.conf=/vagrant/vagrant/config/krb5.conf
"}
kafka-clj.jaas
(:import (javax.security.auth.login LoginContext)
(javax.security.auth Subject)
(java.security PrivilegedExceptionAction Principal)
(javax.security.sasl Sasl SaslClient)
(javax.security.auth.callback CallbackHandler)
(java.util.concurrent TimeoutException)
(io.netty.buffer ByteBuf Unpooled)
(javax.security.auth.kerberos KerberosTicket)
(java.io InputStream ByteArrayInputStream ByteArrayOutputStream)
(sun.misc HexDumpEncoder)
(kafka_clj.util Util))
(:require [clojure.tools.logging :refer [info error debug]]
[kafka-clj.tcp-api :as tcp-api]
[kafka-clj.protocol :as protocol]
[tcp-driver.driver :as tcp-driver]
[tcp-driver.io.stream :as tcp-stream]
[kafka-clj.buff-utils :as buff-utils]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;; helper functions
(defonce ^:constant MECHS (into-array String ["GSSAPI"]))
(defonce ^:constant ^Long HALF-MINUTE-MS (* 30 1000))
(defn timeout? [timeout-ms current-ms]
(> (- (System/currentTimeMillis) (long current-ms)) (long timeout-ms)))
(defn with-auth [^LoginContext ctx f]
(Subject/doAs ^Subject (.getSubject ctx)
(reify PrivilegedExceptionAction
(run [_]
(f)))))
(defn readp-resp [conn timeout-ms]
(let [len (tcp-stream/read-int conn timeout-ms)]
(tcp-stream/read-bytes conn len timeout-ms)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;; public functions
(defn kafka-service-name
"Search for sasl.kerberos.service.name is defined in either conf, System.properties its used,
otherwise the default kafka name is used"
[conf]
(or
(:sasl.kerberos.service.name conf)
(System/getProperty "sasl.kerberos.service.name")
"kafka"))
(defn jaas-login ^LoginContext
[jaas-name]
(debug "trying jaas login for name " jaas-name)
(let [login (LoginContext. (str jaas-name))]
(.login login)
(debug "login complete: have " login)
login))
(defn jaas-expire-time
"For all KerberosTicket(s) in the LoginContext the min auth time value is returned"
[^LoginContext ctx]
(let [^Subject subject (.getSubject ctx)]
(if subject
(apply
min
(map
#(.getTime (.getEndTime ^KerberosTicket %))
(.getPrivateCredentials subject KerberosTicket)))
Long/MAX_VALUE)))
(defn jaas-expired?
"True if the expire time is withing 30 seconds of the current time"
[^LoginContext ctx]
(debug "jaas-expired: expire-time " (long (jaas-expire-time ctx)) " curr-time " (System/currentTimeMillis))
(<
(- (long (jaas-expire-time ctx))
(System/currentTimeMillis))
HALF-MINUTE-MS))
(defn jaas-logout [^LoginContext ctx]
(.logout ctx))
(defn ^Principal principal-name
"Return the unparsed principal name e.g kafka/broker1.kafkafast@KAFKAFAST
A context can have multiple principals, this method returns the first principal found"
[^LoginContext ctx]
(.getName ^Principal (first (.getPrincipals ^Subject (.getSubject ctx)))))
;;with auth
(defn ^SaslClient sasl-client
"See https://docs.oracle.com/javase/8/docs/api/javax/security/sasl/Sasl.html
servicePrincipal: should be in the format kafka/{host} see kafka-principal-name
host: the kafka broker"
[conf ^LoginContext ctx host]
(let []
(with-auth ctx (fn []
(Sasl/createSaslClient MECHS
(principal-name ctx)
(str (kafka-service-name conf)) ;;the sasl client will construct kafka/{host}@{REALM}
(str host)
{}
(reify CallbackHandler
(handle [_ callbacks]
(debug "Callback " callbacks))))))))
(defn as-hex [^"[B" bts]
(when bts
(let [cnt (Math/min (int 16) (int (count bts)))
arr-out (ByteArrayOutputStream.)
bts-in (ByteArrayInputStream. bts (int 0) (int cnt))]
(.encodeBuffer (HexDumpEncoder.) bts-in arr-out)
(.toString arr-out))))
(defn send-read-data
"Write [int size][client-resp] then read [int size][server resp]"
[conn ^"[B" client-resp should-read timeout-ms]
(debug "gssapi send to broker : " (as-hex client-resp))
(tcp-stream/write-int conn (count client-resp))
(tcp-stream/write-bytes conn client-resp)
(tcp-stream/flush-out conn)
(when should-read
(let [resp (readp-resp conn timeout-ms)]
(debug "gssapi read from broker : " (as-hex resp))
resp)))
(defn handshake-loop! [conn ^SaslClient sasl-client timeout-ms]
{:pre [conn sasl-client (number? timeout-ms)]}
(let [current-ms (System/currentTimeMillis)]
(loop [server-resp (byte-array []) initial true]
(cond
(timeout? timeout-ms current-ms) (throw (TimeoutException. (str "Could not handshake with sasl client " sasl-client " in " timeout-ms "ms")))
(.isComplete sasl-client) true
:else (let [client-resp (if (and
initial
(not (.hasInitialResponse sasl-client)))
(byte-array []) ;;send initial empty byte array token
(.evaluateChallenge sasl-client server-resp)) ;otherwise eval and send response back
]
(if client-resp ;;if any client-resp data, send, but only if sasl-client is not complete
(recur (send-read-data conn client-resp (not (.isComplete sasl-client)) timeout-ms) false)
(recur server-resp false)))))))
(defn handshake-request!
"
SaslHandshake API (Key: 17)
1. SizeInBytes => int16
2. api_key => PI:KEY:<KEY>END_PI (PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI
3. api_version => INT16 (0)
4. correlation_id => INT32
5. client_id => NULLABLE_STRING
6. mechanism => String \"GSSAPI\" or \"PLAIN\";
"
[conn]
(let [corr-id (protocol/unique-corrid!)
buff (Unpooled/buffer)
_ (do
(buff-utils/with-size buff
(fn [^ByteBuf buff]
(.writeShort buff (short protocol/API_KEY_SASL_HANDSHAKE))
(.writeShort buff (short protocol/API_VERSION))
(.writeInt buff (int corr-id))
(buff-utils/write-short-string buff nil)
(buff-utils/write-short-string buff (str (first MECHS))))))]
(info "Write request: " (short protocol/API_KEY_SASL_HANDSHAKE)
" version " (int protocol/API_VERSION)
" mechs " (str (first MECHS))
" corr-id " corr-id)
(tcp-stream/write-bytes conn (Util/toBytes ^ByteBuf buff))
(tcp-stream/flush-out conn)))
(defn handshake-response!
";Response:
1. SizeInBytes => int16
2. correlation_id => INT32
3. error_code => INT16
0 => None, 34 => InvalidSaslState, 35 => UnsupportedVersion
4. enabled_mechanisms => [STRING]"
[conn timeout-ms]
(let [len (tcp-stream/read-int conn timeout-ms)
^ByteBuf buff (Unpooled/wrappedBuffer ^"[B" (tcp-stream/read-bytes conn len timeout-ms))
corr-id (.readInt buff)
error-code (.readShort buff)
mechs (buff-utils/read-string-array buff)]
(info "handshake-response: error-code: " error-code " mechs " mechs " corr-id " corr-id)
(if (zero? error-code)
true
(throw (RuntimeException. (str "Handshake error: " error-code " mechanims: " mechs))))))
(defn sasl-handshake!
"client: kafka-clj/tcp client
sasl-client: jaas/sasl-client
timeout-ms: timeout in milliseconds"
[conn ^SaslClient sasl-client timeout-ms & {:keys [kafka-version] :or {kafka-version "0.10.0"}}]
(debug "sasl-handshake!: >>>>>>>>>>>>>>>>>>>>>>>>kafka-version: " kafka-version)
(when (not (.contains (str kafka-version) "0.9"))
(handshake-request! conn)
(handshake-response! conn timeout-ms))
;;no exception means handshake is complete
(handshake-loop! conn sasl-client timeout-ms))
|
[
{
"context": " (.setRefreshInterval (int 0))\n ;; (.putUser \"alfresco\" (org.eclipse.jetty.util.security.Password. \"alfr",
"end": 4946,
"score": 0.9992841482162476,
"start": 4938,
"tag": "USERNAME",
"value": "alfresco"
},
{
"context": "esco\" (org.eclipse.jetty.util.security.Password. \"alfresco\"))\n ))\n\n(defn alfresco-configure [server]\n (.",
"end": 5000,
"score": 0.9986261129379272,
"start": 4992,
"tag": "PASSWORD",
"value": "alfresco"
}
] | itest/jetty.clj | deas/lambdalf | 1 | (ns jetty
"Jetty 9 server, shamelessly stolen (from jetty9 ring adapter) and hacked.
Fire it up like so:
(def jetty-component
(jetty/new-jetty (jetty/create-jetty (jetty/create-handler \"./test-webapp\" \"/alfresco\")
{:port 1234 :configurator jetty/alfresco-configure })))
(.start jetty-component)
"
(:import (org.eclipse.jetty.server Handler
Server
Request
ServerConnector
HttpConfiguration
HttpConnectionFactory
SslConnectionFactory
ConnectionFactory)
(org.eclipse.jetty.server.handler HandlerCollection
AbstractHandler
ContextHandler
HandlerList)
(org.eclipse.jetty.webapp WebAppContext)
(org.eclipse.jetty.util.thread QueuedThreadPool
ScheduledExecutorScheduler)
(org.eclipse.jetty.util.ssl SslContextFactory))
(:require [clojure.string :as string]
[clojure.tools.logging :as log]
[com.stuartsierra.component :as component]))
(defn- http-config
[{:as options
:keys [ssl-port secure-scheme output-buffer-size request-header-size
response-header-size send-server-version? send-date-header?
header-cache-size]
:or {ssl-port 443
secure-scheme "https"
output-buffer-size 32768
request-header-size 8192
response-header-size 8192
send-server-version? true
send-date-header? false
header-cache-size 512}}]
"Creates jetty http configurator"
(doto (HttpConfiguration.)
(.setSecureScheme secure-scheme)
(.setSecurePort ssl-port)
(.setOutputBufferSize output-buffer-size)
(.setRequestHeaderSize request-header-size)
(.setResponseHeaderSize response-header-size)
(.setSendServerVersion send-server-version?)
(.setSendDateHeader send-date-header?)
(.setHeaderCacheSize header-cache-size)))
(defn- ssl-context-factory
"Creates a new SslContextFactory instance from a map of options."
[{:as options
:keys [keystore keystore-type key-password client-auth
truststore trust-password truststore-type]}]
(let [context (SslContextFactory.)]
(if (string? keystore)
(.setKeyStorePath context keystore)
(.setKeyStore context ^java.security.KeyStore keystore))
(.setKeyStorePassword context key-password)
(when keystore-type
(.setKeyStoreType context keystore-type))
(when truststore
(.setTrustStore context ^java.security.KeyStore truststore))
(when trust-password
(.setTrustStorePassword context trust-password))
(when truststore-type
(.setTrustStoreType context truststore-type))
(case client-auth
:need (.setNeedClientAuth context true)
:want (.setWantClientAuth context true)
nil)
context))
(defn- create-server
"Construct a Jetty Server instance."
[{:as options
:keys [port max-threads daemon? max-idle-time host ssl? ssl-port]
:or {port 80
max-threads 50
daemon? false
max-idle-time 200000
ssl? false}}]
(let [pool (doto (QueuedThreadPool. (int max-threads))
(.setDaemon daemon?))
server (doto (Server. pool)
(.addBean (ScheduledExecutorScheduler.)))
http-configuration (http-config options)
http-connector (doto (ServerConnector.
^Server server
(into-array ConnectionFactory [(HttpConnectionFactory. http-configuration)]))
(.setPort port)
(.setHost host)
(.setIdleTimeout max-idle-time))
https-connector (when (or ssl? ssl-port)
(doto (ServerConnector.
^Server server
(ssl-context-factory options)
(into-array ConnectionFactory [(HttpConnectionFactory. http-configuration)]))
(.setPort ssl-port)
(.setHost host)
(.setIdleTimeout max-idle-time)))
connectors (if https-connector
[http-connector https-connector]
[http-connector])
connectors (into-array connectors)]
(.setConnectors server connectors)
server))
(defn create-login-configurator []
(doto (org.eclipse.jetty.security.HashLoginService.)
(.setName "Repository")
(.setConfig "realm.properties")
(.setRefreshInterval (int 0))
;; (.putUser "alfresco" (org.eclipse.jetty.util.security.Password. "alfresco"))
))
(defn alfresco-configure [server]
(.addBean server (create-login-configurator)))
(defn create-handler [path ctx-path]
(let [handler (WebAppContext. path ctx-path)]
;; (doto handler
;; ;; Y U no kick in?
;; (.setExtraClasspath "./webapp/WEB-INF/lib/alfresco-web-client.jar")) ;; path1;path2
handler))
(defn ^Server create-jetty
"Start a Jetty webserver to serve the given handler according to the
supplied options:
:port - the port to listen on (defaults to 80)
:host - the hostname to listen on
:join? - blocks the thread until server ends (defaults to true)
:daemon? - use daemon threads (defaults to false)
:ssl? - allow connections over HTTPS
:ssl-port - the SSL port to listen on (defaults to 443, implies :ssl?)
:keystore - the keystore to use for SSL connections
:keystore-type - the format of keystore
:key-password - the password to the keystore
:truststore - a truststore to use for SSL connections
:truststore-type - the format of trust store
:trust-password - the password to the truststore
:max-threads - the maximum number of threads to use (default 50)
:max-idle-time - the maximum idle time in milliseconds for a connection (default 200000)
:ws-max-idle-time - the maximum idle time in milliseconds for a websocket connection (default 500000)
:client-auth - SSL client certificate authenticate, may be set to :need, :want or :none (defaults to :none)
:websockets - a map from context path to a map of handler fns:
{\"/context\" {:on-connect #(create-fn %) ; ^Session ws-session
:on-text #(text-fn % %2 %3 %4) ; ^Session ws-session message
:on-bytes #(binary-fn % %2 %3 %4 %5 %6) ; ^Session ws-session payload offset len
:on-close #(close-fn % %2 %3 %4) ; ^Session ws-session statusCode reason
:on-error #(error-fn % %2 %3)}} ; ^Session ws-session e"
[handler {:as options
:keys [max-threads websockets configurator];; join?
:or {max-threads 50}}] ;; join? true
(let [^Server s (create-server options)
^QueuedThreadPool p (QueuedThreadPool. (int max-threads))
;; ring-app-handler (proxy-handler handler)
;; ws-handlers (map (fn [[context-path handler]]
;; (doto (ContextHandler.)
;; (.setContextPath context-path)
;; (.setHandler (proxy-ws-handler handler options))))
;; websockets)
contexts (doto (HandlerList.)
(.setHandlers
;; (into-array Handler (reverse (conj ws-handlers ring-app-handler)))
(into-array Handler [handler])))]
(.setHandler s contexts)
(when-let [c configurator]
(c s))
;; (.start s)
;; (when join?
;; (.join s))
s))
(defrecord Jetty [server]
component/Lifecycle
(start [component]
(log/info "Starting Jetty")
(assoc component :server server)
(.start server))
(stop [component]
(log/info "Stopping Jetty")
(.stop (:server component))
(assoc component :server nil))
)
(defn new-jetty [server]
(map->Jetty {:server server}))
| 53933 | (ns jetty
"Jetty 9 server, shamelessly stolen (from jetty9 ring adapter) and hacked.
Fire it up like so:
(def jetty-component
(jetty/new-jetty (jetty/create-jetty (jetty/create-handler \"./test-webapp\" \"/alfresco\")
{:port 1234 :configurator jetty/alfresco-configure })))
(.start jetty-component)
"
(:import (org.eclipse.jetty.server Handler
Server
Request
ServerConnector
HttpConfiguration
HttpConnectionFactory
SslConnectionFactory
ConnectionFactory)
(org.eclipse.jetty.server.handler HandlerCollection
AbstractHandler
ContextHandler
HandlerList)
(org.eclipse.jetty.webapp WebAppContext)
(org.eclipse.jetty.util.thread QueuedThreadPool
ScheduledExecutorScheduler)
(org.eclipse.jetty.util.ssl SslContextFactory))
(:require [clojure.string :as string]
[clojure.tools.logging :as log]
[com.stuartsierra.component :as component]))
(defn- http-config
[{:as options
:keys [ssl-port secure-scheme output-buffer-size request-header-size
response-header-size send-server-version? send-date-header?
header-cache-size]
:or {ssl-port 443
secure-scheme "https"
output-buffer-size 32768
request-header-size 8192
response-header-size 8192
send-server-version? true
send-date-header? false
header-cache-size 512}}]
"Creates jetty http configurator"
(doto (HttpConfiguration.)
(.setSecureScheme secure-scheme)
(.setSecurePort ssl-port)
(.setOutputBufferSize output-buffer-size)
(.setRequestHeaderSize request-header-size)
(.setResponseHeaderSize response-header-size)
(.setSendServerVersion send-server-version?)
(.setSendDateHeader send-date-header?)
(.setHeaderCacheSize header-cache-size)))
(defn- ssl-context-factory
"Creates a new SslContextFactory instance from a map of options."
[{:as options
:keys [keystore keystore-type key-password client-auth
truststore trust-password truststore-type]}]
(let [context (SslContextFactory.)]
(if (string? keystore)
(.setKeyStorePath context keystore)
(.setKeyStore context ^java.security.KeyStore keystore))
(.setKeyStorePassword context key-password)
(when keystore-type
(.setKeyStoreType context keystore-type))
(when truststore
(.setTrustStore context ^java.security.KeyStore truststore))
(when trust-password
(.setTrustStorePassword context trust-password))
(when truststore-type
(.setTrustStoreType context truststore-type))
(case client-auth
:need (.setNeedClientAuth context true)
:want (.setWantClientAuth context true)
nil)
context))
(defn- create-server
"Construct a Jetty Server instance."
[{:as options
:keys [port max-threads daemon? max-idle-time host ssl? ssl-port]
:or {port 80
max-threads 50
daemon? false
max-idle-time 200000
ssl? false}}]
(let [pool (doto (QueuedThreadPool. (int max-threads))
(.setDaemon daemon?))
server (doto (Server. pool)
(.addBean (ScheduledExecutorScheduler.)))
http-configuration (http-config options)
http-connector (doto (ServerConnector.
^Server server
(into-array ConnectionFactory [(HttpConnectionFactory. http-configuration)]))
(.setPort port)
(.setHost host)
(.setIdleTimeout max-idle-time))
https-connector (when (or ssl? ssl-port)
(doto (ServerConnector.
^Server server
(ssl-context-factory options)
(into-array ConnectionFactory [(HttpConnectionFactory. http-configuration)]))
(.setPort ssl-port)
(.setHost host)
(.setIdleTimeout max-idle-time)))
connectors (if https-connector
[http-connector https-connector]
[http-connector])
connectors (into-array connectors)]
(.setConnectors server connectors)
server))
(defn create-login-configurator []
(doto (org.eclipse.jetty.security.HashLoginService.)
(.setName "Repository")
(.setConfig "realm.properties")
(.setRefreshInterval (int 0))
;; (.putUser "alfresco" (org.eclipse.jetty.util.security.Password. "<PASSWORD>"))
))
(defn alfresco-configure [server]
(.addBean server (create-login-configurator)))
(defn create-handler [path ctx-path]
(let [handler (WebAppContext. path ctx-path)]
;; (doto handler
;; ;; Y U no kick in?
;; (.setExtraClasspath "./webapp/WEB-INF/lib/alfresco-web-client.jar")) ;; path1;path2
handler))
(defn ^Server create-jetty
"Start a Jetty webserver to serve the given handler according to the
supplied options:
:port - the port to listen on (defaults to 80)
:host - the hostname to listen on
:join? - blocks the thread until server ends (defaults to true)
:daemon? - use daemon threads (defaults to false)
:ssl? - allow connections over HTTPS
:ssl-port - the SSL port to listen on (defaults to 443, implies :ssl?)
:keystore - the keystore to use for SSL connections
:keystore-type - the format of keystore
:key-password - the password to the keystore
:truststore - a truststore to use for SSL connections
:truststore-type - the format of trust store
:trust-password - the password to the truststore
:max-threads - the maximum number of threads to use (default 50)
:max-idle-time - the maximum idle time in milliseconds for a connection (default 200000)
:ws-max-idle-time - the maximum idle time in milliseconds for a websocket connection (default 500000)
:client-auth - SSL client certificate authenticate, may be set to :need, :want or :none (defaults to :none)
:websockets - a map from context path to a map of handler fns:
{\"/context\" {:on-connect #(create-fn %) ; ^Session ws-session
:on-text #(text-fn % %2 %3 %4) ; ^Session ws-session message
:on-bytes #(binary-fn % %2 %3 %4 %5 %6) ; ^Session ws-session payload offset len
:on-close #(close-fn % %2 %3 %4) ; ^Session ws-session statusCode reason
:on-error #(error-fn % %2 %3)}} ; ^Session ws-session e"
[handler {:as options
:keys [max-threads websockets configurator];; join?
:or {max-threads 50}}] ;; join? true
(let [^Server s (create-server options)
^QueuedThreadPool p (QueuedThreadPool. (int max-threads))
;; ring-app-handler (proxy-handler handler)
;; ws-handlers (map (fn [[context-path handler]]
;; (doto (ContextHandler.)
;; (.setContextPath context-path)
;; (.setHandler (proxy-ws-handler handler options))))
;; websockets)
contexts (doto (HandlerList.)
(.setHandlers
;; (into-array Handler (reverse (conj ws-handlers ring-app-handler)))
(into-array Handler [handler])))]
(.setHandler s contexts)
(when-let [c configurator]
(c s))
;; (.start s)
;; (when join?
;; (.join s))
s))
(defrecord Jetty [server]
component/Lifecycle
(start [component]
(log/info "Starting Jetty")
(assoc component :server server)
(.start server))
(stop [component]
(log/info "Stopping Jetty")
(.stop (:server component))
(assoc component :server nil))
)
(defn new-jetty [server]
(map->Jetty {:server server}))
| true | (ns jetty
"Jetty 9 server, shamelessly stolen (from jetty9 ring adapter) and hacked.
Fire it up like so:
(def jetty-component
(jetty/new-jetty (jetty/create-jetty (jetty/create-handler \"./test-webapp\" \"/alfresco\")
{:port 1234 :configurator jetty/alfresco-configure })))
(.start jetty-component)
"
(:import (org.eclipse.jetty.server Handler
Server
Request
ServerConnector
HttpConfiguration
HttpConnectionFactory
SslConnectionFactory
ConnectionFactory)
(org.eclipse.jetty.server.handler HandlerCollection
AbstractHandler
ContextHandler
HandlerList)
(org.eclipse.jetty.webapp WebAppContext)
(org.eclipse.jetty.util.thread QueuedThreadPool
ScheduledExecutorScheduler)
(org.eclipse.jetty.util.ssl SslContextFactory))
(:require [clojure.string :as string]
[clojure.tools.logging :as log]
[com.stuartsierra.component :as component]))
(defn- http-config
[{:as options
:keys [ssl-port secure-scheme output-buffer-size request-header-size
response-header-size send-server-version? send-date-header?
header-cache-size]
:or {ssl-port 443
secure-scheme "https"
output-buffer-size 32768
request-header-size 8192
response-header-size 8192
send-server-version? true
send-date-header? false
header-cache-size 512}}]
"Creates jetty http configurator"
(doto (HttpConfiguration.)
(.setSecureScheme secure-scheme)
(.setSecurePort ssl-port)
(.setOutputBufferSize output-buffer-size)
(.setRequestHeaderSize request-header-size)
(.setResponseHeaderSize response-header-size)
(.setSendServerVersion send-server-version?)
(.setSendDateHeader send-date-header?)
(.setHeaderCacheSize header-cache-size)))
(defn- ssl-context-factory
"Creates a new SslContextFactory instance from a map of options."
[{:as options
:keys [keystore keystore-type key-password client-auth
truststore trust-password truststore-type]}]
(let [context (SslContextFactory.)]
(if (string? keystore)
(.setKeyStorePath context keystore)
(.setKeyStore context ^java.security.KeyStore keystore))
(.setKeyStorePassword context key-password)
(when keystore-type
(.setKeyStoreType context keystore-type))
(when truststore
(.setTrustStore context ^java.security.KeyStore truststore))
(when trust-password
(.setTrustStorePassword context trust-password))
(when truststore-type
(.setTrustStoreType context truststore-type))
(case client-auth
:need (.setNeedClientAuth context true)
:want (.setWantClientAuth context true)
nil)
context))
(defn- create-server
"Construct a Jetty Server instance."
[{:as options
:keys [port max-threads daemon? max-idle-time host ssl? ssl-port]
:or {port 80
max-threads 50
daemon? false
max-idle-time 200000
ssl? false}}]
(let [pool (doto (QueuedThreadPool. (int max-threads))
(.setDaemon daemon?))
server (doto (Server. pool)
(.addBean (ScheduledExecutorScheduler.)))
http-configuration (http-config options)
http-connector (doto (ServerConnector.
^Server server
(into-array ConnectionFactory [(HttpConnectionFactory. http-configuration)]))
(.setPort port)
(.setHost host)
(.setIdleTimeout max-idle-time))
https-connector (when (or ssl? ssl-port)
(doto (ServerConnector.
^Server server
(ssl-context-factory options)
(into-array ConnectionFactory [(HttpConnectionFactory. http-configuration)]))
(.setPort ssl-port)
(.setHost host)
(.setIdleTimeout max-idle-time)))
connectors (if https-connector
[http-connector https-connector]
[http-connector])
connectors (into-array connectors)]
(.setConnectors server connectors)
server))
(defn create-login-configurator []
(doto (org.eclipse.jetty.security.HashLoginService.)
(.setName "Repository")
(.setConfig "realm.properties")
(.setRefreshInterval (int 0))
;; (.putUser "alfresco" (org.eclipse.jetty.util.security.Password. "PI:PASSWORD:<PASSWORD>END_PI"))
))
(defn alfresco-configure [server]
(.addBean server (create-login-configurator)))
(defn create-handler [path ctx-path]
(let [handler (WebAppContext. path ctx-path)]
;; (doto handler
;; ;; Y U no kick in?
;; (.setExtraClasspath "./webapp/WEB-INF/lib/alfresco-web-client.jar")) ;; path1;path2
handler))
(defn ^Server create-jetty
"Start a Jetty webserver to serve the given handler according to the
supplied options:
:port - the port to listen on (defaults to 80)
:host - the hostname to listen on
:join? - blocks the thread until server ends (defaults to true)
:daemon? - use daemon threads (defaults to false)
:ssl? - allow connections over HTTPS
:ssl-port - the SSL port to listen on (defaults to 443, implies :ssl?)
:keystore - the keystore to use for SSL connections
:keystore-type - the format of keystore
:key-password - the password to the keystore
:truststore - a truststore to use for SSL connections
:truststore-type - the format of trust store
:trust-password - the password to the truststore
:max-threads - the maximum number of threads to use (default 50)
:max-idle-time - the maximum idle time in milliseconds for a connection (default 200000)
:ws-max-idle-time - the maximum idle time in milliseconds for a websocket connection (default 500000)
:client-auth - SSL client certificate authenticate, may be set to :need, :want or :none (defaults to :none)
:websockets - a map from context path to a map of handler fns:
{\"/context\" {:on-connect #(create-fn %) ; ^Session ws-session
:on-text #(text-fn % %2 %3 %4) ; ^Session ws-session message
:on-bytes #(binary-fn % %2 %3 %4 %5 %6) ; ^Session ws-session payload offset len
:on-close #(close-fn % %2 %3 %4) ; ^Session ws-session statusCode reason
:on-error #(error-fn % %2 %3)}} ; ^Session ws-session e"
[handler {:as options
:keys [max-threads websockets configurator];; join?
:or {max-threads 50}}] ;; join? true
(let [^Server s (create-server options)
^QueuedThreadPool p (QueuedThreadPool. (int max-threads))
;; ring-app-handler (proxy-handler handler)
;; ws-handlers (map (fn [[context-path handler]]
;; (doto (ContextHandler.)
;; (.setContextPath context-path)
;; (.setHandler (proxy-ws-handler handler options))))
;; websockets)
contexts (doto (HandlerList.)
(.setHandlers
;; (into-array Handler (reverse (conj ws-handlers ring-app-handler)))
(into-array Handler [handler])))]
(.setHandler s contexts)
(when-let [c configurator]
(c s))
;; (.start s)
;; (when join?
;; (.join s))
s))
(defrecord Jetty [server]
component/Lifecycle
(start [component]
(log/info "Starting Jetty")
(assoc component :server server)
(.start server))
(stop [component]
(log/info "Stopping Jetty")
(.stop (:server component))
(assoc component :server nil))
)
(defn new-jetty [server]
(map->Jetty {:server server}))
|
[
{
"context": "(ns #^{:author \"Roger Allen\"\n :doc \"Overtone library code.\"}\n shaderto",
"end": 27,
"score": 0.9998623728752136,
"start": 16,
"tag": "NAME",
"value": "Roger Allen"
},
{
"context": "ume tap synth inspired by\n;; https://github.com/samaaron/arnold/blob/master/src/arnold/voltap.clj\n(defsynt",
"end": 752,
"score": 0.9996206164360046,
"start": 744,
"tag": "USERNAME",
"value": "samaaron"
},
{
"context": "3 0.7\n;;\n;; http://www.physik.uni-wuerzburg.de/~praktiku/Anleitung/Fremde/ANO14.pdf\n(defsynth bus-freqs->b",
"end": 3248,
"score": 0.8545183539390564,
"start": 3240,
"tag": "USERNAME",
"value": "praktiku"
}
] | src/shadertone/tone.clj | baskeboler/shadertone | 304 | (ns #^{:author "Roger Allen"
:doc "Overtone library code."}
shadertone.tone
(:use [overtone.helpers lib]
[overtone.libs event deps]
[overtone.sc defaults synth ugens buffer node foundation-groups bus]
[overtone.sc.cgens buf-io tap]
[overtone.studio core util])
(:require [shadertone.shader :as s]
[overtone.sc.server :as server]) ;; has a "stop" in it
(:import (org.lwjgl BufferUtils)
(java.nio FloatBuffer)
(org.lwjgl.opengl GL11 GL12 GL13 GL20 ARBTextureRg)))
;; ----------------------------------------------------------------------
;; Tap into the Overtone output volume and send it to iOvertoneVolume
;; volume tap synth inspired by
;; https://github.com/samaaron/arnold/blob/master/src/arnold/voltap.clj
(defsynth vol []
(tap "system-vol" 60 (lag (abs (in:ar 0)) 0.1)))
(defonce voltap-synth
(vol [:after (foundation-monitor-group)]))
;; ----------------------------------------------------------------------
;; Grab Waveform & FFT data and send it to the iChannel[0] texture.
;; data capture fns cribbed from overtone/gui/scope.clj
(defonce WAVE-BUF-SIZE 4096) ; stick to powers of 2 for fft and GL
(defonce WAVE-BUF-SIZE-2X (* 2 WAVE-BUF-SIZE))
(defonce FFTWAVE-BUF-SIZE (* 2 WAVE-BUF-SIZE))
(defonce init-wave-array (float-array (repeat WAVE-BUF-SIZE 0.0)))
(defonce init-fft-array (float-array (repeat WAVE-BUF-SIZE 0.0)))
;; synths pour data into these bufs
(defonce wave-buf (buffer WAVE-BUF-SIZE))
(defonce fft-buf (buffer WAVE-BUF-SIZE))
;; on request from ogl, stuff wave-buf & fft-buf into fftwave-float-buf
;; and use that FloatBuffer for texturing
(defonce fftwave-tex-id (atom 0))
(defonce fftwave-tex-num (atom 0))
(defonce fftwave-float-buf (-> ^FloatBuffer (BufferUtils/createFloatBuffer FFTWAVE-BUF-SIZE)
(.put ^floats init-fft-array)
(.put ^floats init-wave-array)
(.flip)))
(defonce wave-bus-synth (bus->buf [:after (foundation-monitor-group)] 0 wave-buf))
(defn- ensure-internal-server!
"Throws an exception if the server isn't internal - wave relies on
fast access to shared buffers with the server which is currently only
available with the internal server. Also ensures server is connected."
[]
(when (server/server-disconnected?)
(throw (Exception. "Cannot use waves until a server has been booted or connected")))
(when (server/external-server?)
(throw (Exception. (str "Sorry, it's only possible to use waves with an internal server. Your server connection info is as follows: " (server/connection-info))))))
;; Inspired by overtone/gui/scope.clj, but made changes for
;; - linear rather than logarithmic dB output
;; - by hand magnitude calculation rather than pv_magsmear
;; - internal fft-buf 2x external buf since it contains
;; real/imag pairs.
;;
;; Buffer update speed:
;; N sec/buf hz/buf res @44100Hz
;; 512 0.012 86.1 43.1
;; 1024 0.023 43.1 21.5
;; 2048 0.046 21.5 10.8
;; 4096 0.093 10.8 5.4 <<< seems reasonable compromise
;; 8192 0.186 5.4 2.7
;; 16384 0.372 2.7 1.3
;; 32768 0.743 1.3 0.7
;;
;; http://www.physik.uni-wuerzburg.de/~praktiku/Anleitung/Fremde/ANO14.pdf
(defsynth bus-freqs->buf
[in-bus 0 scope-buf 1 fft-buf-size WAVE-BUF-SIZE-2X rate 2]
(let [phase (- 1 (* rate (reciprocal fft-buf-size)))
fft-buf (local-buf fft-buf-size 1)
;; drop DC & nyquist samples
n-samples (* 0.5 (- (buf-samples:ir fft-buf) 2))
signal (in in-bus 1)
;; found 0.5 window gave less periodic noise
freqs (fft fft-buf signal 0.5 HANN)
;; indexer = 2, 4, 6, ..., N-4, N-2
indexer (+ n-samples 2
(* (lf-saw (/ rate (buf-dur:ir fft-buf)) phase) ;; what are limits to this rate?
n-samples))
indexer (round indexer 2) ;; always point to the real sample
;; convert real,imag pairs to magnitude
s0 (buf-rd 1 fft-buf indexer 1 1)
s1 (buf-rd 1 fft-buf (+ 1 indexer) 1 1) ; kibit keep
lin-mag (sqrt (+ (* s0 s0) (* s1 s1)))]
(record-buf lin-mag scope-buf)))
(defonce fft-bus-synth
(bus-freqs->buf [:after (foundation-monitor-group)] 0 fft-buf))
;; user-fn for shader display of waveform and fft
(defn tone-fftwave-fn
"The shader display will call this routine on every draw. Update
the waveform texture with FFT data in the first row and waveform
data in the 2nd row."
[dispatch pgm-id]
(case dispatch ;; FIXME defmulti?
:init ;; create & bind the texture
(let [tex-id (GL11/glGenTextures)]
(ensure-internal-server!)
(reset! fftwave-tex-id tex-id)
(GL11/glBindTexture GL11/GL_TEXTURE_2D tex-id)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_MAG_FILTER
GL11/GL_LINEAR)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_MIN_FILTER
GL11/GL_LINEAR)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_WRAP_S
GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_WRAP_T
GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexImage2D GL11/GL_TEXTURE_2D
0 ARBTextureRg/GL_R32F
^Integer WAVE-BUF-SIZE
2 0 GL11/GL_RED GL11/GL_FLOAT
^FloatBuffer fftwave-float-buf)
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0))
:pre-draw ;; grab the data and put it in the texture for drawing.
(do
(if (buffer-live? wave-buf) ;; FIXME? assume fft-buf is live
(-> ^FloatBuffer fftwave-float-buf
(.put ^floats (buffer-data fft-buf))
(.put ^floats (buffer-data wave-buf))
(.flip)))
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 @fftwave-tex-num))
(GL11/glBindTexture GL11/GL_TEXTURE_2D @fftwave-tex-id)
(GL11/glTexImage2D GL11/GL_TEXTURE_2D 0 ARBTextureRg/GL_R32F
^Integer WAVE-BUF-SIZE
2 0 GL11/GL_RED GL11/GL_FLOAT
^FloatBuffer fftwave-float-buf))
:post-draw ;; unbind the texture
(do
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 @fftwave-tex-num))
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0))
:destroy ;;
(do
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0)
(GL11/glDeleteTextures ^Integer @fftwave-tex-id))))
(defn- fix-fftwav-texture
"look for the :overtone-audio keyword, set the fftwave-tex-num atom"
[[i tex]]
(if (or (string? tex)
(and (keyword? tex) (= :previous-frame tex)))
tex ;; just return the string untouched
(do
(assert (keyword? tex))
(assert (= :overtone-audio tex))
(reset! fftwave-tex-num i) ;; NOTE: multiple entries will only use last one
nil))) ;; return nil
(defn- fix-texture-list
"look for the :overtone-audio keyword and replace it with nil"
[textures]
(reset! fftwave-tex-num 0) ;; FIXME this default could mess up other tex0 cases
(map fix-fftwav-texture (map-indexed vector textures)))
;; ======================================================================
(defonce tone-user-data (atom {}))
(defonce tone-user-locs (atom {}))
;; The default Overtone user-draw-fn expects:
;; uniform float iOvertoneVolume;
;; at the top of your glsl shader.
;; Also calls tone-fftwave-fn to put waveform and fft data into:
;; iChannel[0]
(defn- tone-default-fn
[dispatch pgm-id]
(case dispatch ;; FIXME defmulti?
:init ;; find Uniform Location
(doseq [key (keys @tone-user-data)]
(let [loc (GL20/glGetUniformLocation ^Integer pgm-id ^String key)]
(swap! tone-user-locs assoc key loc)))
:pre-draw
(doseq [key (keys @tone-user-data)]
(let [loc (@tone-user-locs key)
val (deref (@tone-user-data key))
val (if (map? val)
;; special handling for maps--expected to be synth taps
;; FIXME? is a map okay? or should it be a record?
(try
(float @(get-in (:synth val) [:taps (:tap val)]))
(catch Exception e 0.0))
;; other user data
val)]
;;(println key loc val)
(if (float? val)
(GL20/glUniform1f loc val)
(when (vector? val)
(case (count val)
1 (GL20/glUniform1f loc (nth val 0))
2 (GL20/glUniform2f loc (nth val 0) (nth val 1))
3 (GL20/glUniform3f loc (nth val 0) (nth val 1) (nth val 2))
4 (GL20/glUniform4f loc (nth val 0) (nth val 1) (nth val 2) (nth val 3)))))))
:post-draw
nil ;; nothing to do
:destroy
nil ;; nothing to do
)
(tone-fftwave-fn dispatch pgm-id))
;; ======================================================================
;; Public API
(defn start
"Start a new shader display. Pass in optional user-data and user-fn
for custom control."
[shader-filename-or-str-atom
&{:keys [width height title textures user-data user-fn]
:or {width 600
height 600
title "shadertone"
textures []
user-data {}
user-fn tone-default-fn}}]
(let [textures (fix-texture-list textures)
user-data (merge-with #(or %1 %2) ; kibit keep
user-data {"iOvertoneVolume"
(atom {:synth voltap-synth
:tap "system-vol"})})]
(reset! tone-user-data user-data)
(s/start shader-filename-or-str-atom
:width width
:height height
:title title
:textures textures
:user-fn user-fn)))
(defn start-fullscreen
"Start a new fullscreen shader display. Pass in optional user-data
and user-fn for custom control."
[shader-filename-or-str-atom
&{:keys [textures user-data user-fn]
:or {textures []
user-data {}
user-fn tone-default-fn}}]
(let [textures (fix-texture-list textures)
user-data (merge-with #(or %1 %2) ; kibit keep
user-data {"iOvertoneVolume"
(atom {:synth voltap-synth
:tap "system-vol"})})]
(reset! tone-user-data user-data)
(s/start-fullscreen shader-filename-or-str-atom
:textures textures
:user-fn user-fn)))
(defn stop
[]
(s/stop))
| 65034 | (ns #^{:author "<NAME>"
:doc "Overtone library code."}
shadertone.tone
(:use [overtone.helpers lib]
[overtone.libs event deps]
[overtone.sc defaults synth ugens buffer node foundation-groups bus]
[overtone.sc.cgens buf-io tap]
[overtone.studio core util])
(:require [shadertone.shader :as s]
[overtone.sc.server :as server]) ;; has a "stop" in it
(:import (org.lwjgl BufferUtils)
(java.nio FloatBuffer)
(org.lwjgl.opengl GL11 GL12 GL13 GL20 ARBTextureRg)))
;; ----------------------------------------------------------------------
;; Tap into the Overtone output volume and send it to iOvertoneVolume
;; volume tap synth inspired by
;; https://github.com/samaaron/arnold/blob/master/src/arnold/voltap.clj
(defsynth vol []
(tap "system-vol" 60 (lag (abs (in:ar 0)) 0.1)))
(defonce voltap-synth
(vol [:after (foundation-monitor-group)]))
;; ----------------------------------------------------------------------
;; Grab Waveform & FFT data and send it to the iChannel[0] texture.
;; data capture fns cribbed from overtone/gui/scope.clj
(defonce WAVE-BUF-SIZE 4096) ; stick to powers of 2 for fft and GL
(defonce WAVE-BUF-SIZE-2X (* 2 WAVE-BUF-SIZE))
(defonce FFTWAVE-BUF-SIZE (* 2 WAVE-BUF-SIZE))
(defonce init-wave-array (float-array (repeat WAVE-BUF-SIZE 0.0)))
(defonce init-fft-array (float-array (repeat WAVE-BUF-SIZE 0.0)))
;; synths pour data into these bufs
(defonce wave-buf (buffer WAVE-BUF-SIZE))
(defonce fft-buf (buffer WAVE-BUF-SIZE))
;; on request from ogl, stuff wave-buf & fft-buf into fftwave-float-buf
;; and use that FloatBuffer for texturing
(defonce fftwave-tex-id (atom 0))
(defonce fftwave-tex-num (atom 0))
(defonce fftwave-float-buf (-> ^FloatBuffer (BufferUtils/createFloatBuffer FFTWAVE-BUF-SIZE)
(.put ^floats init-fft-array)
(.put ^floats init-wave-array)
(.flip)))
(defonce wave-bus-synth (bus->buf [:after (foundation-monitor-group)] 0 wave-buf))
(defn- ensure-internal-server!
"Throws an exception if the server isn't internal - wave relies on
fast access to shared buffers with the server which is currently only
available with the internal server. Also ensures server is connected."
[]
(when (server/server-disconnected?)
(throw (Exception. "Cannot use waves until a server has been booted or connected")))
(when (server/external-server?)
(throw (Exception. (str "Sorry, it's only possible to use waves with an internal server. Your server connection info is as follows: " (server/connection-info))))))
;; Inspired by overtone/gui/scope.clj, but made changes for
;; - linear rather than logarithmic dB output
;; - by hand magnitude calculation rather than pv_magsmear
;; - internal fft-buf 2x external buf since it contains
;; real/imag pairs.
;;
;; Buffer update speed:
;; N sec/buf hz/buf res @44100Hz
;; 512 0.012 86.1 43.1
;; 1024 0.023 43.1 21.5
;; 2048 0.046 21.5 10.8
;; 4096 0.093 10.8 5.4 <<< seems reasonable compromise
;; 8192 0.186 5.4 2.7
;; 16384 0.372 2.7 1.3
;; 32768 0.743 1.3 0.7
;;
;; http://www.physik.uni-wuerzburg.de/~praktiku/Anleitung/Fremde/ANO14.pdf
(defsynth bus-freqs->buf
[in-bus 0 scope-buf 1 fft-buf-size WAVE-BUF-SIZE-2X rate 2]
(let [phase (- 1 (* rate (reciprocal fft-buf-size)))
fft-buf (local-buf fft-buf-size 1)
;; drop DC & nyquist samples
n-samples (* 0.5 (- (buf-samples:ir fft-buf) 2))
signal (in in-bus 1)
;; found 0.5 window gave less periodic noise
freqs (fft fft-buf signal 0.5 HANN)
;; indexer = 2, 4, 6, ..., N-4, N-2
indexer (+ n-samples 2
(* (lf-saw (/ rate (buf-dur:ir fft-buf)) phase) ;; what are limits to this rate?
n-samples))
indexer (round indexer 2) ;; always point to the real sample
;; convert real,imag pairs to magnitude
s0 (buf-rd 1 fft-buf indexer 1 1)
s1 (buf-rd 1 fft-buf (+ 1 indexer) 1 1) ; kibit keep
lin-mag (sqrt (+ (* s0 s0) (* s1 s1)))]
(record-buf lin-mag scope-buf)))
(defonce fft-bus-synth
(bus-freqs->buf [:after (foundation-monitor-group)] 0 fft-buf))
;; user-fn for shader display of waveform and fft
(defn tone-fftwave-fn
"The shader display will call this routine on every draw. Update
the waveform texture with FFT data in the first row and waveform
data in the 2nd row."
[dispatch pgm-id]
(case dispatch ;; FIXME defmulti?
:init ;; create & bind the texture
(let [tex-id (GL11/glGenTextures)]
(ensure-internal-server!)
(reset! fftwave-tex-id tex-id)
(GL11/glBindTexture GL11/GL_TEXTURE_2D tex-id)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_MAG_FILTER
GL11/GL_LINEAR)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_MIN_FILTER
GL11/GL_LINEAR)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_WRAP_S
GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_WRAP_T
GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexImage2D GL11/GL_TEXTURE_2D
0 ARBTextureRg/GL_R32F
^Integer WAVE-BUF-SIZE
2 0 GL11/GL_RED GL11/GL_FLOAT
^FloatBuffer fftwave-float-buf)
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0))
:pre-draw ;; grab the data and put it in the texture for drawing.
(do
(if (buffer-live? wave-buf) ;; FIXME? assume fft-buf is live
(-> ^FloatBuffer fftwave-float-buf
(.put ^floats (buffer-data fft-buf))
(.put ^floats (buffer-data wave-buf))
(.flip)))
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 @fftwave-tex-num))
(GL11/glBindTexture GL11/GL_TEXTURE_2D @fftwave-tex-id)
(GL11/glTexImage2D GL11/GL_TEXTURE_2D 0 ARBTextureRg/GL_R32F
^Integer WAVE-BUF-SIZE
2 0 GL11/GL_RED GL11/GL_FLOAT
^FloatBuffer fftwave-float-buf))
:post-draw ;; unbind the texture
(do
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 @fftwave-tex-num))
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0))
:destroy ;;
(do
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0)
(GL11/glDeleteTextures ^Integer @fftwave-tex-id))))
(defn- fix-fftwav-texture
"look for the :overtone-audio keyword, set the fftwave-tex-num atom"
[[i tex]]
(if (or (string? tex)
(and (keyword? tex) (= :previous-frame tex)))
tex ;; just return the string untouched
(do
(assert (keyword? tex))
(assert (= :overtone-audio tex))
(reset! fftwave-tex-num i) ;; NOTE: multiple entries will only use last one
nil))) ;; return nil
(defn- fix-texture-list
"look for the :overtone-audio keyword and replace it with nil"
[textures]
(reset! fftwave-tex-num 0) ;; FIXME this default could mess up other tex0 cases
(map fix-fftwav-texture (map-indexed vector textures)))
;; ======================================================================
(defonce tone-user-data (atom {}))
(defonce tone-user-locs (atom {}))
;; The default Overtone user-draw-fn expects:
;; uniform float iOvertoneVolume;
;; at the top of your glsl shader.
;; Also calls tone-fftwave-fn to put waveform and fft data into:
;; iChannel[0]
(defn- tone-default-fn
[dispatch pgm-id]
(case dispatch ;; FIXME defmulti?
:init ;; find Uniform Location
(doseq [key (keys @tone-user-data)]
(let [loc (GL20/glGetUniformLocation ^Integer pgm-id ^String key)]
(swap! tone-user-locs assoc key loc)))
:pre-draw
(doseq [key (keys @tone-user-data)]
(let [loc (@tone-user-locs key)
val (deref (@tone-user-data key))
val (if (map? val)
;; special handling for maps--expected to be synth taps
;; FIXME? is a map okay? or should it be a record?
(try
(float @(get-in (:synth val) [:taps (:tap val)]))
(catch Exception e 0.0))
;; other user data
val)]
;;(println key loc val)
(if (float? val)
(GL20/glUniform1f loc val)
(when (vector? val)
(case (count val)
1 (GL20/glUniform1f loc (nth val 0))
2 (GL20/glUniform2f loc (nth val 0) (nth val 1))
3 (GL20/glUniform3f loc (nth val 0) (nth val 1) (nth val 2))
4 (GL20/glUniform4f loc (nth val 0) (nth val 1) (nth val 2) (nth val 3)))))))
:post-draw
nil ;; nothing to do
:destroy
nil ;; nothing to do
)
(tone-fftwave-fn dispatch pgm-id))
;; ======================================================================
;; Public API
(defn start
"Start a new shader display. Pass in optional user-data and user-fn
for custom control."
[shader-filename-or-str-atom
&{:keys [width height title textures user-data user-fn]
:or {width 600
height 600
title "shadertone"
textures []
user-data {}
user-fn tone-default-fn}}]
(let [textures (fix-texture-list textures)
user-data (merge-with #(or %1 %2) ; kibit keep
user-data {"iOvertoneVolume"
(atom {:synth voltap-synth
:tap "system-vol"})})]
(reset! tone-user-data user-data)
(s/start shader-filename-or-str-atom
:width width
:height height
:title title
:textures textures
:user-fn user-fn)))
(defn start-fullscreen
"Start a new fullscreen shader display. Pass in optional user-data
and user-fn for custom control."
[shader-filename-or-str-atom
&{:keys [textures user-data user-fn]
:or {textures []
user-data {}
user-fn tone-default-fn}}]
(let [textures (fix-texture-list textures)
user-data (merge-with #(or %1 %2) ; kibit keep
user-data {"iOvertoneVolume"
(atom {:synth voltap-synth
:tap "system-vol"})})]
(reset! tone-user-data user-data)
(s/start-fullscreen shader-filename-or-str-atom
:textures textures
:user-fn user-fn)))
(defn stop
[]
(s/stop))
| true | (ns #^{:author "PI:NAME:<NAME>END_PI"
:doc "Overtone library code."}
shadertone.tone
(:use [overtone.helpers lib]
[overtone.libs event deps]
[overtone.sc defaults synth ugens buffer node foundation-groups bus]
[overtone.sc.cgens buf-io tap]
[overtone.studio core util])
(:require [shadertone.shader :as s]
[overtone.sc.server :as server]) ;; has a "stop" in it
(:import (org.lwjgl BufferUtils)
(java.nio FloatBuffer)
(org.lwjgl.opengl GL11 GL12 GL13 GL20 ARBTextureRg)))
;; ----------------------------------------------------------------------
;; Tap into the Overtone output volume and send it to iOvertoneVolume
;; volume tap synth inspired by
;; https://github.com/samaaron/arnold/blob/master/src/arnold/voltap.clj
(defsynth vol []
(tap "system-vol" 60 (lag (abs (in:ar 0)) 0.1)))
(defonce voltap-synth
(vol [:after (foundation-monitor-group)]))
;; ----------------------------------------------------------------------
;; Grab Waveform & FFT data and send it to the iChannel[0] texture.
;; data capture fns cribbed from overtone/gui/scope.clj
(defonce WAVE-BUF-SIZE 4096) ; stick to powers of 2 for fft and GL
(defonce WAVE-BUF-SIZE-2X (* 2 WAVE-BUF-SIZE))
(defonce FFTWAVE-BUF-SIZE (* 2 WAVE-BUF-SIZE))
(defonce init-wave-array (float-array (repeat WAVE-BUF-SIZE 0.0)))
(defonce init-fft-array (float-array (repeat WAVE-BUF-SIZE 0.0)))
;; synths pour data into these bufs
(defonce wave-buf (buffer WAVE-BUF-SIZE))
(defonce fft-buf (buffer WAVE-BUF-SIZE))
;; on request from ogl, stuff wave-buf & fft-buf into fftwave-float-buf
;; and use that FloatBuffer for texturing
(defonce fftwave-tex-id (atom 0))
(defonce fftwave-tex-num (atom 0))
(defonce fftwave-float-buf (-> ^FloatBuffer (BufferUtils/createFloatBuffer FFTWAVE-BUF-SIZE)
(.put ^floats init-fft-array)
(.put ^floats init-wave-array)
(.flip)))
(defonce wave-bus-synth (bus->buf [:after (foundation-monitor-group)] 0 wave-buf))
(defn- ensure-internal-server!
"Throws an exception if the server isn't internal - wave relies on
fast access to shared buffers with the server which is currently only
available with the internal server. Also ensures server is connected."
[]
(when (server/server-disconnected?)
(throw (Exception. "Cannot use waves until a server has been booted or connected")))
(when (server/external-server?)
(throw (Exception. (str "Sorry, it's only possible to use waves with an internal server. Your server connection info is as follows: " (server/connection-info))))))
;; Inspired by overtone/gui/scope.clj, but made changes for
;; - linear rather than logarithmic dB output
;; - by hand magnitude calculation rather than pv_magsmear
;; - internal fft-buf 2x external buf since it contains
;; real/imag pairs.
;;
;; Buffer update speed:
;; N sec/buf hz/buf res @44100Hz
;; 512 0.012 86.1 43.1
;; 1024 0.023 43.1 21.5
;; 2048 0.046 21.5 10.8
;; 4096 0.093 10.8 5.4 <<< seems reasonable compromise
;; 8192 0.186 5.4 2.7
;; 16384 0.372 2.7 1.3
;; 32768 0.743 1.3 0.7
;;
;; http://www.physik.uni-wuerzburg.de/~praktiku/Anleitung/Fremde/ANO14.pdf
(defsynth bus-freqs->buf
[in-bus 0 scope-buf 1 fft-buf-size WAVE-BUF-SIZE-2X rate 2]
(let [phase (- 1 (* rate (reciprocal fft-buf-size)))
fft-buf (local-buf fft-buf-size 1)
;; drop DC & nyquist samples
n-samples (* 0.5 (- (buf-samples:ir fft-buf) 2))
signal (in in-bus 1)
;; found 0.5 window gave less periodic noise
freqs (fft fft-buf signal 0.5 HANN)
;; indexer = 2, 4, 6, ..., N-4, N-2
indexer (+ n-samples 2
(* (lf-saw (/ rate (buf-dur:ir fft-buf)) phase) ;; what are limits to this rate?
n-samples))
indexer (round indexer 2) ;; always point to the real sample
;; convert real,imag pairs to magnitude
s0 (buf-rd 1 fft-buf indexer 1 1)
s1 (buf-rd 1 fft-buf (+ 1 indexer) 1 1) ; kibit keep
lin-mag (sqrt (+ (* s0 s0) (* s1 s1)))]
(record-buf lin-mag scope-buf)))
(defonce fft-bus-synth
(bus-freqs->buf [:after (foundation-monitor-group)] 0 fft-buf))
;; user-fn for shader display of waveform and fft
(defn tone-fftwave-fn
"The shader display will call this routine on every draw. Update
the waveform texture with FFT data in the first row and waveform
data in the 2nd row."
[dispatch pgm-id]
(case dispatch ;; FIXME defmulti?
:init ;; create & bind the texture
(let [tex-id (GL11/glGenTextures)]
(ensure-internal-server!)
(reset! fftwave-tex-id tex-id)
(GL11/glBindTexture GL11/GL_TEXTURE_2D tex-id)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_MAG_FILTER
GL11/GL_LINEAR)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_MIN_FILTER
GL11/GL_LINEAR)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_WRAP_S
GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_WRAP_T
GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexImage2D GL11/GL_TEXTURE_2D
0 ARBTextureRg/GL_R32F
^Integer WAVE-BUF-SIZE
2 0 GL11/GL_RED GL11/GL_FLOAT
^FloatBuffer fftwave-float-buf)
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0))
:pre-draw ;; grab the data and put it in the texture for drawing.
(do
(if (buffer-live? wave-buf) ;; FIXME? assume fft-buf is live
(-> ^FloatBuffer fftwave-float-buf
(.put ^floats (buffer-data fft-buf))
(.put ^floats (buffer-data wave-buf))
(.flip)))
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 @fftwave-tex-num))
(GL11/glBindTexture GL11/GL_TEXTURE_2D @fftwave-tex-id)
(GL11/glTexImage2D GL11/GL_TEXTURE_2D 0 ARBTextureRg/GL_R32F
^Integer WAVE-BUF-SIZE
2 0 GL11/GL_RED GL11/GL_FLOAT
^FloatBuffer fftwave-float-buf))
:post-draw ;; unbind the texture
(do
(GL13/glActiveTexture (+ GL13/GL_TEXTURE0 @fftwave-tex-num))
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0))
:destroy ;;
(do
(GL11/glBindTexture GL11/GL_TEXTURE_2D 0)
(GL11/glDeleteTextures ^Integer @fftwave-tex-id))))
(defn- fix-fftwav-texture
"look for the :overtone-audio keyword, set the fftwave-tex-num atom"
[[i tex]]
(if (or (string? tex)
(and (keyword? tex) (= :previous-frame tex)))
tex ;; just return the string untouched
(do
(assert (keyword? tex))
(assert (= :overtone-audio tex))
(reset! fftwave-tex-num i) ;; NOTE: multiple entries will only use last one
nil))) ;; return nil
(defn- fix-texture-list
"look for the :overtone-audio keyword and replace it with nil"
[textures]
(reset! fftwave-tex-num 0) ;; FIXME this default could mess up other tex0 cases
(map fix-fftwav-texture (map-indexed vector textures)))
;; ======================================================================
(defonce tone-user-data (atom {}))
(defonce tone-user-locs (atom {}))
;; The default Overtone user-draw-fn expects:
;; uniform float iOvertoneVolume;
;; at the top of your glsl shader.
;; Also calls tone-fftwave-fn to put waveform and fft data into:
;; iChannel[0]
(defn- tone-default-fn
[dispatch pgm-id]
(case dispatch ;; FIXME defmulti?
:init ;; find Uniform Location
(doseq [key (keys @tone-user-data)]
(let [loc (GL20/glGetUniformLocation ^Integer pgm-id ^String key)]
(swap! tone-user-locs assoc key loc)))
:pre-draw
(doseq [key (keys @tone-user-data)]
(let [loc (@tone-user-locs key)
val (deref (@tone-user-data key))
val (if (map? val)
;; special handling for maps--expected to be synth taps
;; FIXME? is a map okay? or should it be a record?
(try
(float @(get-in (:synth val) [:taps (:tap val)]))
(catch Exception e 0.0))
;; other user data
val)]
;;(println key loc val)
(if (float? val)
(GL20/glUniform1f loc val)
(when (vector? val)
(case (count val)
1 (GL20/glUniform1f loc (nth val 0))
2 (GL20/glUniform2f loc (nth val 0) (nth val 1))
3 (GL20/glUniform3f loc (nth val 0) (nth val 1) (nth val 2))
4 (GL20/glUniform4f loc (nth val 0) (nth val 1) (nth val 2) (nth val 3)))))))
:post-draw
nil ;; nothing to do
:destroy
nil ;; nothing to do
)
(tone-fftwave-fn dispatch pgm-id))
;; ======================================================================
;; Public API
(defn start
"Start a new shader display. Pass in optional user-data and user-fn
for custom control."
[shader-filename-or-str-atom
&{:keys [width height title textures user-data user-fn]
:or {width 600
height 600
title "shadertone"
textures []
user-data {}
user-fn tone-default-fn}}]
(let [textures (fix-texture-list textures)
user-data (merge-with #(or %1 %2) ; kibit keep
user-data {"iOvertoneVolume"
(atom {:synth voltap-synth
:tap "system-vol"})})]
(reset! tone-user-data user-data)
(s/start shader-filename-or-str-atom
:width width
:height height
:title title
:textures textures
:user-fn user-fn)))
(defn start-fullscreen
"Start a new fullscreen shader display. Pass in optional user-data
and user-fn for custom control."
[shader-filename-or-str-atom
&{:keys [textures user-data user-fn]
:or {textures []
user-data {}
user-fn tone-default-fn}}]
(let [textures (fix-texture-list textures)
user-data (merge-with #(or %1 %2) ; kibit keep
user-data {"iOvertoneVolume"
(atom {:synth voltap-synth
:tap "system-vol"})})]
(reset! tone-user-data user-data)
(s/start-fullscreen shader-filename-or-str-atom
:textures textures
:user-fn user-fn)))
(defn stop
[]
(s/stop))
|
[
{
"context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(ns\n #^{:author \"Konrad Hinsen\"\n :skip-wiki true\n :doc \"Examples for usi",
"end": 360,
"score": 0.9998729825019836,
"start": 347,
"tag": "NAME",
"value": "Konrad Hinsen"
}
] | ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/monads/examples.clj | allertonm/Couverjure | 3 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Monad application examples
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns
#^{:author "Konrad Hinsen"
:skip-wiki true
:doc "Examples for using monads"}
clojure.contrib.monads.examples
(:use [clojure.contrib.monads
:only (domonad with-monad m-lift m-seq m-reduce m-when
sequence-m
maybe-m
state-m fetch-state set-state
writer-m write
cont-m run-cont call-cc
maybe-t)])
(:require (clojure.contrib [accumulators :as accu])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Sequence manipulations with the sequence monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Note: in the Haskell world, this monad is called the list monad.
; The Clojure equivalent to Haskell's lists are (possibly lazy)
; sequences. This is why I call this monad "sequence". All sequences
; created by sequence monad operations are lazy.
; Monad comprehensions in the sequence monad work exactly the same
; as Clojure's 'for' construct, except that :while clauses are not
; available.
(domonad sequence-m
[x (range 5)
y (range 3)]
(+ x y))
; Inside a with-monad block, domonad is used without the monad name.
(with-monad sequence-m
(domonad
[x (range 5)
y (range 3)]
(+ x y)))
; Conditions are written with :when, as in Clojure's for form:
(domonad sequence-m
[x (range 5)
y (range (+ 1 x))
:when (= (+ x y) 2)]
(list x y))
; :let is also supported like in for:
(domonad sequence-m
[x (range 5)
y (range (+ 1 x))
:let [sum (+ x y)
diff (- x y)]
:when (= sum 2)]
(list diff))
; An example of a sequence function defined in terms of a lift operation.
(with-monad sequence-m
(defn pairs [xs]
((m-lift 2 #(list %1 %2)) xs xs)))
(pairs (range 5))
; Another way to define pairs is through the m-seq operation. It takes
; a sequence of monadic values and returns a monadic value containing
; the sequence of the underlying values, obtained from chaining together
; from left to right the monadic values in the sequence.
(with-monad sequence-m
(defn pairs [xs]
(m-seq (list xs xs))))
(pairs (range 5))
; This definition suggests a generalization:
(with-monad sequence-m
(defn ntuples [n xs]
(m-seq (replicate n xs))))
(ntuples 2 (range 5))
(ntuples 3 (range 5))
; Lift operations can also be used inside a monad comprehension:
(domonad sequence-m
[x ((m-lift 1 (partial * 2)) (range 5))
y (range 2)]
[x y])
; The m-plus operation does concatenation in the sequence monad.
(domonad sequence-m
[x ((m-lift 2 +) (range 5) (range 3))
y (m-plus (range 2) '(10 11))]
[x y])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Handling failures with the maybe monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Maybe monad versions of basic arithmetic
(with-monad maybe-m
(def m+ (m-lift 2 +))
(def m- (m-lift 2 -))
(def m* (m-lift 2 *)))
; Division is special for two reasons: we can't call it m/ because that's
; not a legal Clojure symbol, and we want it to fail if a division by zero
; is attempted. It is best defined by a monad comprehension with a
; :when clause:
(defn safe-div [x y]
(domonad maybe-m
[a x
b y
:when (not (zero? b))]
(/ a b)))
; Now do some non-trivial computation with division
; It fails for (1) x = 0, (2) y = 0 or (3) y = -x.
(with-monad maybe-m
(defn some-function [x y]
(let [one (m-result 1)]
(safe-div one (m+ (safe-div one (m-result x))
(safe-div one (m-result y)))))))
; An example that doesn't fail:
(some-function 2 3)
; And two that do fail, at different places:
(some-function 2 0)
(some-function 2 -2)
; In the maybe monad, m-plus selects the first monadic value that
; holds a valid value.
(with-monad maybe-m
(m-plus (some-function 2 0) (some-function 2 -2) (some-function 2 3)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Random numbers with the state monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A state monad item represents a computation that changes a state and
; returns a value. Its structure is a function that takes a state argument
; and returns a two-item list containing the value and the updated state.
; It is important to realize that everything you put into a state monad
; expression is a state monad item (thus a function), and everything you
; get out as well. A state monad does not perform a calculation, it
; constructs a function that does the computation when called.
; First, we define a simple random number generator with explicit state.
; rng is a function of its state (an integer) that returns the
; pseudo-random value derived from this state and the updated state
; for the next iteration. This is exactly the structure of a state
; monad item.
(defn rng [seed]
(let [m 259200
value (/ (float seed) (float m))
next (rem (+ 54773 (* 7141 seed)) m)]
[value next]))
; We define a convenience function that creates an infinite lazy seq
; of values obtained from iteratively applying a state monad value.
(defn value-seq [f seed]
(lazy-seq
(let [[value next] (f seed)]
(cons value (value-seq f next)))))
; Next, we define basic statistics functions to check our random numbers
(defn sum [xs] (apply + xs))
(defn mean [xs] (/ (sum xs) (count xs)))
(defn variance [xs]
(let [m (mean xs)
sq #(* % %)]
(mean (for [x xs] (sq (- x m))))))
; rng implements a uniform distribution in the interval [0., 1.), so
; ideally, the mean would be 1/2 (0.5) and the variance 1/12 (0.8333).
(mean (take 1000 (value-seq rng 1)))
(variance (take 1000 (value-seq rng 1)))
; We make use of the state monad to implement a simple (but often sufficient)
; approximation to a Gaussian distribution: the sum of 12 random numbers
; from rng's distribution, shifted by -6, has a distribution that is
; approximately Gaussian with 0 mean and variance 1, by virtue of the central
; limit theorem.
; In the first version, we call rng 12 times explicitly and calculate the
; shifted sum in a monad comprehension:
(def gaussian1
(domonad state-m
[x1 rng
x2 rng
x3 rng
x4 rng
x5 rng
x6 rng
x7 rng
x8 rng
x9 rng
x10 rng
x11 rng
x12 rng]
(- (+ x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 6.)))
; Let's test it:
(mean (take 1000 (value-seq gaussian1 1)))
(variance (take 1000 (value-seq gaussian1 1)))
; Of course, we'd rather have a loop construct for creating the 12
; random numbers. This would be easy if we could define a summation
; operation on random-number generators, which would then be used in
; combination with reduce. The lift operation gives us exactly that.
; More precisely, we need (m-lift 2 +), because we want both arguments
; of + to be lifted to the state monad:
(def gaussian2
(domonad state-m
[sum12 (reduce (m-lift 2 +) (replicate 12 rng))]
(- sum12 6.)))
; Such a reduction is often quite useful, so there's m-reduce predefined
; to simplify it:
(def gaussian2
(domonad state-m
[sum12 (m-reduce + (replicate 12 rng))]
(- sum12 6.)))
; The statistics should be strictly the same as above, as long as
; we use the same seed:
(mean (take 1000 (value-seq gaussian2 1)))
(variance (take 1000 (value-seq gaussian2 1)))
; We can also do the subtraction of 6 in a lifted function, and get rid
; of the monad comprehension altogether:
(with-monad state-m
(def gaussian3
((m-lift 1 #(- % 6.))
(m-reduce + (replicate 12 rng)))))
; Again, the statistics are the same:
(mean (take 1000 (value-seq gaussian3 1)))
(variance (take 1000 (value-seq gaussian3 1)))
; For a random point in two dimensions, we'd like a random number generator
; that yields a list of two random numbers. The m-seq operation can easily
; provide it:
(with-monad state-m
(def rng2 (m-seq (list rng rng))))
; Let's test it:
(rng2 1)
; fetch-state and get-state can be used to save the seed of the random
; number generator and go back to that saved seed later on:
(def identical-random-seqs
(domonad state-m
[seed (fetch-state)
x1 rng
x2 rng
_ (set-state seed)
y1 rng
y2 rng]
(list [x1 x2] [y1 y2])))
(identical-random-seqs 1)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Logging with the writer monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A basic logging example
(domonad (writer-m accu/empty-string)
[x (m-result 1)
_ (write "first step\n")
y (m-result 2)
_ (write "second step\n")]
(+ x y))
; For a more elaborate application, let's trace the recursive calls of
; a naive implementation of a Fibonacci function. The starting point is:
(defn fib [n]
(if (< n 2)
n
(let [n1 (dec n)
n2 (dec n1)]
(+ (fib n1) (fib n2)))))
; First we rewrite it to make every computational step explicit
; in a let expression:
(defn fib [n]
(if (< n 2)
n
(let [n1 (dec n)
n2 (dec n1)
f1 (fib n1)
f2 (fib n2)]
(+ f1 f2))))
; Next, we replace the let by a domonad in a writer monad that uses a
; vector accumulator. We can then place calls to write in between the
; steps, and obtain as a result both the return value of the function
; and the accumulated trace values.
(with-monad (writer-m accu/empty-vector)
(defn fib-trace [n]
(if (< n 2)
(m-result n)
(domonad
[n1 (m-result (dec n))
n2 (m-result (dec n1))
f1 (fib-trace n1)
_ (write [n1 f1])
f2 (fib-trace n2)
_ (write [n2 f2])
]
(+ f1 f2))))
)
(fib-trace 5)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Sequences with undefined value: the maybe-t monad transformer
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A monad transformer is a function that takes a monad argument and
; returns a monad as its result. The resulting monad adds some
; specific behaviour aspect to the input monad.
; The simplest monad transformer is maybe-t. It adds the functionality
; of the maybe monad (handling failures or undefined values) to any other
; monad. We illustrate this by applying maybe-t to the sequence monad.
; The result is an enhanced sequence monad in which undefined values
; (represented by nil) are not subjected to any transformation, but
; lead immediately to a nil result in the output.
; First we define the combined monad:
(def seq-maybe-m (maybe-t sequence-m))
; As a first illustration, we create a range of integers and replace
; all even values by nil, using a simple when expression. We use this
; sequence in a monad comprehension that yields (inc x). The result
; is a sequence in which inc has been applied to all non-nil values,
; whereas the nil values appear unmodified in the output:
(domonad seq-maybe-m
[x (for [n (range 10)] (when (odd? n) n))]
(inc x))
; Next we repeat the definition of the function pairs (see above), but
; using the seq-maybe monad:
(with-monad seq-maybe-m
(defn pairs-maybe [xs]
(m-seq (list xs xs))))
; Applying this to a sequence containing nils yields the pairs of all
; non-nil values interspersed with nils that result from any combination
; in which one or both of the values is nil:
(pairs-maybe (for [n (range 5)] (when (odd? n) n)))
; It is important to realize that undefined values (nil) are not eliminated
; from the iterations. They are simply not passed on to any operations.
; The outcome of any function applied to arguments of which at least one
; is nil is supposed to be nil as well, and the function is never called.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Continuation-passing style in the cont monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A simple computation performed in continuation-passing style.
; (m-result 1) returns a function that, when called with a single
; argument f, calls (f 1). The result of the domonad-computation is
; a function that behaves in the same way, passing 3 to its function
; argument. run-cont executes a continuation by calling it on identity.
(run-cont
(domonad cont-m
[x (m-result 1)
y (m-result 2)]
(+ x y)))
; Let's capture a continuation using call-cc. We store it in a global
; variable so that we can do with it whatever we want. The computation
; is the same one as in the first example, but it has the side effect
; of storing the continuation at (m-result 2).
(def continuation nil)
(run-cont
(domonad cont-m
[x (m-result 1)
y (call-cc (fn [c] (def continuation c) (c 2)))]
(+ x y)))
; Now we can call the continuation with whatever argument we want. The
; supplied argument takes the place of 2 in the above computation:
(run-cont (continuation 5))
(run-cont (continuation 42))
(run-cont (continuation -1))
; Next, a function that illustrates how a captured continuation can be
; used as an "emergency exit" out of a computation:
(defn sqrt-as-str [x]
(call-cc
(fn [k]
(domonad cont-m
[_ (m-when (< x 0) (k (str "negative argument " x)))]
(str (. Math sqrt x))))))
(run-cont (sqrt-as-str 2))
(run-cont (sqrt-as-str -2))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| 90073 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Monad application examples
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns
#^{:author "<NAME>"
:skip-wiki true
:doc "Examples for using monads"}
clojure.contrib.monads.examples
(:use [clojure.contrib.monads
:only (domonad with-monad m-lift m-seq m-reduce m-when
sequence-m
maybe-m
state-m fetch-state set-state
writer-m write
cont-m run-cont call-cc
maybe-t)])
(:require (clojure.contrib [accumulators :as accu])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Sequence manipulations with the sequence monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Note: in the Haskell world, this monad is called the list monad.
; The Clojure equivalent to Haskell's lists are (possibly lazy)
; sequences. This is why I call this monad "sequence". All sequences
; created by sequence monad operations are lazy.
; Monad comprehensions in the sequence monad work exactly the same
; as Clojure's 'for' construct, except that :while clauses are not
; available.
(domonad sequence-m
[x (range 5)
y (range 3)]
(+ x y))
; Inside a with-monad block, domonad is used without the monad name.
(with-monad sequence-m
(domonad
[x (range 5)
y (range 3)]
(+ x y)))
; Conditions are written with :when, as in Clojure's for form:
(domonad sequence-m
[x (range 5)
y (range (+ 1 x))
:when (= (+ x y) 2)]
(list x y))
; :let is also supported like in for:
(domonad sequence-m
[x (range 5)
y (range (+ 1 x))
:let [sum (+ x y)
diff (- x y)]
:when (= sum 2)]
(list diff))
; An example of a sequence function defined in terms of a lift operation.
(with-monad sequence-m
(defn pairs [xs]
((m-lift 2 #(list %1 %2)) xs xs)))
(pairs (range 5))
; Another way to define pairs is through the m-seq operation. It takes
; a sequence of monadic values and returns a monadic value containing
; the sequence of the underlying values, obtained from chaining together
; from left to right the monadic values in the sequence.
(with-monad sequence-m
(defn pairs [xs]
(m-seq (list xs xs))))
(pairs (range 5))
; This definition suggests a generalization:
(with-monad sequence-m
(defn ntuples [n xs]
(m-seq (replicate n xs))))
(ntuples 2 (range 5))
(ntuples 3 (range 5))
; Lift operations can also be used inside a monad comprehension:
(domonad sequence-m
[x ((m-lift 1 (partial * 2)) (range 5))
y (range 2)]
[x y])
; The m-plus operation does concatenation in the sequence monad.
(domonad sequence-m
[x ((m-lift 2 +) (range 5) (range 3))
y (m-plus (range 2) '(10 11))]
[x y])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Handling failures with the maybe monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Maybe monad versions of basic arithmetic
(with-monad maybe-m
(def m+ (m-lift 2 +))
(def m- (m-lift 2 -))
(def m* (m-lift 2 *)))
; Division is special for two reasons: we can't call it m/ because that's
; not a legal Clojure symbol, and we want it to fail if a division by zero
; is attempted. It is best defined by a monad comprehension with a
; :when clause:
(defn safe-div [x y]
(domonad maybe-m
[a x
b y
:when (not (zero? b))]
(/ a b)))
; Now do some non-trivial computation with division
; It fails for (1) x = 0, (2) y = 0 or (3) y = -x.
(with-monad maybe-m
(defn some-function [x y]
(let [one (m-result 1)]
(safe-div one (m+ (safe-div one (m-result x))
(safe-div one (m-result y)))))))
; An example that doesn't fail:
(some-function 2 3)
; And two that do fail, at different places:
(some-function 2 0)
(some-function 2 -2)
; In the maybe monad, m-plus selects the first monadic value that
; holds a valid value.
(with-monad maybe-m
(m-plus (some-function 2 0) (some-function 2 -2) (some-function 2 3)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Random numbers with the state monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A state monad item represents a computation that changes a state and
; returns a value. Its structure is a function that takes a state argument
; and returns a two-item list containing the value and the updated state.
; It is important to realize that everything you put into a state monad
; expression is a state monad item (thus a function), and everything you
; get out as well. A state monad does not perform a calculation, it
; constructs a function that does the computation when called.
; First, we define a simple random number generator with explicit state.
; rng is a function of its state (an integer) that returns the
; pseudo-random value derived from this state and the updated state
; for the next iteration. This is exactly the structure of a state
; monad item.
(defn rng [seed]
(let [m 259200
value (/ (float seed) (float m))
next (rem (+ 54773 (* 7141 seed)) m)]
[value next]))
; We define a convenience function that creates an infinite lazy seq
; of values obtained from iteratively applying a state monad value.
(defn value-seq [f seed]
(lazy-seq
(let [[value next] (f seed)]
(cons value (value-seq f next)))))
; Next, we define basic statistics functions to check our random numbers
(defn sum [xs] (apply + xs))
(defn mean [xs] (/ (sum xs) (count xs)))
(defn variance [xs]
(let [m (mean xs)
sq #(* % %)]
(mean (for [x xs] (sq (- x m))))))
; rng implements a uniform distribution in the interval [0., 1.), so
; ideally, the mean would be 1/2 (0.5) and the variance 1/12 (0.8333).
(mean (take 1000 (value-seq rng 1)))
(variance (take 1000 (value-seq rng 1)))
; We make use of the state monad to implement a simple (but often sufficient)
; approximation to a Gaussian distribution: the sum of 12 random numbers
; from rng's distribution, shifted by -6, has a distribution that is
; approximately Gaussian with 0 mean and variance 1, by virtue of the central
; limit theorem.
; In the first version, we call rng 12 times explicitly and calculate the
; shifted sum in a monad comprehension:
(def gaussian1
(domonad state-m
[x1 rng
x2 rng
x3 rng
x4 rng
x5 rng
x6 rng
x7 rng
x8 rng
x9 rng
x10 rng
x11 rng
x12 rng]
(- (+ x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 6.)))
; Let's test it:
(mean (take 1000 (value-seq gaussian1 1)))
(variance (take 1000 (value-seq gaussian1 1)))
; Of course, we'd rather have a loop construct for creating the 12
; random numbers. This would be easy if we could define a summation
; operation on random-number generators, which would then be used in
; combination with reduce. The lift operation gives us exactly that.
; More precisely, we need (m-lift 2 +), because we want both arguments
; of + to be lifted to the state monad:
(def gaussian2
(domonad state-m
[sum12 (reduce (m-lift 2 +) (replicate 12 rng))]
(- sum12 6.)))
; Such a reduction is often quite useful, so there's m-reduce predefined
; to simplify it:
(def gaussian2
(domonad state-m
[sum12 (m-reduce + (replicate 12 rng))]
(- sum12 6.)))
; The statistics should be strictly the same as above, as long as
; we use the same seed:
(mean (take 1000 (value-seq gaussian2 1)))
(variance (take 1000 (value-seq gaussian2 1)))
; We can also do the subtraction of 6 in a lifted function, and get rid
; of the monad comprehension altogether:
(with-monad state-m
(def gaussian3
((m-lift 1 #(- % 6.))
(m-reduce + (replicate 12 rng)))))
; Again, the statistics are the same:
(mean (take 1000 (value-seq gaussian3 1)))
(variance (take 1000 (value-seq gaussian3 1)))
; For a random point in two dimensions, we'd like a random number generator
; that yields a list of two random numbers. The m-seq operation can easily
; provide it:
(with-monad state-m
(def rng2 (m-seq (list rng rng))))
; Let's test it:
(rng2 1)
; fetch-state and get-state can be used to save the seed of the random
; number generator and go back to that saved seed later on:
(def identical-random-seqs
(domonad state-m
[seed (fetch-state)
x1 rng
x2 rng
_ (set-state seed)
y1 rng
y2 rng]
(list [x1 x2] [y1 y2])))
(identical-random-seqs 1)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Logging with the writer monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A basic logging example
(domonad (writer-m accu/empty-string)
[x (m-result 1)
_ (write "first step\n")
y (m-result 2)
_ (write "second step\n")]
(+ x y))
; For a more elaborate application, let's trace the recursive calls of
; a naive implementation of a Fibonacci function. The starting point is:
(defn fib [n]
(if (< n 2)
n
(let [n1 (dec n)
n2 (dec n1)]
(+ (fib n1) (fib n2)))))
; First we rewrite it to make every computational step explicit
; in a let expression:
(defn fib [n]
(if (< n 2)
n
(let [n1 (dec n)
n2 (dec n1)
f1 (fib n1)
f2 (fib n2)]
(+ f1 f2))))
; Next, we replace the let by a domonad in a writer monad that uses a
; vector accumulator. We can then place calls to write in between the
; steps, and obtain as a result both the return value of the function
; and the accumulated trace values.
(with-monad (writer-m accu/empty-vector)
(defn fib-trace [n]
(if (< n 2)
(m-result n)
(domonad
[n1 (m-result (dec n))
n2 (m-result (dec n1))
f1 (fib-trace n1)
_ (write [n1 f1])
f2 (fib-trace n2)
_ (write [n2 f2])
]
(+ f1 f2))))
)
(fib-trace 5)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Sequences with undefined value: the maybe-t monad transformer
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A monad transformer is a function that takes a monad argument and
; returns a monad as its result. The resulting monad adds some
; specific behaviour aspect to the input monad.
; The simplest monad transformer is maybe-t. It adds the functionality
; of the maybe monad (handling failures or undefined values) to any other
; monad. We illustrate this by applying maybe-t to the sequence monad.
; The result is an enhanced sequence monad in which undefined values
; (represented by nil) are not subjected to any transformation, but
; lead immediately to a nil result in the output.
; First we define the combined monad:
(def seq-maybe-m (maybe-t sequence-m))
; As a first illustration, we create a range of integers and replace
; all even values by nil, using a simple when expression. We use this
; sequence in a monad comprehension that yields (inc x). The result
; is a sequence in which inc has been applied to all non-nil values,
; whereas the nil values appear unmodified in the output:
(domonad seq-maybe-m
[x (for [n (range 10)] (when (odd? n) n))]
(inc x))
; Next we repeat the definition of the function pairs (see above), but
; using the seq-maybe monad:
(with-monad seq-maybe-m
(defn pairs-maybe [xs]
(m-seq (list xs xs))))
; Applying this to a sequence containing nils yields the pairs of all
; non-nil values interspersed with nils that result from any combination
; in which one or both of the values is nil:
(pairs-maybe (for [n (range 5)] (when (odd? n) n)))
; It is important to realize that undefined values (nil) are not eliminated
; from the iterations. They are simply not passed on to any operations.
; The outcome of any function applied to arguments of which at least one
; is nil is supposed to be nil as well, and the function is never called.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Continuation-passing style in the cont monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A simple computation performed in continuation-passing style.
; (m-result 1) returns a function that, when called with a single
; argument f, calls (f 1). The result of the domonad-computation is
; a function that behaves in the same way, passing 3 to its function
; argument. run-cont executes a continuation by calling it on identity.
(run-cont
(domonad cont-m
[x (m-result 1)
y (m-result 2)]
(+ x y)))
; Let's capture a continuation using call-cc. We store it in a global
; variable so that we can do with it whatever we want. The computation
; is the same one as in the first example, but it has the side effect
; of storing the continuation at (m-result 2).
(def continuation nil)
(run-cont
(domonad cont-m
[x (m-result 1)
y (call-cc (fn [c] (def continuation c) (c 2)))]
(+ x y)))
; Now we can call the continuation with whatever argument we want. The
; supplied argument takes the place of 2 in the above computation:
(run-cont (continuation 5))
(run-cont (continuation 42))
(run-cont (continuation -1))
; Next, a function that illustrates how a captured continuation can be
; used as an "emergency exit" out of a computation:
(defn sqrt-as-str [x]
(call-cc
(fn [k]
(domonad cont-m
[_ (m-when (< x 0) (k (str "negative argument " x)))]
(str (. Math sqrt x))))))
(run-cont (sqrt-as-str 2))
(run-cont (sqrt-as-str -2))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| true | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Monad application examples
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns
#^{:author "PI:NAME:<NAME>END_PI"
:skip-wiki true
:doc "Examples for using monads"}
clojure.contrib.monads.examples
(:use [clojure.contrib.monads
:only (domonad with-monad m-lift m-seq m-reduce m-when
sequence-m
maybe-m
state-m fetch-state set-state
writer-m write
cont-m run-cont call-cc
maybe-t)])
(:require (clojure.contrib [accumulators :as accu])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Sequence manipulations with the sequence monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Note: in the Haskell world, this monad is called the list monad.
; The Clojure equivalent to Haskell's lists are (possibly lazy)
; sequences. This is why I call this monad "sequence". All sequences
; created by sequence monad operations are lazy.
; Monad comprehensions in the sequence monad work exactly the same
; as Clojure's 'for' construct, except that :while clauses are not
; available.
(domonad sequence-m
[x (range 5)
y (range 3)]
(+ x y))
; Inside a with-monad block, domonad is used without the monad name.
(with-monad sequence-m
(domonad
[x (range 5)
y (range 3)]
(+ x y)))
; Conditions are written with :when, as in Clojure's for form:
(domonad sequence-m
[x (range 5)
y (range (+ 1 x))
:when (= (+ x y) 2)]
(list x y))
; :let is also supported like in for:
(domonad sequence-m
[x (range 5)
y (range (+ 1 x))
:let [sum (+ x y)
diff (- x y)]
:when (= sum 2)]
(list diff))
; An example of a sequence function defined in terms of a lift operation.
(with-monad sequence-m
(defn pairs [xs]
((m-lift 2 #(list %1 %2)) xs xs)))
(pairs (range 5))
; Another way to define pairs is through the m-seq operation. It takes
; a sequence of monadic values and returns a monadic value containing
; the sequence of the underlying values, obtained from chaining together
; from left to right the monadic values in the sequence.
(with-monad sequence-m
(defn pairs [xs]
(m-seq (list xs xs))))
(pairs (range 5))
; This definition suggests a generalization:
(with-monad sequence-m
(defn ntuples [n xs]
(m-seq (replicate n xs))))
(ntuples 2 (range 5))
(ntuples 3 (range 5))
; Lift operations can also be used inside a monad comprehension:
(domonad sequence-m
[x ((m-lift 1 (partial * 2)) (range 5))
y (range 2)]
[x y])
; The m-plus operation does concatenation in the sequence monad.
(domonad sequence-m
[x ((m-lift 2 +) (range 5) (range 3))
y (m-plus (range 2) '(10 11))]
[x y])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Handling failures with the maybe monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Maybe monad versions of basic arithmetic
(with-monad maybe-m
(def m+ (m-lift 2 +))
(def m- (m-lift 2 -))
(def m* (m-lift 2 *)))
; Division is special for two reasons: we can't call it m/ because that's
; not a legal Clojure symbol, and we want it to fail if a division by zero
; is attempted. It is best defined by a monad comprehension with a
; :when clause:
(defn safe-div [x y]
(domonad maybe-m
[a x
b y
:when (not (zero? b))]
(/ a b)))
; Now do some non-trivial computation with division
; It fails for (1) x = 0, (2) y = 0 or (3) y = -x.
(with-monad maybe-m
(defn some-function [x y]
(let [one (m-result 1)]
(safe-div one (m+ (safe-div one (m-result x))
(safe-div one (m-result y)))))))
; An example that doesn't fail:
(some-function 2 3)
; And two that do fail, at different places:
(some-function 2 0)
(some-function 2 -2)
; In the maybe monad, m-plus selects the first monadic value that
; holds a valid value.
(with-monad maybe-m
(m-plus (some-function 2 0) (some-function 2 -2) (some-function 2 3)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Random numbers with the state monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A state monad item represents a computation that changes a state and
; returns a value. Its structure is a function that takes a state argument
; and returns a two-item list containing the value and the updated state.
; It is important to realize that everything you put into a state monad
; expression is a state monad item (thus a function), and everything you
; get out as well. A state monad does not perform a calculation, it
; constructs a function that does the computation when called.
; First, we define a simple random number generator with explicit state.
; rng is a function of its state (an integer) that returns the
; pseudo-random value derived from this state and the updated state
; for the next iteration. This is exactly the structure of a state
; monad item.
(defn rng [seed]
(let [m 259200
value (/ (float seed) (float m))
next (rem (+ 54773 (* 7141 seed)) m)]
[value next]))
; We define a convenience function that creates an infinite lazy seq
; of values obtained from iteratively applying a state monad value.
(defn value-seq [f seed]
(lazy-seq
(let [[value next] (f seed)]
(cons value (value-seq f next)))))
; Next, we define basic statistics functions to check our random numbers
(defn sum [xs] (apply + xs))
(defn mean [xs] (/ (sum xs) (count xs)))
(defn variance [xs]
(let [m (mean xs)
sq #(* % %)]
(mean (for [x xs] (sq (- x m))))))
; rng implements a uniform distribution in the interval [0., 1.), so
; ideally, the mean would be 1/2 (0.5) and the variance 1/12 (0.8333).
(mean (take 1000 (value-seq rng 1)))
(variance (take 1000 (value-seq rng 1)))
; We make use of the state monad to implement a simple (but often sufficient)
; approximation to a Gaussian distribution: the sum of 12 random numbers
; from rng's distribution, shifted by -6, has a distribution that is
; approximately Gaussian with 0 mean and variance 1, by virtue of the central
; limit theorem.
; In the first version, we call rng 12 times explicitly and calculate the
; shifted sum in a monad comprehension:
(def gaussian1
(domonad state-m
[x1 rng
x2 rng
x3 rng
x4 rng
x5 rng
x6 rng
x7 rng
x8 rng
x9 rng
x10 rng
x11 rng
x12 rng]
(- (+ x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 6.)))
; Let's test it:
(mean (take 1000 (value-seq gaussian1 1)))
(variance (take 1000 (value-seq gaussian1 1)))
; Of course, we'd rather have a loop construct for creating the 12
; random numbers. This would be easy if we could define a summation
; operation on random-number generators, which would then be used in
; combination with reduce. The lift operation gives us exactly that.
; More precisely, we need (m-lift 2 +), because we want both arguments
; of + to be lifted to the state monad:
(def gaussian2
(domonad state-m
[sum12 (reduce (m-lift 2 +) (replicate 12 rng))]
(- sum12 6.)))
; Such a reduction is often quite useful, so there's m-reduce predefined
; to simplify it:
(def gaussian2
(domonad state-m
[sum12 (m-reduce + (replicate 12 rng))]
(- sum12 6.)))
; The statistics should be strictly the same as above, as long as
; we use the same seed:
(mean (take 1000 (value-seq gaussian2 1)))
(variance (take 1000 (value-seq gaussian2 1)))
; We can also do the subtraction of 6 in a lifted function, and get rid
; of the monad comprehension altogether:
(with-monad state-m
(def gaussian3
((m-lift 1 #(- % 6.))
(m-reduce + (replicate 12 rng)))))
; Again, the statistics are the same:
(mean (take 1000 (value-seq gaussian3 1)))
(variance (take 1000 (value-seq gaussian3 1)))
; For a random point in two dimensions, we'd like a random number generator
; that yields a list of two random numbers. The m-seq operation can easily
; provide it:
(with-monad state-m
(def rng2 (m-seq (list rng rng))))
; Let's test it:
(rng2 1)
; fetch-state and get-state can be used to save the seed of the random
; number generator and go back to that saved seed later on:
(def identical-random-seqs
(domonad state-m
[seed (fetch-state)
x1 rng
x2 rng
_ (set-state seed)
y1 rng
y2 rng]
(list [x1 x2] [y1 y2])))
(identical-random-seqs 1)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Logging with the writer monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A basic logging example
(domonad (writer-m accu/empty-string)
[x (m-result 1)
_ (write "first step\n")
y (m-result 2)
_ (write "second step\n")]
(+ x y))
; For a more elaborate application, let's trace the recursive calls of
; a naive implementation of a Fibonacci function. The starting point is:
(defn fib [n]
(if (< n 2)
n
(let [n1 (dec n)
n2 (dec n1)]
(+ (fib n1) (fib n2)))))
; First we rewrite it to make every computational step explicit
; in a let expression:
(defn fib [n]
(if (< n 2)
n
(let [n1 (dec n)
n2 (dec n1)
f1 (fib n1)
f2 (fib n2)]
(+ f1 f2))))
; Next, we replace the let by a domonad in a writer monad that uses a
; vector accumulator. We can then place calls to write in between the
; steps, and obtain as a result both the return value of the function
; and the accumulated trace values.
(with-monad (writer-m accu/empty-vector)
(defn fib-trace [n]
(if (< n 2)
(m-result n)
(domonad
[n1 (m-result (dec n))
n2 (m-result (dec n1))
f1 (fib-trace n1)
_ (write [n1 f1])
f2 (fib-trace n2)
_ (write [n2 f2])
]
(+ f1 f2))))
)
(fib-trace 5)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Sequences with undefined value: the maybe-t monad transformer
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A monad transformer is a function that takes a monad argument and
; returns a monad as its result. The resulting monad adds some
; specific behaviour aspect to the input monad.
; The simplest monad transformer is maybe-t. It adds the functionality
; of the maybe monad (handling failures or undefined values) to any other
; monad. We illustrate this by applying maybe-t to the sequence monad.
; The result is an enhanced sequence monad in which undefined values
; (represented by nil) are not subjected to any transformation, but
; lead immediately to a nil result in the output.
; First we define the combined monad:
(def seq-maybe-m (maybe-t sequence-m))
; As a first illustration, we create a range of integers and replace
; all even values by nil, using a simple when expression. We use this
; sequence in a monad comprehension that yields (inc x). The result
; is a sequence in which inc has been applied to all non-nil values,
; whereas the nil values appear unmodified in the output:
(domonad seq-maybe-m
[x (for [n (range 10)] (when (odd? n) n))]
(inc x))
; Next we repeat the definition of the function pairs (see above), but
; using the seq-maybe monad:
(with-monad seq-maybe-m
(defn pairs-maybe [xs]
(m-seq (list xs xs))))
; Applying this to a sequence containing nils yields the pairs of all
; non-nil values interspersed with nils that result from any combination
; in which one or both of the values is nil:
(pairs-maybe (for [n (range 5)] (when (odd? n) n)))
; It is important to realize that undefined values (nil) are not eliminated
; from the iterations. They are simply not passed on to any operations.
; The outcome of any function applied to arguments of which at least one
; is nil is supposed to be nil as well, and the function is never called.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Continuation-passing style in the cont monad
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A simple computation performed in continuation-passing style.
; (m-result 1) returns a function that, when called with a single
; argument f, calls (f 1). The result of the domonad-computation is
; a function that behaves in the same way, passing 3 to its function
; argument. run-cont executes a continuation by calling it on identity.
(run-cont
(domonad cont-m
[x (m-result 1)
y (m-result 2)]
(+ x y)))
; Let's capture a continuation using call-cc. We store it in a global
; variable so that we can do with it whatever we want. The computation
; is the same one as in the first example, but it has the side effect
; of storing the continuation at (m-result 2).
(def continuation nil)
(run-cont
(domonad cont-m
[x (m-result 1)
y (call-cc (fn [c] (def continuation c) (c 2)))]
(+ x y)))
; Now we can call the continuation with whatever argument we want. The
; supplied argument takes the place of 2 in the above computation:
(run-cont (continuation 5))
(run-cont (continuation 42))
(run-cont (continuation -1))
; Next, a function that illustrates how a captured continuation can be
; used as an "emergency exit" out of a computation:
(defn sqrt-as-str [x]
(call-cc
(fn [k]
(domonad cont-m
[_ (m-when (< x 0) (k (str "negative argument " x)))]
(str (. Math sqrt x))))))
(run-cont (sqrt-as-str 2))
(run-cont (sqrt-as-str -2))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-01-21\"\n ",
"end": 97,
"score": 0.7367715835571289,
"start": 88,
"tag": "EMAIL",
"value": "wahpenayo"
},
{
"context": "-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-01-21\"\n :doc \"[Public ai",
"end": 114,
"score": 0.7248497009277344,
"start": 101,
"tag": "EMAIL",
"value": "gmail dot com"
},
{
"context": " benchmark data sampling code](https://github.com/szilard/benchm-ml/blob/master/0-init/2-gendata.txt)\n ",
"end": 664,
"score": 0.9988123774528503,
"start": 657,
"tag": "USERNAME",
"value": "szilard"
},
{
"context": "el.\n See [Issue 33](https://github.com/szilard/benchm-ml/issues/33).\n <p>\n ",
"end": 1067,
"score": 0.9987618327140808,
"start": 1060,
"tag": "USERNAME",
"value": "szilard"
}
] | src/main/clojure/taigabench/ontime/data.clj | wahpenayo/taigabench | 0 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "wahpenayo at gmail dot com"
:date "2018-01-21"
:doc "[Public airline ontime data for benchmarking](http://stat-computing.org/dataexpo/2009/).
<p>
<b>Note:</b>Using attributes mostly as defined as in
[BENCHMARKING RANDOM FOREST IMPLEMENTATIONS](http://datascience.la/benchmarking-random-forest-implementations/):
a subset of possible predictors and departure delay
greater than 15 minutes as the outcome.
<p>
The [original benchmark data sampling code](https://github.com/szilard/benchm-ml/blob/master/0-init/2-gendata.txt)
appears to use actual departure time as a predictor,
which would make the model useless for predicting
departure delay, since if you know the actual departure
time and the scheduled departure time, you can
compute the delay without any model.
See [Issue 33](https://github.com/szilard/benchm-ml/issues/33).
<p>
Here, I've replaced `DepTime` (actual departure time,
unknownable when a prediction would be useful)
by `CRSDepTime`, the scheduled departure time.
<p>
I've added scheduled arrival and elapsed times as
predictors." }
taigabench.ontime.data
(:require [clojure.string :as s]
[clojure.java.io :as io]
[zana.api :as z]
[taiga.api :as taiga])
(:import [java.time DayOfWeek LocalDate Month]
[org.apache.commons.math3.distribution
RealDistribution]
[clojure.lang IFn$OD]
[taigabench.java.ontime Airline Airport DayOfMonth]))
;;----------------------------------------------------------------
(defn- parse-double ^double [^String s]
(if (= "NA" s)
Double/NaN
(Double/parseDouble s)))
;;----------------------------------------------------------------
(defn- parse-hhmm ^double [^String s]
(if (= "NA" s)
Double/NaN
(let [nh (- (.length s) 2)
h (double (if (< 0 nh)
(Integer/parseInt (subs s 0 nh))
0.0))
m (double (Integer/parseInt
(if (< 0 nh)
(subs s nh)
s)))]
(assert (<= 0 h 24.0) (pr-str s))
;; some bad data, eg "2096"
#_(assert (<= 0 m 59.0) (pr-str s))
(double (+ (* 60.0 h) m)))))
(defn- parse-dayofyear
"Original data doesn't have `dayofyear`."
^double [tuple _]
(let [doy (:dayofyear tuple)]
(if doy
(parse-double doy)
;; assuming no missing data
(let [y (int (Double/parseDouble (:year tuple)))
m (int (Double/parseDouble (:month tuple)))
d (int (Double/parseDouble (:dayofmonth tuple)))]
(.getDayOfYear (LocalDate/of y m d))))))
(defn- parse-daysaftermar1
"Original data doesn't have `daysaftermar1`."
^double [tuple _]
(let [dam1 (:daysaftermar1 tuple)]
(if dam1
(parse-double dam1)
;; assuming no missing data
(let [y (int (Double/parseDouble (:year tuple)))
m (int (Double/parseDouble (:month tuple)))
d (int (Double/parseDouble (:dayofmonth tuple)))
doy (.getDayOfYear (LocalDate/of y m d))
mar1 (.getDayOfYear (LocalDate/of y 3 1))]
(mod (- doy mar1) (int 365))))))
(defn- parse-cmonth ^Month [tuple _]
(let [x (:cmonth tuple)]
(if x
(Month/valueOf x)
(Month/of (Integer/parseInt (:month tuple))))))
(defn- parse-cdayofweek ^DayOfWeek [tuple _]
(let [x (:cdayofweek tuple)]
(if x
(DayOfWeek/valueOf x)
(DayOfWeek/of (Integer/parseInt(:dayofweek tuple))))))
(defn- parse-cdayofmonth ^DayOfMonth [tuple _]
(let [x (:cdayofmonth tuple)]
(if x
(DayOfMonth/valueOf x)
(DayOfMonth/of (Integer/parseInt (:dayofmonth tuple))))))
(defn- parse-carrier ^Airline [tuple _]
(let [^String name (:uniquecarrier tuple)
^String name (if (.startsWith name "9")
(str "_" name)
name)]
(Airline/valueOf name)))
(defn- parse-airport ^Airport [^String airport]
(Airport/valueOf airport))
;; 152 min is 99% of non-canceled flights
;; try 1 hour for cancelled/diverted/missing
(def ^{:private true :tag Double/TYPE} CANCELLED-DELAY (* 2.0 60))
(defn- parse-arrdelay
(^double [tuple]
;; Treating cancelled/diverted as XXX hour delay,
;; but should be until actual arrival of next available flight
;; (with seats).
(let [arrdelay (:arrdelay tuple)]
(if (and arrdelay (not= "NA" arrdelay))
(parse-double arrdelay)
#_(double CANCELLED-DELAY)
;; treat misssing differently from cancelled/diverted
(let [cancelled (:cancelled tuple)
diverted (:diverted tuple)]
(if (or (not= "0" cancelled) (not= "0" diverted))
(double CANCELLED-DELAY)
Double/NaN ;; missing
#_(throw (IllegalArgumentException.
(str "can't parse:\n"
(z/pprint-map-str tuple)))))))))
(^double [tuple _] (parse-arrdelay tuple)))
(defn- parse-arr-delayed-15min ^double [tuple _]
(let [delay (parse-arrdelay tuple)]
(if (< delay 15.0)
0.0
1.0)))
(defn- rot ^double [^double t]
(rem (+ t (* 21.0 60.0)) (* 24.0 60.0)))
;;----------------------------------------------------------------
(z/define-datum Ontime
[^float [month (fn mon ^double [tuple _]
(parse-double (:month tuple)))]
^float [rotmonth (fn mon ^double [tuple _]
(rem (+ (parse-double (:month tuple)) 6.0) 12.0))]
^float [dayofmonth (fn dom ^double [tuple _]
(parse-double (:dayofmonth tuple)))]
^float [dayofweek (fn dow ^double [tuple _]
(parse-double (:dayofweek tuple)))]
^float [dayofyear parse-dayofyear]
^float [daysaftermar1 parse-daysaftermar1]
;; TODO: rotate as periodicity hack?
^float [crsdeptime (fn dep ^double [tuple _]
(parse-hhmm (:crsdeptime tuple)))]
^float [rotdeptime (fn rotdep ^double [tuple _]
(rot (parse-hhmm (:crsdeptime tuple))))]
^float [crsarrtime (fn arr ^double [tuple _]
(parse-hhmm (:crsarrtime tuple)))]
^float [rotarrtime (fn rotarr ^double [tuple _]
(rot (parse-hhmm (:crsarrtime tuple))))]
^float [crselapsedtime (fn elapsed ^double [tuple _]
(let [elapsed
(parse-double
(:crselapsedtime tuple))]
(if (Double/isNaN elapsed)
;; NOTE: NOT CORRECT!
;; scheculed times are in local
;; zones, need to convert to UTC,
;; which requires timezone
;; per airport, and correct DST.
;; Should missing scheduled
;; elapsed times be
;; dropped meanwhile?
(- (parse-hhmm
(:crsarrtime tuple))
(parse-hhmm
(:crsdeptime tuple)))
elapsed)))]
^float [distance (fn dist ^double [tuple _]
(parse-double (:distance tuple)))]
^java.time.Month [cmonth parse-cmonth]
;;^taigabench.java.ontime.DayOfMonth [cdayofmonth parse-cdayofmonth]
^java.time.DayOfWeek [cdayofweek parse-cdayofweek]
^taigabench.java.ontime.Airline [uniquecarrier parse-carrier]
^taigabench.java.ontime.Airport [origin
(fn origin [tuple _]
(parse-airport
(:origin tuple)))]
^taigabench.java.ontime.Airport [dest
(fn dest [tuple _]
(parse-airport
(:dest tuple)))]
^float [arrdelay parse-arrdelay]
^float [arr-delayed-15min parse-arr-delayed-15min]
^float prediction
^org.apache.commons.math3.distribution.RealDistribution
predictedDistribution])
;;----------------------------------------------------------------
(def predictors
"An attribute map for Taiga training/prediction."
(into {} (map #(vector (keyword (z/name %)) %)
[month rotmonth
dayofmonth dayofweek dayofyear daysaftermar1
crsdeptime crsarrtime rotdeptime rotarrtime
crselapsedtime distance
cmonth #_cdayofmonth cdayofweek
uniquecarrier origin dest])))
(def l2-attributes
"An attribute map for Taiga training/prediction, including
<code>:ground-truth</code> and <code>:prediction</code>."
(assoc
predictors
:ground-truth arrdelay
:prediction prediction))
(def qcost-attributes
"An attribute map for Taiga training/prediction, including
<code>:ground-truth</code> and <code>:prediction</code>."
(assoc
predictors
:ground-truth arrdelay
:prediction predictedDistribution))
(def classify-attributes
"An attribute map for Taiga training/prediction, including
<code>:ground-truth</code> and <code>:prediction</code>."
(assoc
predictors
:ground-truth arr-delayed-15min
:prediction prediction))
(def csv-attributes
"A list of attributes to write to sampled data files."
(sort-by
z/name
(conj (vals predictors) arrdelay)))
;;----------------------------------------------------------------
(defn raw-data-file ^java.io.File [year]
(io/file "data" "ontime" (str year ".csv.bz2")))
(defn read-raw-data ^Iterable [year]
(read-tsv-file (raw-data-file year) #"\,"))
;;----------------------------------------------------------------
;; TODO: fix z/define-datum io so round trip csv <-> data
;; consistency is easy to ensure, also save writing and reading
;; redundant attributes (categorial and numerical).
(defn- data-file ^java.io.File [fname ext]
(io/file "data" "ontime" (str fname "." ext)))
(def ^{:private true :tag String} csv-header
(s/join "," (map z/name csv-attributes)))
(defn- to-string
"The `float` valued attributes should really be `int`
(except for the prediction attributes, which aren't written)."
[x r]
(str
(if (instance? IFn$OD x)
(int (.invokePrim ^IFn$OD x r))
(x r)
#_(let [xr (x r)]
(cond ;;(instance? Airline xr) xr
;;(instance? Airport xr) xr
(instance? DayOfMonth xr) (.getValue ^DayOfMonth xr)
(instance? DayOfWeek xr) (.getValue ^DayOfWeek xr)
(instance? Month xr) (.getValue ^Month xr)
:else xr)))))
(defn- csv-line ^String [^Ontime r]
(s/join "," (mapv str (mapv #(to-string % r) csv-attributes))))
(defn write-data-file [^Iterable data ^String prefix]
(with-open [w (z/print-writer (data-file prefix "csv.gz"))]
(.println w csv-header)
(z/mapc #(.println w (csv-line %)) data)))
(defn read-data-file ^Iterable [^String prefix]
(read-tsv-file (data-file prefix "csv.gz") #"\,"))
;;----------------------------------------------------------------
(defn output-file ^java.io.File [problem fname ext]
(let [f (io/file "output" problem "ontime" (str fname "." ext))]
(io/make-parents f)
f))
(defn results-file ^java.io.File [problem fname]
(let [f (output-file fname "results.csv")]
(io/make-parents f)
f))
;;----------------------------------------------------------------
;; common settings for all models
(def prototype
{:csv-reader #(read-tsv-file % #"\,")
:bin-reader read-binary-file
:bin-writer write-binary-file
:mincount 255
:nterms 127
:maxdepth 1024})
;;----------------------------------------------------------------
| 65108 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<EMAIL> at <EMAIL>"
:date "2018-01-21"
:doc "[Public airline ontime data for benchmarking](http://stat-computing.org/dataexpo/2009/).
<p>
<b>Note:</b>Using attributes mostly as defined as in
[BENCHMARKING RANDOM FOREST IMPLEMENTATIONS](http://datascience.la/benchmarking-random-forest-implementations/):
a subset of possible predictors and departure delay
greater than 15 minutes as the outcome.
<p>
The [original benchmark data sampling code](https://github.com/szilard/benchm-ml/blob/master/0-init/2-gendata.txt)
appears to use actual departure time as a predictor,
which would make the model useless for predicting
departure delay, since if you know the actual departure
time and the scheduled departure time, you can
compute the delay without any model.
See [Issue 33](https://github.com/szilard/benchm-ml/issues/33).
<p>
Here, I've replaced `DepTime` (actual departure time,
unknownable when a prediction would be useful)
by `CRSDepTime`, the scheduled departure time.
<p>
I've added scheduled arrival and elapsed times as
predictors." }
taigabench.ontime.data
(:require [clojure.string :as s]
[clojure.java.io :as io]
[zana.api :as z]
[taiga.api :as taiga])
(:import [java.time DayOfWeek LocalDate Month]
[org.apache.commons.math3.distribution
RealDistribution]
[clojure.lang IFn$OD]
[taigabench.java.ontime Airline Airport DayOfMonth]))
;;----------------------------------------------------------------
(defn- parse-double ^double [^String s]
(if (= "NA" s)
Double/NaN
(Double/parseDouble s)))
;;----------------------------------------------------------------
(defn- parse-hhmm ^double [^String s]
(if (= "NA" s)
Double/NaN
(let [nh (- (.length s) 2)
h (double (if (< 0 nh)
(Integer/parseInt (subs s 0 nh))
0.0))
m (double (Integer/parseInt
(if (< 0 nh)
(subs s nh)
s)))]
(assert (<= 0 h 24.0) (pr-str s))
;; some bad data, eg "2096"
#_(assert (<= 0 m 59.0) (pr-str s))
(double (+ (* 60.0 h) m)))))
(defn- parse-dayofyear
"Original data doesn't have `dayofyear`."
^double [tuple _]
(let [doy (:dayofyear tuple)]
(if doy
(parse-double doy)
;; assuming no missing data
(let [y (int (Double/parseDouble (:year tuple)))
m (int (Double/parseDouble (:month tuple)))
d (int (Double/parseDouble (:dayofmonth tuple)))]
(.getDayOfYear (LocalDate/of y m d))))))
(defn- parse-daysaftermar1
"Original data doesn't have `daysaftermar1`."
^double [tuple _]
(let [dam1 (:daysaftermar1 tuple)]
(if dam1
(parse-double dam1)
;; assuming no missing data
(let [y (int (Double/parseDouble (:year tuple)))
m (int (Double/parseDouble (:month tuple)))
d (int (Double/parseDouble (:dayofmonth tuple)))
doy (.getDayOfYear (LocalDate/of y m d))
mar1 (.getDayOfYear (LocalDate/of y 3 1))]
(mod (- doy mar1) (int 365))))))
(defn- parse-cmonth ^Month [tuple _]
(let [x (:cmonth tuple)]
(if x
(Month/valueOf x)
(Month/of (Integer/parseInt (:month tuple))))))
(defn- parse-cdayofweek ^DayOfWeek [tuple _]
(let [x (:cdayofweek tuple)]
(if x
(DayOfWeek/valueOf x)
(DayOfWeek/of (Integer/parseInt(:dayofweek tuple))))))
(defn- parse-cdayofmonth ^DayOfMonth [tuple _]
(let [x (:cdayofmonth tuple)]
(if x
(DayOfMonth/valueOf x)
(DayOfMonth/of (Integer/parseInt (:dayofmonth tuple))))))
(defn- parse-carrier ^Airline [tuple _]
(let [^String name (:uniquecarrier tuple)
^String name (if (.startsWith name "9")
(str "_" name)
name)]
(Airline/valueOf name)))
(defn- parse-airport ^Airport [^String airport]
(Airport/valueOf airport))
;; 152 min is 99% of non-canceled flights
;; try 1 hour for cancelled/diverted/missing
(def ^{:private true :tag Double/TYPE} CANCELLED-DELAY (* 2.0 60))
(defn- parse-arrdelay
(^double [tuple]
;; Treating cancelled/diverted as XXX hour delay,
;; but should be until actual arrival of next available flight
;; (with seats).
(let [arrdelay (:arrdelay tuple)]
(if (and arrdelay (not= "NA" arrdelay))
(parse-double arrdelay)
#_(double CANCELLED-DELAY)
;; treat misssing differently from cancelled/diverted
(let [cancelled (:cancelled tuple)
diverted (:diverted tuple)]
(if (or (not= "0" cancelled) (not= "0" diverted))
(double CANCELLED-DELAY)
Double/NaN ;; missing
#_(throw (IllegalArgumentException.
(str "can't parse:\n"
(z/pprint-map-str tuple)))))))))
(^double [tuple _] (parse-arrdelay tuple)))
(defn- parse-arr-delayed-15min ^double [tuple _]
(let [delay (parse-arrdelay tuple)]
(if (< delay 15.0)
0.0
1.0)))
(defn- rot ^double [^double t]
(rem (+ t (* 21.0 60.0)) (* 24.0 60.0)))
;;----------------------------------------------------------------
(z/define-datum Ontime
[^float [month (fn mon ^double [tuple _]
(parse-double (:month tuple)))]
^float [rotmonth (fn mon ^double [tuple _]
(rem (+ (parse-double (:month tuple)) 6.0) 12.0))]
^float [dayofmonth (fn dom ^double [tuple _]
(parse-double (:dayofmonth tuple)))]
^float [dayofweek (fn dow ^double [tuple _]
(parse-double (:dayofweek tuple)))]
^float [dayofyear parse-dayofyear]
^float [daysaftermar1 parse-daysaftermar1]
;; TODO: rotate as periodicity hack?
^float [crsdeptime (fn dep ^double [tuple _]
(parse-hhmm (:crsdeptime tuple)))]
^float [rotdeptime (fn rotdep ^double [tuple _]
(rot (parse-hhmm (:crsdeptime tuple))))]
^float [crsarrtime (fn arr ^double [tuple _]
(parse-hhmm (:crsarrtime tuple)))]
^float [rotarrtime (fn rotarr ^double [tuple _]
(rot (parse-hhmm (:crsarrtime tuple))))]
^float [crselapsedtime (fn elapsed ^double [tuple _]
(let [elapsed
(parse-double
(:crselapsedtime tuple))]
(if (Double/isNaN elapsed)
;; NOTE: NOT CORRECT!
;; scheculed times are in local
;; zones, need to convert to UTC,
;; which requires timezone
;; per airport, and correct DST.
;; Should missing scheduled
;; elapsed times be
;; dropped meanwhile?
(- (parse-hhmm
(:crsarrtime tuple))
(parse-hhmm
(:crsdeptime tuple)))
elapsed)))]
^float [distance (fn dist ^double [tuple _]
(parse-double (:distance tuple)))]
^java.time.Month [cmonth parse-cmonth]
;;^taigabench.java.ontime.DayOfMonth [cdayofmonth parse-cdayofmonth]
^java.time.DayOfWeek [cdayofweek parse-cdayofweek]
^taigabench.java.ontime.Airline [uniquecarrier parse-carrier]
^taigabench.java.ontime.Airport [origin
(fn origin [tuple _]
(parse-airport
(:origin tuple)))]
^taigabench.java.ontime.Airport [dest
(fn dest [tuple _]
(parse-airport
(:dest tuple)))]
^float [arrdelay parse-arrdelay]
^float [arr-delayed-15min parse-arr-delayed-15min]
^float prediction
^org.apache.commons.math3.distribution.RealDistribution
predictedDistribution])
;;----------------------------------------------------------------
(def predictors
"An attribute map for Taiga training/prediction."
(into {} (map #(vector (keyword (z/name %)) %)
[month rotmonth
dayofmonth dayofweek dayofyear daysaftermar1
crsdeptime crsarrtime rotdeptime rotarrtime
crselapsedtime distance
cmonth #_cdayofmonth cdayofweek
uniquecarrier origin dest])))
(def l2-attributes
"An attribute map for Taiga training/prediction, including
<code>:ground-truth</code> and <code>:prediction</code>."
(assoc
predictors
:ground-truth arrdelay
:prediction prediction))
(def qcost-attributes
"An attribute map for Taiga training/prediction, including
<code>:ground-truth</code> and <code>:prediction</code>."
(assoc
predictors
:ground-truth arrdelay
:prediction predictedDistribution))
(def classify-attributes
"An attribute map for Taiga training/prediction, including
<code>:ground-truth</code> and <code>:prediction</code>."
(assoc
predictors
:ground-truth arr-delayed-15min
:prediction prediction))
(def csv-attributes
"A list of attributes to write to sampled data files."
(sort-by
z/name
(conj (vals predictors) arrdelay)))
;;----------------------------------------------------------------
(defn raw-data-file ^java.io.File [year]
(io/file "data" "ontime" (str year ".csv.bz2")))
(defn read-raw-data ^Iterable [year]
(read-tsv-file (raw-data-file year) #"\,"))
;;----------------------------------------------------------------
;; TODO: fix z/define-datum io so round trip csv <-> data
;; consistency is easy to ensure, also save writing and reading
;; redundant attributes (categorial and numerical).
(defn- data-file ^java.io.File [fname ext]
(io/file "data" "ontime" (str fname "." ext)))
(def ^{:private true :tag String} csv-header
(s/join "," (map z/name csv-attributes)))
(defn- to-string
"The `float` valued attributes should really be `int`
(except for the prediction attributes, which aren't written)."
[x r]
(str
(if (instance? IFn$OD x)
(int (.invokePrim ^IFn$OD x r))
(x r)
#_(let [xr (x r)]
(cond ;;(instance? Airline xr) xr
;;(instance? Airport xr) xr
(instance? DayOfMonth xr) (.getValue ^DayOfMonth xr)
(instance? DayOfWeek xr) (.getValue ^DayOfWeek xr)
(instance? Month xr) (.getValue ^Month xr)
:else xr)))))
(defn- csv-line ^String [^Ontime r]
(s/join "," (mapv str (mapv #(to-string % r) csv-attributes))))
(defn write-data-file [^Iterable data ^String prefix]
(with-open [w (z/print-writer (data-file prefix "csv.gz"))]
(.println w csv-header)
(z/mapc #(.println w (csv-line %)) data)))
(defn read-data-file ^Iterable [^String prefix]
(read-tsv-file (data-file prefix "csv.gz") #"\,"))
;;----------------------------------------------------------------
(defn output-file ^java.io.File [problem fname ext]
(let [f (io/file "output" problem "ontime" (str fname "." ext))]
(io/make-parents f)
f))
(defn results-file ^java.io.File [problem fname]
(let [f (output-file fname "results.csv")]
(io/make-parents f)
f))
;;----------------------------------------------------------------
;; common settings for all models
(def prototype
{:csv-reader #(read-tsv-file % #"\,")
:bin-reader read-binary-file
:bin-writer write-binary-file
:mincount 255
:nterms 127
:maxdepth 1024})
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:EMAIL:<EMAIL>END_PI at PI:EMAIL:<EMAIL>END_PI"
:date "2018-01-21"
:doc "[Public airline ontime data for benchmarking](http://stat-computing.org/dataexpo/2009/).
<p>
<b>Note:</b>Using attributes mostly as defined as in
[BENCHMARKING RANDOM FOREST IMPLEMENTATIONS](http://datascience.la/benchmarking-random-forest-implementations/):
a subset of possible predictors and departure delay
greater than 15 minutes as the outcome.
<p>
The [original benchmark data sampling code](https://github.com/szilard/benchm-ml/blob/master/0-init/2-gendata.txt)
appears to use actual departure time as a predictor,
which would make the model useless for predicting
departure delay, since if you know the actual departure
time and the scheduled departure time, you can
compute the delay without any model.
See [Issue 33](https://github.com/szilard/benchm-ml/issues/33).
<p>
Here, I've replaced `DepTime` (actual departure time,
unknownable when a prediction would be useful)
by `CRSDepTime`, the scheduled departure time.
<p>
I've added scheduled arrival and elapsed times as
predictors." }
taigabench.ontime.data
(:require [clojure.string :as s]
[clojure.java.io :as io]
[zana.api :as z]
[taiga.api :as taiga])
(:import [java.time DayOfWeek LocalDate Month]
[org.apache.commons.math3.distribution
RealDistribution]
[clojure.lang IFn$OD]
[taigabench.java.ontime Airline Airport DayOfMonth]))
;;----------------------------------------------------------------
(defn- parse-double ^double [^String s]
(if (= "NA" s)
Double/NaN
(Double/parseDouble s)))
;;----------------------------------------------------------------
(defn- parse-hhmm ^double [^String s]
(if (= "NA" s)
Double/NaN
(let [nh (- (.length s) 2)
h (double (if (< 0 nh)
(Integer/parseInt (subs s 0 nh))
0.0))
m (double (Integer/parseInt
(if (< 0 nh)
(subs s nh)
s)))]
(assert (<= 0 h 24.0) (pr-str s))
;; some bad data, eg "2096"
#_(assert (<= 0 m 59.0) (pr-str s))
(double (+ (* 60.0 h) m)))))
(defn- parse-dayofyear
"Original data doesn't have `dayofyear`."
^double [tuple _]
(let [doy (:dayofyear tuple)]
(if doy
(parse-double doy)
;; assuming no missing data
(let [y (int (Double/parseDouble (:year tuple)))
m (int (Double/parseDouble (:month tuple)))
d (int (Double/parseDouble (:dayofmonth tuple)))]
(.getDayOfYear (LocalDate/of y m d))))))
(defn- parse-daysaftermar1
"Original data doesn't have `daysaftermar1`."
^double [tuple _]
(let [dam1 (:daysaftermar1 tuple)]
(if dam1
(parse-double dam1)
;; assuming no missing data
(let [y (int (Double/parseDouble (:year tuple)))
m (int (Double/parseDouble (:month tuple)))
d (int (Double/parseDouble (:dayofmonth tuple)))
doy (.getDayOfYear (LocalDate/of y m d))
mar1 (.getDayOfYear (LocalDate/of y 3 1))]
(mod (- doy mar1) (int 365))))))
(defn- parse-cmonth ^Month [tuple _]
(let [x (:cmonth tuple)]
(if x
(Month/valueOf x)
(Month/of (Integer/parseInt (:month tuple))))))
(defn- parse-cdayofweek ^DayOfWeek [tuple _]
(let [x (:cdayofweek tuple)]
(if x
(DayOfWeek/valueOf x)
(DayOfWeek/of (Integer/parseInt(:dayofweek tuple))))))
(defn- parse-cdayofmonth ^DayOfMonth [tuple _]
(let [x (:cdayofmonth tuple)]
(if x
(DayOfMonth/valueOf x)
(DayOfMonth/of (Integer/parseInt (:dayofmonth tuple))))))
(defn- parse-carrier ^Airline [tuple _]
(let [^String name (:uniquecarrier tuple)
^String name (if (.startsWith name "9")
(str "_" name)
name)]
(Airline/valueOf name)))
(defn- parse-airport ^Airport [^String airport]
(Airport/valueOf airport))
;; 152 min is 99% of non-canceled flights
;; try 1 hour for cancelled/diverted/missing
(def ^{:private true :tag Double/TYPE} CANCELLED-DELAY (* 2.0 60))
(defn- parse-arrdelay
(^double [tuple]
;; Treating cancelled/diverted as XXX hour delay,
;; but should be until actual arrival of next available flight
;; (with seats).
(let [arrdelay (:arrdelay tuple)]
(if (and arrdelay (not= "NA" arrdelay))
(parse-double arrdelay)
#_(double CANCELLED-DELAY)
;; treat misssing differently from cancelled/diverted
(let [cancelled (:cancelled tuple)
diverted (:diverted tuple)]
(if (or (not= "0" cancelled) (not= "0" diverted))
(double CANCELLED-DELAY)
Double/NaN ;; missing
#_(throw (IllegalArgumentException.
(str "can't parse:\n"
(z/pprint-map-str tuple)))))))))
(^double [tuple _] (parse-arrdelay tuple)))
(defn- parse-arr-delayed-15min ^double [tuple _]
(let [delay (parse-arrdelay tuple)]
(if (< delay 15.0)
0.0
1.0)))
(defn- rot ^double [^double t]
(rem (+ t (* 21.0 60.0)) (* 24.0 60.0)))
;;----------------------------------------------------------------
(z/define-datum Ontime
[^float [month (fn mon ^double [tuple _]
(parse-double (:month tuple)))]
^float [rotmonth (fn mon ^double [tuple _]
(rem (+ (parse-double (:month tuple)) 6.0) 12.0))]
^float [dayofmonth (fn dom ^double [tuple _]
(parse-double (:dayofmonth tuple)))]
^float [dayofweek (fn dow ^double [tuple _]
(parse-double (:dayofweek tuple)))]
^float [dayofyear parse-dayofyear]
^float [daysaftermar1 parse-daysaftermar1]
;; TODO: rotate as periodicity hack?
^float [crsdeptime (fn dep ^double [tuple _]
(parse-hhmm (:crsdeptime tuple)))]
^float [rotdeptime (fn rotdep ^double [tuple _]
(rot (parse-hhmm (:crsdeptime tuple))))]
^float [crsarrtime (fn arr ^double [tuple _]
(parse-hhmm (:crsarrtime tuple)))]
^float [rotarrtime (fn rotarr ^double [tuple _]
(rot (parse-hhmm (:crsarrtime tuple))))]
^float [crselapsedtime (fn elapsed ^double [tuple _]
(let [elapsed
(parse-double
(:crselapsedtime tuple))]
(if (Double/isNaN elapsed)
;; NOTE: NOT CORRECT!
;; scheculed times are in local
;; zones, need to convert to UTC,
;; which requires timezone
;; per airport, and correct DST.
;; Should missing scheduled
;; elapsed times be
;; dropped meanwhile?
(- (parse-hhmm
(:crsarrtime tuple))
(parse-hhmm
(:crsdeptime tuple)))
elapsed)))]
^float [distance (fn dist ^double [tuple _]
(parse-double (:distance tuple)))]
^java.time.Month [cmonth parse-cmonth]
;;^taigabench.java.ontime.DayOfMonth [cdayofmonth parse-cdayofmonth]
^java.time.DayOfWeek [cdayofweek parse-cdayofweek]
^taigabench.java.ontime.Airline [uniquecarrier parse-carrier]
^taigabench.java.ontime.Airport [origin
(fn origin [tuple _]
(parse-airport
(:origin tuple)))]
^taigabench.java.ontime.Airport [dest
(fn dest [tuple _]
(parse-airport
(:dest tuple)))]
^float [arrdelay parse-arrdelay]
^float [arr-delayed-15min parse-arr-delayed-15min]
^float prediction
^org.apache.commons.math3.distribution.RealDistribution
predictedDistribution])
;;----------------------------------------------------------------
(def predictors
"An attribute map for Taiga training/prediction."
(into {} (map #(vector (keyword (z/name %)) %)
[month rotmonth
dayofmonth dayofweek dayofyear daysaftermar1
crsdeptime crsarrtime rotdeptime rotarrtime
crselapsedtime distance
cmonth #_cdayofmonth cdayofweek
uniquecarrier origin dest])))
(def l2-attributes
"An attribute map for Taiga training/prediction, including
<code>:ground-truth</code> and <code>:prediction</code>."
(assoc
predictors
:ground-truth arrdelay
:prediction prediction))
(def qcost-attributes
"An attribute map for Taiga training/prediction, including
<code>:ground-truth</code> and <code>:prediction</code>."
(assoc
predictors
:ground-truth arrdelay
:prediction predictedDistribution))
(def classify-attributes
"An attribute map for Taiga training/prediction, including
<code>:ground-truth</code> and <code>:prediction</code>."
(assoc
predictors
:ground-truth arr-delayed-15min
:prediction prediction))
(def csv-attributes
"A list of attributes to write to sampled data files."
(sort-by
z/name
(conj (vals predictors) arrdelay)))
;;----------------------------------------------------------------
(defn raw-data-file ^java.io.File [year]
(io/file "data" "ontime" (str year ".csv.bz2")))
(defn read-raw-data ^Iterable [year]
(read-tsv-file (raw-data-file year) #"\,"))
;;----------------------------------------------------------------
;; TODO: fix z/define-datum io so round trip csv <-> data
;; consistency is easy to ensure, also save writing and reading
;; redundant attributes (categorial and numerical).
(defn- data-file ^java.io.File [fname ext]
(io/file "data" "ontime" (str fname "." ext)))
(def ^{:private true :tag String} csv-header
(s/join "," (map z/name csv-attributes)))
(defn- to-string
"The `float` valued attributes should really be `int`
(except for the prediction attributes, which aren't written)."
[x r]
(str
(if (instance? IFn$OD x)
(int (.invokePrim ^IFn$OD x r))
(x r)
#_(let [xr (x r)]
(cond ;;(instance? Airline xr) xr
;;(instance? Airport xr) xr
(instance? DayOfMonth xr) (.getValue ^DayOfMonth xr)
(instance? DayOfWeek xr) (.getValue ^DayOfWeek xr)
(instance? Month xr) (.getValue ^Month xr)
:else xr)))))
(defn- csv-line ^String [^Ontime r]
(s/join "," (mapv str (mapv #(to-string % r) csv-attributes))))
(defn write-data-file [^Iterable data ^String prefix]
(with-open [w (z/print-writer (data-file prefix "csv.gz"))]
(.println w csv-header)
(z/mapc #(.println w (csv-line %)) data)))
(defn read-data-file ^Iterable [^String prefix]
(read-tsv-file (data-file prefix "csv.gz") #"\,"))
;;----------------------------------------------------------------
(defn output-file ^java.io.File [problem fname ext]
(let [f (io/file "output" problem "ontime" (str fname "." ext))]
(io/make-parents f)
f))
(defn results-file ^java.io.File [problem fname]
(let [f (output-file fname "results.csv")]
(io/make-parents f)
f))
;;----------------------------------------------------------------
;; common settings for all models
(def prototype
{:csv-reader #(read-tsv-file % #"\,")
:bin-reader read-binary-file
:bin-writer write-binary-file
:mincount 255
:nterms 127
:maxdepth 1024})
;;----------------------------------------------------------------
|
[
{
"context": " (r/atom true))\n(def names (r/atom [{:first-name \"Hans\" :surname \"Emil\"}\n {:first-nam",
"end": 696,
"score": 0.999537467956543,
"start": 692,
"tag": "NAME",
"value": "Hans"
},
{
"context": "(def names (r/atom [{:first-name \"Hans\" :surname \"Emil\"}\n {:first-name \"Max\" :surname",
"end": 712,
"score": 0.9981578588485718,
"start": 708,
"tag": "NAME",
"value": "Emil"
},
{
"context": "surname \"Emil\"}\n {:first-name \"Max\" :surname \"Mustermann\"}\n {:fir",
"end": 752,
"score": 0.999695897102356,
"start": 749,
"tag": "NAME",
"value": "Max"
},
{
"context": "\n {:first-name \"Max\" :surname \"Mustermann\"}\n {:first-name \"Roman\" :surna",
"end": 774,
"score": 0.9969168305397034,
"start": 764,
"tag": "NAME",
"value": "Mustermann"
},
{
"context": "e \"Mustermann\"}\n {:first-name \"Roman\" :surname \"Tisch\"}]))\n(def list-node (r/atom nil)",
"end": 816,
"score": 0.9994259476661682,
"start": 811,
"tag": "NAME",
"value": "Roman"
},
{
"context": " {:first-name \"Roman\" :surname \"Tisch\"}]))\n(def list-node (r/atom nil))\n",
"end": 833,
"score": 0.9976577758789062,
"start": 828,
"tag": "NAME",
"value": "Tisch"
}
] | src/site/state.cljs | alex-sumner/seven-guis | 0 | (ns site.state
(:require [reagent.core :as r]))
;;task 1 counter
(def counter (r/atom 0))
;;task 2 temperature converter
(def celcius (r/atom 0))
(def farenheit (r/atom 32))
;;task 3 flight booker
(def journey-type (r/atom "One Way"))
(def departure (r/atom ""))
(def return (r/atom ""))
(def return-disabled (r/atom true))
(def book-disabled (r/atom true))
(def booking-modal-showing (r/atom false))
;;task 4 timer
(def interval (r/atom 30))
;;task 5 crud
(def name-filter (r/atom ""))
(def first-name (r/atom ""))
(def surname (r/atom ""))
(def create-disabled (r/atom false))
(def update-disabled (r/atom true))
(def delete-disabled (r/atom true))
(def names (r/atom [{:first-name "Hans" :surname "Emil"}
{:first-name "Max" :surname "Mustermann"}
{:first-name "Roman" :surname "Tisch"}]))
(def list-node (r/atom nil))
| 116192 | (ns site.state
(:require [reagent.core :as r]))
;;task 1 counter
(def counter (r/atom 0))
;;task 2 temperature converter
(def celcius (r/atom 0))
(def farenheit (r/atom 32))
;;task 3 flight booker
(def journey-type (r/atom "One Way"))
(def departure (r/atom ""))
(def return (r/atom ""))
(def return-disabled (r/atom true))
(def book-disabled (r/atom true))
(def booking-modal-showing (r/atom false))
;;task 4 timer
(def interval (r/atom 30))
;;task 5 crud
(def name-filter (r/atom ""))
(def first-name (r/atom ""))
(def surname (r/atom ""))
(def create-disabled (r/atom false))
(def update-disabled (r/atom true))
(def delete-disabled (r/atom true))
(def names (r/atom [{:first-name "<NAME>" :surname "<NAME>"}
{:first-name "<NAME>" :surname "<NAME>"}
{:first-name "<NAME>" :surname "<NAME>"}]))
(def list-node (r/atom nil))
| true | (ns site.state
(:require [reagent.core :as r]))
;;task 1 counter
(def counter (r/atom 0))
;;task 2 temperature converter
(def celcius (r/atom 0))
(def farenheit (r/atom 32))
;;task 3 flight booker
(def journey-type (r/atom "One Way"))
(def departure (r/atom ""))
(def return (r/atom ""))
(def return-disabled (r/atom true))
(def book-disabled (r/atom true))
(def booking-modal-showing (r/atom false))
;;task 4 timer
(def interval (r/atom 30))
;;task 5 crud
(def name-filter (r/atom ""))
(def first-name (r/atom ""))
(def surname (r/atom ""))
(def create-disabled (r/atom false))
(def update-disabled (r/atom true))
(def delete-disabled (r/atom true))
(def names (r/atom [{:first-name "PI:NAME:<NAME>END_PI" :surname "PI:NAME:<NAME>END_PI"}
{:first-name "PI:NAME:<NAME>END_PI" :surname "PI:NAME:<NAME>END_PI"}
{:first-name "PI:NAME:<NAME>END_PI" :surname "PI:NAME:<NAME>END_PI"}]))
(def list-node (r/atom nil))
|
[
{
"context": "strix-async {:group-key \"goo\"\n ",
"end": 11418,
"score": 0.52008455991745,
"start": 11415,
"tag": "KEY",
"value": "goo"
},
{
"context": " :command-key \"goo\"\n ",
"end": 11508,
"score": 0.610941469669342,
"start": 11505,
"tag": "KEY",
"value": "goo"
},
{
"context": "strix-async {:group-key \"goo\"\n ",
"end": 12409,
"score": 0.9581995010375977,
"start": 12406,
"tag": "KEY",
"value": "goo"
},
{
"context": " :command-key \"goo\"\n ",
"end": 12502,
"score": 0.9549922347068787,
"start": 12499,
"tag": "KEY",
"value": "goo"
},
{
"context": " :thread-pool-key \"goo\"\n ",
"end": 12595,
"score": 0.9275141954421997,
"start": 12592,
"tag": "KEY",
"value": "goo"
}
] | test/bulwark/core_test.clj | NNcrawler/bulwark | 0 | (ns bulwark.core-test
(:require [clojure.test :refer :all]
[bulwark.core :as bulwark]
[clojure.stacktrace :as stacktrace])
(:import (com.netflix.hystrix.exception HystrixRuntimeException)))
(defmacro catch-and-return
[& body]
`(try
~@body
(catch Exception e#
e#)))
(deftest with-hystrix-works
(testing "Successful call"
(let [fallback (fn [_]
"failure")
result (bulwark/with-hystrix {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback
:request-volume-threshold 20}
"success")]
(is (= "success" result))))
(testing "Successful call without a fallback"
(let [result (bulwark/with-hystrix {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:request-volume-threshold 20}
"success")]
(is (= "success" result))))
(testing "Fallback when exception is thrown"
(let [fallback (fn [{:keys [failed-execution-exception]}]
{:status "failure"
:exception failed-execution-exception})
result (bulwark/with-hystrix {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(throw (ex-info "foo" {:error "foo"}))
"success")]
(is (= "failure" (:status result)))
(is (= {:error "foo"}
(-> result
:exception
ex-data)))))
(testing "When an exception is thrown without a fallback"
(let [exception (catch-and-return
(bulwark/with-hystrix {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(throw (ex-info "foo" {:error "foo"}))
"success"))]
(is (= {:error "foo"}
(-> exception
stacktrace/root-cause
ex-data)))))
(testing "Fallback when body times out"
(let [fallback (fn [{:keys [response-timed-out?]}]
{:status "failure"
:response-timed-out? response-timed-out?})
result (bulwark/with-hystrix {:group-key "goo"
:command-key "goo"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(Thread/sleep 200)
"success")]
(is (= {:status "failure"
:response-timed-out? true}
result))))
(testing "When body times out without a fallback"
(is (thrown-with-msg? HystrixRuntimeException #"goo timed-out.*"
(bulwark/with-hystrix {:group-key "goo"
:command-key "goo"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(Thread/sleep 200)
"success")))))
(deftest with-hystrix-queue-works
(testing "Successful call"
(let [fallback (fn [_]
"failure")
result (bulwark/with-hystrix-async {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback
:request-volume-threshold 20}
{:status "success"
:response "success"})]
(is (= @result {:status "success"
:response "success"}))))
(testing "Successful call without request volume threshold config"
(let [fallback (fn [_]
"failure")
result (bulwark/with-hystrix-async {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
{:status "success"
:response "success"})]
(is (= @result {:status "success"
:response "success"}))))
(testing "Successful call without a fallback"
(let [result (bulwark/with-hystrix-async {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:request-volume-threshold 20}
{:status "success" :response "success"})]
(is (= @result {:status "success"
:response "success"}))))
(testing "Fallback when exception is thrown"
(let [fallback (fn [{:keys [failed-execution-exception]}]
{:status "failure" :response failed-execution-exception})
result (bulwark/with-hystrix-async {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(throw (ex-info "foo" {:error "foo"}))
"success")]
(is (= "failure"
(:status @result)))
(is (= {:error "foo"}
(ex-data (:response @result))))))
(testing "When an exception is thrown without a fallback"
(let [exception (try @(bulwark/with-hystrix-async {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(throw (ex-info "foo" {:error "foo"}))
"success")
(catch Exception e
e))]
(is (= {:error "foo"}
(-> exception
stacktrace/root-cause
ex-data)))))
(testing "Fallback when body times out"
(let [fallback (fn [{:keys [response-timed-out?]}]
{:status "failure"
:response-timed-out? response-timed-out?})
result (bulwark/with-hystrix-async {:group-key "goo"
:command-key "goo"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(Thread/sleep 200)
"success")]
(is (= {:status "failure"
:response-timed-out? true}
@result))))
(testing "When body times out without a fallback"
(let [exception (catch-and-return
@(bulwark/with-hystrix-async {:group-key "goo"
:command-key "goo"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(Thread/sleep 200)
"success"))]
(is (instance? HystrixRuntimeException (.getCause exception)))
(is (re-matches #"goo timed-out.*" (-> exception
(.getCause)
(.getMessage)))))))
| 114534 | (ns bulwark.core-test
(:require [clojure.test :refer :all]
[bulwark.core :as bulwark]
[clojure.stacktrace :as stacktrace])
(:import (com.netflix.hystrix.exception HystrixRuntimeException)))
(defmacro catch-and-return
[& body]
`(try
~@body
(catch Exception e#
e#)))
(deftest with-hystrix-works
(testing "Successful call"
(let [fallback (fn [_]
"failure")
result (bulwark/with-hystrix {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback
:request-volume-threshold 20}
"success")]
(is (= "success" result))))
(testing "Successful call without a fallback"
(let [result (bulwark/with-hystrix {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:request-volume-threshold 20}
"success")]
(is (= "success" result))))
(testing "Fallback when exception is thrown"
(let [fallback (fn [{:keys [failed-execution-exception]}]
{:status "failure"
:exception failed-execution-exception})
result (bulwark/with-hystrix {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(throw (ex-info "foo" {:error "foo"}))
"success")]
(is (= "failure" (:status result)))
(is (= {:error "foo"}
(-> result
:exception
ex-data)))))
(testing "When an exception is thrown without a fallback"
(let [exception (catch-and-return
(bulwark/with-hystrix {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(throw (ex-info "foo" {:error "foo"}))
"success"))]
(is (= {:error "foo"}
(-> exception
stacktrace/root-cause
ex-data)))))
(testing "Fallback when body times out"
(let [fallback (fn [{:keys [response-timed-out?]}]
{:status "failure"
:response-timed-out? response-timed-out?})
result (bulwark/with-hystrix {:group-key "goo"
:command-key "goo"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(Thread/sleep 200)
"success")]
(is (= {:status "failure"
:response-timed-out? true}
result))))
(testing "When body times out without a fallback"
(is (thrown-with-msg? HystrixRuntimeException #"goo timed-out.*"
(bulwark/with-hystrix {:group-key "goo"
:command-key "goo"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(Thread/sleep 200)
"success")))))
(deftest with-hystrix-queue-works
(testing "Successful call"
(let [fallback (fn [_]
"failure")
result (bulwark/with-hystrix-async {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback
:request-volume-threshold 20}
{:status "success"
:response "success"})]
(is (= @result {:status "success"
:response "success"}))))
(testing "Successful call without request volume threshold config"
(let [fallback (fn [_]
"failure")
result (bulwark/with-hystrix-async {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
{:status "success"
:response "success"})]
(is (= @result {:status "success"
:response "success"}))))
(testing "Successful call without a fallback"
(let [result (bulwark/with-hystrix-async {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:request-volume-threshold 20}
{:status "success" :response "success"})]
(is (= @result {:status "success"
:response "success"}))))
(testing "Fallback when exception is thrown"
(let [fallback (fn [{:keys [failed-execution-exception]}]
{:status "failure" :response failed-execution-exception})
result (bulwark/with-hystrix-async {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(throw (ex-info "foo" {:error "foo"}))
"success")]
(is (= "failure"
(:status @result)))
(is (= {:error "foo"}
(ex-data (:response @result))))))
(testing "When an exception is thrown without a fallback"
(let [exception (try @(bulwark/with-hystrix-async {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(throw (ex-info "foo" {:error "foo"}))
"success")
(catch Exception e
e))]
(is (= {:error "foo"}
(-> exception
stacktrace/root-cause
ex-data)))))
(testing "Fallback when body times out"
(let [fallback (fn [{:keys [response-timed-out?]}]
{:status "failure"
:response-timed-out? response-timed-out?})
result (bulwark/with-hystrix-async {:group-key "<KEY>"
:command-key "<KEY>"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(Thread/sleep 200)
"success")]
(is (= {:status "failure"
:response-timed-out? true}
@result))))
(testing "When body times out without a fallback"
(let [exception (catch-and-return
@(bulwark/with-hystrix-async {:group-key "<KEY>"
:command-key "<KEY>"
:thread-pool-key "<KEY>"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(Thread/sleep 200)
"success"))]
(is (instance? HystrixRuntimeException (.getCause exception)))
(is (re-matches #"goo timed-out.*" (-> exception
(.getCause)
(.getMessage)))))))
| true | (ns bulwark.core-test
(:require [clojure.test :refer :all]
[bulwark.core :as bulwark]
[clojure.stacktrace :as stacktrace])
(:import (com.netflix.hystrix.exception HystrixRuntimeException)))
(defmacro catch-and-return
[& body]
`(try
~@body
(catch Exception e#
e#)))
(deftest with-hystrix-works
(testing "Successful call"
(let [fallback (fn [_]
"failure")
result (bulwark/with-hystrix {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback
:request-volume-threshold 20}
"success")]
(is (= "success" result))))
(testing "Successful call without a fallback"
(let [result (bulwark/with-hystrix {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:request-volume-threshold 20}
"success")]
(is (= "success" result))))
(testing "Fallback when exception is thrown"
(let [fallback (fn [{:keys [failed-execution-exception]}]
{:status "failure"
:exception failed-execution-exception})
result (bulwark/with-hystrix {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(throw (ex-info "foo" {:error "foo"}))
"success")]
(is (= "failure" (:status result)))
(is (= {:error "foo"}
(-> result
:exception
ex-data)))))
(testing "When an exception is thrown without a fallback"
(let [exception (catch-and-return
(bulwark/with-hystrix {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(throw (ex-info "foo" {:error "foo"}))
"success"))]
(is (= {:error "foo"}
(-> exception
stacktrace/root-cause
ex-data)))))
(testing "Fallback when body times out"
(let [fallback (fn [{:keys [response-timed-out?]}]
{:status "failure"
:response-timed-out? response-timed-out?})
result (bulwark/with-hystrix {:group-key "goo"
:command-key "goo"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(Thread/sleep 200)
"success")]
(is (= {:status "failure"
:response-timed-out? true}
result))))
(testing "When body times out without a fallback"
(is (thrown-with-msg? HystrixRuntimeException #"goo timed-out.*"
(bulwark/with-hystrix {:group-key "goo"
:command-key "goo"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(Thread/sleep 200)
"success")))))
(deftest with-hystrix-queue-works
(testing "Successful call"
(let [fallback (fn [_]
"failure")
result (bulwark/with-hystrix-async {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback
:request-volume-threshold 20}
{:status "success"
:response "success"})]
(is (= @result {:status "success"
:response "success"}))))
(testing "Successful call without request volume threshold config"
(let [fallback (fn [_]
"failure")
result (bulwark/with-hystrix-async {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
{:status "success"
:response "success"})]
(is (= @result {:status "success"
:response "success"}))))
(testing "Successful call without a fallback"
(let [result (bulwark/with-hystrix-async {:group-key "foo"
:command-key "foo"
:thread-pool-key "foo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:request-volume-threshold 20}
{:status "success" :response "success"})]
(is (= @result {:status "success"
:response "success"}))))
(testing "Fallback when exception is thrown"
(let [fallback (fn [{:keys [failed-execution-exception]}]
{:status "failure" :response failed-execution-exception})
result (bulwark/with-hystrix-async {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(throw (ex-info "foo" {:error "foo"}))
"success")]
(is (= "failure"
(:status @result)))
(is (= {:error "foo"}
(ex-data (:response @result))))))
(testing "When an exception is thrown without a fallback"
(let [exception (try @(bulwark/with-hystrix-async {:group-key "bar"
:command-key "bar"
:thread-pool-key "bar"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(throw (ex-info "foo" {:error "foo"}))
"success")
(catch Exception e
e))]
(is (= {:error "foo"}
(-> exception
stacktrace/root-cause
ex-data)))))
(testing "Fallback when body times out"
(let [fallback (fn [{:keys [response-timed-out?]}]
{:status "failure"
:response-timed-out? response-timed-out?})
result (bulwark/with-hystrix-async {:group-key "PI:KEY:<KEY>END_PI"
:command-key "PI:KEY:<KEY>END_PI"
:thread-pool-key "goo"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100
:fallback-fn fallback}
(Thread/sleep 200)
"success")]
(is (= {:status "failure"
:response-timed-out? true}
@result))))
(testing "When body times out without a fallback"
(let [exception (catch-and-return
@(bulwark/with-hystrix-async {:group-key "PI:KEY:<KEY>END_PI"
:command-key "PI:KEY:<KEY>END_PI"
:thread-pool-key "PI:KEY:<KEY>END_PI"
:thread-count 2
:breaker-sleep-window-ms 500
:breaker-error-threshold-percentage 20
:execution-timeout-ms 100}
(Thread/sleep 200)
"success"))]
(is (instance? HystrixRuntimeException (.getCause exception)))
(is (re-matches #"goo timed-out.*" (-> exception
(.getCause)
(.getMessage)))))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.