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": "op\") [])\n (xor\n (seq\n (call \"12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e\" (\"op\" \"string_to_b58\") [\"12D3KooWSD5PToNiLQwKDXs", "end": 254, "score": 0.994979977607727, "start": 202, "tag": "KEY", "value": "12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e" }, { "context": "CwUt8BVUJEqCHcDe7P5h45e\" (\"op\" \"string_to_b58\") [\"12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e\"] k)\n (par\n (seq\n (cal", "end": 333, "score": 0.9967244863510132, "start": 281, "tag": "KEY", "value": "12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e" }, { "context": "k)\n (par\n (seq\n (call \"12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e\" (\"kad\" \"neighborhood\") [k [] []] nodes)\n ", "end": 438, "score": 0.992493212223053, "start": 386, "tag": "KEY", "value": "12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e" } ]
air/tests/test_module/issues/scripts/issue_177.clj
fluencelabs/aquavm
19
(xor (seq (seq (call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-) (new $res (seq (seq (seq (call -relay- ("op" "noop") []) (xor (seq (call "12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e" ("op" "string_to_b58") ["12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e"] k) (par (seq (call "12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e" ("kad" "neighborhood") [k [] []] nodes) (call %init_peer_id% ("op" "noop") []) ) (seq (fold nodes n (par (seq (xor (call n ("peer" "timestamp_ms") [] $res) (seq (call -relay- ("op" "noop") []) (call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 1]) ) ) (call %init_peer_id% ("op" "noop") []) ) (next n) ) ) (call %init_peer_id% ("op" "noop") []) ) ) ) (call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 2]) ) ) (par (call %init_peer_id% ("op" "identity") [$res.$.[19]!]) (call %init_peer_id% ("peer" "timeout") [1000 "timeout"]) ) ) (call %init_peer_id% ("op" "identity") [$res] res-fix) ) ) ) (call %init_peer_id% ("--after-callback-srv-service--" "print-and-stop") [res-fix nodes]) ) (call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 3]) )
94869
(xor (seq (seq (call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-) (new $res (seq (seq (seq (call -relay- ("op" "noop") []) (xor (seq (call "<KEY>" ("op" "string_to_b58") ["<KEY>"] k) (par (seq (call "<KEY>" ("kad" "neighborhood") [k [] []] nodes) (call %init_peer_id% ("op" "noop") []) ) (seq (fold nodes n (par (seq (xor (call n ("peer" "timestamp_ms") [] $res) (seq (call -relay- ("op" "noop") []) (call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 1]) ) ) (call %init_peer_id% ("op" "noop") []) ) (next n) ) ) (call %init_peer_id% ("op" "noop") []) ) ) ) (call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 2]) ) ) (par (call %init_peer_id% ("op" "identity") [$res.$.[19]!]) (call %init_peer_id% ("peer" "timeout") [1000 "timeout"]) ) ) (call %init_peer_id% ("op" "identity") [$res] res-fix) ) ) ) (call %init_peer_id% ("--after-callback-srv-service--" "print-and-stop") [res-fix nodes]) ) (call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 3]) )
true
(xor (seq (seq (call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-) (new $res (seq (seq (seq (call -relay- ("op" "noop") []) (xor (seq (call "PI:KEY:<KEY>END_PI" ("op" "string_to_b58") ["PI:KEY:<KEY>END_PI"] k) (par (seq (call "PI:KEY:<KEY>END_PI" ("kad" "neighborhood") [k [] []] nodes) (call %init_peer_id% ("op" "noop") []) ) (seq (fold nodes n (par (seq (xor (call n ("peer" "timestamp_ms") [] $res) (seq (call -relay- ("op" "noop") []) (call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 1]) ) ) (call %init_peer_id% ("op" "noop") []) ) (next n) ) ) (call %init_peer_id% ("op" "noop") []) ) ) ) (call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 2]) ) ) (par (call %init_peer_id% ("op" "identity") [$res.$.[19]!]) (call %init_peer_id% ("peer" "timeout") [1000 "timeout"]) ) ) (call %init_peer_id% ("op" "identity") [$res] res-fix) ) ) ) (call %init_peer_id% ("--after-callback-srv-service--" "print-and-stop") [res-fix nodes]) ) (call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 3]) )
[ { "context": " [clojure.test.check.generators :as gen]\n [com.gfredericks.test.chuck.clojure-test :refer [checking]]", "end": 123, "score": 0.6230822801589966, "start": 119, "tag": "USERNAME", "value": "gfre" }, { "context": "coder (byte-array [0]))))\n (is (= (key/parse \"012345\")\n (key/encode key/bytes-lexicoder (byt", "end": 5408, "score": 0.7530132532119751, "start": 5403, "tag": "KEY", "value": "12345" } ]
lib/core/test/merkle_db/key_test.clj
greglook/merkle-db
47
(ns merkle-db.key-test (:require [clojure.test :refer :all] [clojure.test.check.generators :as gen] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [merkle-db.key :as key])) (deftest printing (is (= "#merkle-db/key \"012345\"" (pr-str (key/create [0x01 0x23 0x45]))))) (deftest key-predicate (is (false? (key/key? nil))) (is (false? (key/key? :foo))) (is (false? (key/key? (byte-array [0 1 2])))) (is (true? (key/key? (key/create [0])))) (is (true? (key/key? (key/create [0 1 2 3 4]))))) (deftest lexicographic-ordering (testing "equal arrays" (is (zero? (compare (key/create []) (key/create [])))) (is (zero? (compare (key/create [1 2 3]) (key/create [1 2 3])))) (is (false? (key/before? (key/create [1]) (key/create [1])))) (is (false? (key/after? (key/create [1]) (key/create [1]))))) (testing "equal prefixes" (is (neg? (compare (key/create [1 2 3]) (key/create [1 2 3 4])))) (is (pos? (compare (key/create [1 2 3 4]) (key/create [1 2 3]))))) (testing "order-before" (is (neg? (compare (key/create [1 2 3]) (key/create [1 2 4])))) (is (neg? (compare (key/create [1 2 3]) (key/create [1 3 2])))) (is (neg? (compare (key/create [0 2 3 4]) (key/create [1 3 2 1])))) (is (true? (key/before? (key/create [0 1]) (key/create [0 2]))))) (testing "order-after" (is (pos? (compare (key/create [1 2 4]) (key/create [1 2 3])))) (is (pos? (compare (key/create [1 3 2]) (key/create [1 2 3])))) (is (pos? (compare (key/create [1 3 2 1]) (key/create [0 2 3 4])))) (is (true? (key/after? (key/create [0 1 2]) (key/create [0 1 0])))))) (deftest min-max-util (let [a (key/create [0]) b (key/create [5]) c (key/create [7]) d (key/create [8])] (testing "minimum keys" (is (= a (key/min a))) (is (= b (key/min b c))) (is (= b (key/min c d b))) (is (= a (key/min c d a b)))) (testing "maximum keys" (is (= a (key/max a))) (is (= c (key/max b c))) (is (= d (key/max c d b))) (is (= d (key/max c d a b)))))) (defn- check-lexicoder ([generator] (check-lexicoder generator compare)) ([generator cmp] (checking "reflexive coding" 50 [[coder arg-gen] generator x arg-gen] (let [decoded (key/decode coder (key/encode coder x))] (if (bytes? x) (is (zero? (cmp x decoded))) (is (= x decoded))))) (checking "sort order" 100 [[coder arg-gen] generator a arg-gen b arg-gen] (let [rrank (cmp a b) ka (key/encode coder a) kb (key/encode coder b)] (cond (zero? rrank) (is (zero? (compare ka kb))) (pos? rrank) (is (pos? (compare ka kb))) :else (is (neg? (compare ka kb)))))))) (defn- lexi-comparator "Wrap a comparator for elements of type x to build a lexical comparator over sequences of xs." [cmp] (fn lex-cmp [as bs] (let [prefix-len (min (count as) (count bs))] (loop [as as, bs bs] (if (and (seq as) (seq bs)) (let [rrank (cmp (first as) (first bs))] (if (zero? rrank) (recur (rest as) (rest bs)) rrank)) (- (count as) (count bs))))))) (defmacro ^:private is-reflexive [coder value hex] `(let [coder# ~coder key# (key/parse ~hex)] (is (= key# (key/encode coder# ~value))) (is (= ~value (key/decode coder# key#))))) (def lexicoder-generators "Map of lexicoder types to tuples of a lexicoder instance and a generator for values matching that lexicoder." {:string [key/string-lexicoder (gen/such-that not-empty gen/string)] :integer [key/integer-lexicoder gen/large-integer] :float [key/float-lexicoder (gen/double* {:NaN? false})] :instant [key/instant-lexicoder (gen/fmap #(java.time.Instant/ofEpochMilli %) gen/large-integer)]}) (deftest lexicoder-configs (is (thrown? Exception (key/lexicoder "not a keyword or vector"))) (is (thrown? Exception (key/lexicoder [123 "needs a keyword first"])))) (deftest bytes-lexicoder (testing "construction" (is (identical? key/bytes-lexicoder (key/lexicoder :bytes))) (is (satisfies? key/Lexicoder key/bytes-lexicoder)) (is (= :bytes (key/lexicoder-config key/bytes-lexicoder))) (is (thrown? Exception (key/lexicoder [:bytes :foo])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/bytes-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/bytes-lexicoder "foo")) "should not encode non-byte-arrays") (is (thrown? IllegalArgumentException (key/encode key/bytes-lexicoder (byte-array 0))) "should not encode empty bytes") (is (thrown? IllegalArgumentException (key/decode key/bytes-lexicoder (byte-array 0))) "should not decode empty bytes")) (testing "basic values" (is (= (key/parse "00") (key/encode key/bytes-lexicoder (byte-array [0])))) (is (= (key/parse "012345") (key/encode key/bytes-lexicoder (byte-array [1 35 69])))))) (deftest ^:generative bytes-lexicoding (check-lexicoder (gen/return [key/bytes-lexicoder (gen/such-that not-empty gen/bytes)]) @#'key/compare-bytes)) (deftest string-lexicoder (testing "construction" (is (identical? key/string-lexicoder (key/lexicoder :string))) (is (satisfies? key/Lexicoder (key/lexicoder [:string "UTF-8"]))) (is (= :string (key/lexicoder-config key/string-lexicoder))) (is (= [:string "US-ASCII"] (key/lexicoder-config (key/string-lexicoder* "US-ASCII")))) (is (thrown? Exception (key/lexicoder [:string "UTF-8" :bar])) "should only accept one config parameter")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/string-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/string-lexicoder 123)) "should not encode non-strings") (is (thrown? IllegalArgumentException (key/encode key/string-lexicoder "")) "should not encode empty strings") (is (thrown? IllegalArgumentException (key/decode key/string-lexicoder (byte-array 0))) "should not decode empty bytes")) (testing "basic values" (is-reflexive key/string-lexicoder "foo" "666F6F") (is-reflexive key/string-lexicoder "bar" "626172"))) (deftest ^:generative string-lexicoding (check-lexicoder (gen/return (:string lexicoder-generators)))) (deftest integer-lexicoder (testing "construction" (is (identical? key/integer-lexicoder (key/lexicoder :integer))) (is (= :integer (key/lexicoder-config key/integer-lexicoder))) (is (thrown? Exception (key/lexicoder [:integer :bar])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/integer-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/integer-lexicoder 0.0)) "should not encode non-integers") (is (thrown? IllegalArgumentException (key/decode key/integer-lexicoder (key/parse "80"))) "should not encode too-short keys")) (testing "basic values" (is-reflexive key/integer-lexicoder 0 "8000") (is-reflexive key/integer-lexicoder -1 "7FFF") (is-reflexive key/integer-lexicoder -0x7FFFFFFFFF000000 "788000000001000000"))) (deftest ^:generative integer-lexicoding (check-lexicoder (gen/return (:integer lexicoder-generators)))) (deftest float-lexicoder (testing "construction" (is (identical? key/float-lexicoder (key/lexicoder :float))) (is (= :float (key/lexicoder-config key/float-lexicoder))) (is (thrown? Exception (key/lexicoder [:float :bar])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/float-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/float-lexicoder 123)) "should not encode non-floats") (is (thrown? IllegalArgumentException (key/encode key/float-lexicoder Double/NaN)) "should not encode NaN values")) (testing "basic values" (is-reflexive key/float-lexicoder 0.0 "8000") (is-reflexive key/float-lexicoder 1.0 "873FF0000000000000") (is-reflexive key/float-lexicoder -1.0 "78C00FFFFFFFFFFFFF"))) (deftest ^:generative float-lexicoding (check-lexicoder (gen/return (:float lexicoder-generators)))) (deftest instant-lexicoder (testing "construction" (is (identical? key/instant-lexicoder (key/lexicoder :instant))) (is (= :instant (key/lexicoder-config key/instant-lexicoder))) (is (thrown? Exception (key/lexicoder [:instant :bar])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/instant-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/instant-lexicoder "")) "should not encode non-instant value"))) (deftest ^:generative instant-lexicoding (check-lexicoder (gen/return (:instant lexicoder-generators)))) (deftest sequence-lexicoder (testing "construction" (is (satisfies? key/Lexicoder (key/lexicoder [:seq :integer]))) (is (= [:seq :integer] (key/lexicoder-config (key/sequence-lexicoder key/integer-lexicoder)))) (is (thrown? Exception (key/lexicoder :seq)) "should require at least one config parameter") (is (thrown? Exception (key/lexicoder [:seq :string :foo])) "should only accept one config parameter")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode (key/sequence-lexicoder key/integer-lexicoder) nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode (key/sequence-lexicoder key/integer-lexicoder) #{123})) "should not encode non-sequential values"))) (deftest ^:generative sequence-lexicoding (check-lexicoder (gen/fmap (fn [[coder arg-gen]] [(key/sequence-lexicoder coder) (gen/vector arg-gen)]) (gen/elements (vals lexicoder-generators))) (lexi-comparator compare))) (deftest tuple-lexicoder (testing "construction" (is (satisfies? key/Lexicoder (key/lexicoder [:tuple :string]))) (is (= [:tuple :integer :string] (key/lexicoder-config (key/tuple-lexicoder key/integer-lexicoder key/string-lexicoder)))) (is (thrown? Exception (key/lexicoder [:tuple])) "should require at least one config parameter")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode (key/tuple-lexicoder key/integer-lexicoder) nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode (key/tuple-lexicoder key/integer-lexicoder) #{123})) "should not encode non-sequential values") (is (thrown? IllegalArgumentException (key/encode (key/tuple-lexicoder key/integer-lexicoder) [0 0])) "should not encode tuples larger than coders") (is (thrown? IllegalArgumentException (key/encode (key/lexicoder [:tuple :integer :string]) [0])) "should not encode tuples smaller than coders") (is (thrown? IllegalArgumentException (key/decode (key/tuple-lexicoder key/string-lexicoder) (key/encode (key/tuple-lexicoder key/string-lexicoder key/integer-lexicoder) ["foo" 123]))) "should not decode tuple longer than coders"))) (deftest ^:generative tuple-lexicoding (check-lexicoder (gen/fmap (fn [generators] [(apply key/tuple-lexicoder (map first generators)) (apply gen/tuple (map second generators))]) (gen/not-empty (gen/vector (gen/elements (vals lexicoder-generators))))))) (deftest reverse-lexicoder (testing "construction" (is (satisfies? key/Lexicoder (key/lexicoder [:reverse :instant]))) (is (= [:reverse :bytes] (key/lexicoder-config (key/reverse-lexicoder key/bytes-lexicoder)))) (is (thrown? Exception (key/lexicoder [:reverse]))) (is (thrown? Exception (key/lexicoder [:reverse :integer :string]))))) (deftest ^:generative reverse-lexicoding (check-lexicoder (gen/fmap (fn [[coder arg-gen]] [(key/reverse-lexicoder coder) arg-gen]) (gen/elements (vals lexicoder-generators))) (comp - compare)))
113625
(ns merkle-db.key-test (:require [clojure.test :refer :all] [clojure.test.check.generators :as gen] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [merkle-db.key :as key])) (deftest printing (is (= "#merkle-db/key \"012345\"" (pr-str (key/create [0x01 0x23 0x45]))))) (deftest key-predicate (is (false? (key/key? nil))) (is (false? (key/key? :foo))) (is (false? (key/key? (byte-array [0 1 2])))) (is (true? (key/key? (key/create [0])))) (is (true? (key/key? (key/create [0 1 2 3 4]))))) (deftest lexicographic-ordering (testing "equal arrays" (is (zero? (compare (key/create []) (key/create [])))) (is (zero? (compare (key/create [1 2 3]) (key/create [1 2 3])))) (is (false? (key/before? (key/create [1]) (key/create [1])))) (is (false? (key/after? (key/create [1]) (key/create [1]))))) (testing "equal prefixes" (is (neg? (compare (key/create [1 2 3]) (key/create [1 2 3 4])))) (is (pos? (compare (key/create [1 2 3 4]) (key/create [1 2 3]))))) (testing "order-before" (is (neg? (compare (key/create [1 2 3]) (key/create [1 2 4])))) (is (neg? (compare (key/create [1 2 3]) (key/create [1 3 2])))) (is (neg? (compare (key/create [0 2 3 4]) (key/create [1 3 2 1])))) (is (true? (key/before? (key/create [0 1]) (key/create [0 2]))))) (testing "order-after" (is (pos? (compare (key/create [1 2 4]) (key/create [1 2 3])))) (is (pos? (compare (key/create [1 3 2]) (key/create [1 2 3])))) (is (pos? (compare (key/create [1 3 2 1]) (key/create [0 2 3 4])))) (is (true? (key/after? (key/create [0 1 2]) (key/create [0 1 0])))))) (deftest min-max-util (let [a (key/create [0]) b (key/create [5]) c (key/create [7]) d (key/create [8])] (testing "minimum keys" (is (= a (key/min a))) (is (= b (key/min b c))) (is (= b (key/min c d b))) (is (= a (key/min c d a b)))) (testing "maximum keys" (is (= a (key/max a))) (is (= c (key/max b c))) (is (= d (key/max c d b))) (is (= d (key/max c d a b)))))) (defn- check-lexicoder ([generator] (check-lexicoder generator compare)) ([generator cmp] (checking "reflexive coding" 50 [[coder arg-gen] generator x arg-gen] (let [decoded (key/decode coder (key/encode coder x))] (if (bytes? x) (is (zero? (cmp x decoded))) (is (= x decoded))))) (checking "sort order" 100 [[coder arg-gen] generator a arg-gen b arg-gen] (let [rrank (cmp a b) ka (key/encode coder a) kb (key/encode coder b)] (cond (zero? rrank) (is (zero? (compare ka kb))) (pos? rrank) (is (pos? (compare ka kb))) :else (is (neg? (compare ka kb)))))))) (defn- lexi-comparator "Wrap a comparator for elements of type x to build a lexical comparator over sequences of xs." [cmp] (fn lex-cmp [as bs] (let [prefix-len (min (count as) (count bs))] (loop [as as, bs bs] (if (and (seq as) (seq bs)) (let [rrank (cmp (first as) (first bs))] (if (zero? rrank) (recur (rest as) (rest bs)) rrank)) (- (count as) (count bs))))))) (defmacro ^:private is-reflexive [coder value hex] `(let [coder# ~coder key# (key/parse ~hex)] (is (= key# (key/encode coder# ~value))) (is (= ~value (key/decode coder# key#))))) (def lexicoder-generators "Map of lexicoder types to tuples of a lexicoder instance and a generator for values matching that lexicoder." {:string [key/string-lexicoder (gen/such-that not-empty gen/string)] :integer [key/integer-lexicoder gen/large-integer] :float [key/float-lexicoder (gen/double* {:NaN? false})] :instant [key/instant-lexicoder (gen/fmap #(java.time.Instant/ofEpochMilli %) gen/large-integer)]}) (deftest lexicoder-configs (is (thrown? Exception (key/lexicoder "not a keyword or vector"))) (is (thrown? Exception (key/lexicoder [123 "needs a keyword first"])))) (deftest bytes-lexicoder (testing "construction" (is (identical? key/bytes-lexicoder (key/lexicoder :bytes))) (is (satisfies? key/Lexicoder key/bytes-lexicoder)) (is (= :bytes (key/lexicoder-config key/bytes-lexicoder))) (is (thrown? Exception (key/lexicoder [:bytes :foo])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/bytes-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/bytes-lexicoder "foo")) "should not encode non-byte-arrays") (is (thrown? IllegalArgumentException (key/encode key/bytes-lexicoder (byte-array 0))) "should not encode empty bytes") (is (thrown? IllegalArgumentException (key/decode key/bytes-lexicoder (byte-array 0))) "should not decode empty bytes")) (testing "basic values" (is (= (key/parse "00") (key/encode key/bytes-lexicoder (byte-array [0])))) (is (= (key/parse "0<KEY>") (key/encode key/bytes-lexicoder (byte-array [1 35 69])))))) (deftest ^:generative bytes-lexicoding (check-lexicoder (gen/return [key/bytes-lexicoder (gen/such-that not-empty gen/bytes)]) @#'key/compare-bytes)) (deftest string-lexicoder (testing "construction" (is (identical? key/string-lexicoder (key/lexicoder :string))) (is (satisfies? key/Lexicoder (key/lexicoder [:string "UTF-8"]))) (is (= :string (key/lexicoder-config key/string-lexicoder))) (is (= [:string "US-ASCII"] (key/lexicoder-config (key/string-lexicoder* "US-ASCII")))) (is (thrown? Exception (key/lexicoder [:string "UTF-8" :bar])) "should only accept one config parameter")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/string-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/string-lexicoder 123)) "should not encode non-strings") (is (thrown? IllegalArgumentException (key/encode key/string-lexicoder "")) "should not encode empty strings") (is (thrown? IllegalArgumentException (key/decode key/string-lexicoder (byte-array 0))) "should not decode empty bytes")) (testing "basic values" (is-reflexive key/string-lexicoder "foo" "666F6F") (is-reflexive key/string-lexicoder "bar" "626172"))) (deftest ^:generative string-lexicoding (check-lexicoder (gen/return (:string lexicoder-generators)))) (deftest integer-lexicoder (testing "construction" (is (identical? key/integer-lexicoder (key/lexicoder :integer))) (is (= :integer (key/lexicoder-config key/integer-lexicoder))) (is (thrown? Exception (key/lexicoder [:integer :bar])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/integer-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/integer-lexicoder 0.0)) "should not encode non-integers") (is (thrown? IllegalArgumentException (key/decode key/integer-lexicoder (key/parse "80"))) "should not encode too-short keys")) (testing "basic values" (is-reflexive key/integer-lexicoder 0 "8000") (is-reflexive key/integer-lexicoder -1 "7FFF") (is-reflexive key/integer-lexicoder -0x7FFFFFFFFF000000 "788000000001000000"))) (deftest ^:generative integer-lexicoding (check-lexicoder (gen/return (:integer lexicoder-generators)))) (deftest float-lexicoder (testing "construction" (is (identical? key/float-lexicoder (key/lexicoder :float))) (is (= :float (key/lexicoder-config key/float-lexicoder))) (is (thrown? Exception (key/lexicoder [:float :bar])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/float-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/float-lexicoder 123)) "should not encode non-floats") (is (thrown? IllegalArgumentException (key/encode key/float-lexicoder Double/NaN)) "should not encode NaN values")) (testing "basic values" (is-reflexive key/float-lexicoder 0.0 "8000") (is-reflexive key/float-lexicoder 1.0 "873FF0000000000000") (is-reflexive key/float-lexicoder -1.0 "78C00FFFFFFFFFFFFF"))) (deftest ^:generative float-lexicoding (check-lexicoder (gen/return (:float lexicoder-generators)))) (deftest instant-lexicoder (testing "construction" (is (identical? key/instant-lexicoder (key/lexicoder :instant))) (is (= :instant (key/lexicoder-config key/instant-lexicoder))) (is (thrown? Exception (key/lexicoder [:instant :bar])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/instant-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/instant-lexicoder "")) "should not encode non-instant value"))) (deftest ^:generative instant-lexicoding (check-lexicoder (gen/return (:instant lexicoder-generators)))) (deftest sequence-lexicoder (testing "construction" (is (satisfies? key/Lexicoder (key/lexicoder [:seq :integer]))) (is (= [:seq :integer] (key/lexicoder-config (key/sequence-lexicoder key/integer-lexicoder)))) (is (thrown? Exception (key/lexicoder :seq)) "should require at least one config parameter") (is (thrown? Exception (key/lexicoder [:seq :string :foo])) "should only accept one config parameter")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode (key/sequence-lexicoder key/integer-lexicoder) nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode (key/sequence-lexicoder key/integer-lexicoder) #{123})) "should not encode non-sequential values"))) (deftest ^:generative sequence-lexicoding (check-lexicoder (gen/fmap (fn [[coder arg-gen]] [(key/sequence-lexicoder coder) (gen/vector arg-gen)]) (gen/elements (vals lexicoder-generators))) (lexi-comparator compare))) (deftest tuple-lexicoder (testing "construction" (is (satisfies? key/Lexicoder (key/lexicoder [:tuple :string]))) (is (= [:tuple :integer :string] (key/lexicoder-config (key/tuple-lexicoder key/integer-lexicoder key/string-lexicoder)))) (is (thrown? Exception (key/lexicoder [:tuple])) "should require at least one config parameter")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode (key/tuple-lexicoder key/integer-lexicoder) nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode (key/tuple-lexicoder key/integer-lexicoder) #{123})) "should not encode non-sequential values") (is (thrown? IllegalArgumentException (key/encode (key/tuple-lexicoder key/integer-lexicoder) [0 0])) "should not encode tuples larger than coders") (is (thrown? IllegalArgumentException (key/encode (key/lexicoder [:tuple :integer :string]) [0])) "should not encode tuples smaller than coders") (is (thrown? IllegalArgumentException (key/decode (key/tuple-lexicoder key/string-lexicoder) (key/encode (key/tuple-lexicoder key/string-lexicoder key/integer-lexicoder) ["foo" 123]))) "should not decode tuple longer than coders"))) (deftest ^:generative tuple-lexicoding (check-lexicoder (gen/fmap (fn [generators] [(apply key/tuple-lexicoder (map first generators)) (apply gen/tuple (map second generators))]) (gen/not-empty (gen/vector (gen/elements (vals lexicoder-generators))))))) (deftest reverse-lexicoder (testing "construction" (is (satisfies? key/Lexicoder (key/lexicoder [:reverse :instant]))) (is (= [:reverse :bytes] (key/lexicoder-config (key/reverse-lexicoder key/bytes-lexicoder)))) (is (thrown? Exception (key/lexicoder [:reverse]))) (is (thrown? Exception (key/lexicoder [:reverse :integer :string]))))) (deftest ^:generative reverse-lexicoding (check-lexicoder (gen/fmap (fn [[coder arg-gen]] [(key/reverse-lexicoder coder) arg-gen]) (gen/elements (vals lexicoder-generators))) (comp - compare)))
true
(ns merkle-db.key-test (:require [clojure.test :refer :all] [clojure.test.check.generators :as gen] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [merkle-db.key :as key])) (deftest printing (is (= "#merkle-db/key \"012345\"" (pr-str (key/create [0x01 0x23 0x45]))))) (deftest key-predicate (is (false? (key/key? nil))) (is (false? (key/key? :foo))) (is (false? (key/key? (byte-array [0 1 2])))) (is (true? (key/key? (key/create [0])))) (is (true? (key/key? (key/create [0 1 2 3 4]))))) (deftest lexicographic-ordering (testing "equal arrays" (is (zero? (compare (key/create []) (key/create [])))) (is (zero? (compare (key/create [1 2 3]) (key/create [1 2 3])))) (is (false? (key/before? (key/create [1]) (key/create [1])))) (is (false? (key/after? (key/create [1]) (key/create [1]))))) (testing "equal prefixes" (is (neg? (compare (key/create [1 2 3]) (key/create [1 2 3 4])))) (is (pos? (compare (key/create [1 2 3 4]) (key/create [1 2 3]))))) (testing "order-before" (is (neg? (compare (key/create [1 2 3]) (key/create [1 2 4])))) (is (neg? (compare (key/create [1 2 3]) (key/create [1 3 2])))) (is (neg? (compare (key/create [0 2 3 4]) (key/create [1 3 2 1])))) (is (true? (key/before? (key/create [0 1]) (key/create [0 2]))))) (testing "order-after" (is (pos? (compare (key/create [1 2 4]) (key/create [1 2 3])))) (is (pos? (compare (key/create [1 3 2]) (key/create [1 2 3])))) (is (pos? (compare (key/create [1 3 2 1]) (key/create [0 2 3 4])))) (is (true? (key/after? (key/create [0 1 2]) (key/create [0 1 0])))))) (deftest min-max-util (let [a (key/create [0]) b (key/create [5]) c (key/create [7]) d (key/create [8])] (testing "minimum keys" (is (= a (key/min a))) (is (= b (key/min b c))) (is (= b (key/min c d b))) (is (= a (key/min c d a b)))) (testing "maximum keys" (is (= a (key/max a))) (is (= c (key/max b c))) (is (= d (key/max c d b))) (is (= d (key/max c d a b)))))) (defn- check-lexicoder ([generator] (check-lexicoder generator compare)) ([generator cmp] (checking "reflexive coding" 50 [[coder arg-gen] generator x arg-gen] (let [decoded (key/decode coder (key/encode coder x))] (if (bytes? x) (is (zero? (cmp x decoded))) (is (= x decoded))))) (checking "sort order" 100 [[coder arg-gen] generator a arg-gen b arg-gen] (let [rrank (cmp a b) ka (key/encode coder a) kb (key/encode coder b)] (cond (zero? rrank) (is (zero? (compare ka kb))) (pos? rrank) (is (pos? (compare ka kb))) :else (is (neg? (compare ka kb)))))))) (defn- lexi-comparator "Wrap a comparator for elements of type x to build a lexical comparator over sequences of xs." [cmp] (fn lex-cmp [as bs] (let [prefix-len (min (count as) (count bs))] (loop [as as, bs bs] (if (and (seq as) (seq bs)) (let [rrank (cmp (first as) (first bs))] (if (zero? rrank) (recur (rest as) (rest bs)) rrank)) (- (count as) (count bs))))))) (defmacro ^:private is-reflexive [coder value hex] `(let [coder# ~coder key# (key/parse ~hex)] (is (= key# (key/encode coder# ~value))) (is (= ~value (key/decode coder# key#))))) (def lexicoder-generators "Map of lexicoder types to tuples of a lexicoder instance and a generator for values matching that lexicoder." {:string [key/string-lexicoder (gen/such-that not-empty gen/string)] :integer [key/integer-lexicoder gen/large-integer] :float [key/float-lexicoder (gen/double* {:NaN? false})] :instant [key/instant-lexicoder (gen/fmap #(java.time.Instant/ofEpochMilli %) gen/large-integer)]}) (deftest lexicoder-configs (is (thrown? Exception (key/lexicoder "not a keyword or vector"))) (is (thrown? Exception (key/lexicoder [123 "needs a keyword first"])))) (deftest bytes-lexicoder (testing "construction" (is (identical? key/bytes-lexicoder (key/lexicoder :bytes))) (is (satisfies? key/Lexicoder key/bytes-lexicoder)) (is (= :bytes (key/lexicoder-config key/bytes-lexicoder))) (is (thrown? Exception (key/lexicoder [:bytes :foo])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/bytes-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/bytes-lexicoder "foo")) "should not encode non-byte-arrays") (is (thrown? IllegalArgumentException (key/encode key/bytes-lexicoder (byte-array 0))) "should not encode empty bytes") (is (thrown? IllegalArgumentException (key/decode key/bytes-lexicoder (byte-array 0))) "should not decode empty bytes")) (testing "basic values" (is (= (key/parse "00") (key/encode key/bytes-lexicoder (byte-array [0])))) (is (= (key/parse "0PI:KEY:<KEY>END_PI") (key/encode key/bytes-lexicoder (byte-array [1 35 69])))))) (deftest ^:generative bytes-lexicoding (check-lexicoder (gen/return [key/bytes-lexicoder (gen/such-that not-empty gen/bytes)]) @#'key/compare-bytes)) (deftest string-lexicoder (testing "construction" (is (identical? key/string-lexicoder (key/lexicoder :string))) (is (satisfies? key/Lexicoder (key/lexicoder [:string "UTF-8"]))) (is (= :string (key/lexicoder-config key/string-lexicoder))) (is (= [:string "US-ASCII"] (key/lexicoder-config (key/string-lexicoder* "US-ASCII")))) (is (thrown? Exception (key/lexicoder [:string "UTF-8" :bar])) "should only accept one config parameter")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/string-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/string-lexicoder 123)) "should not encode non-strings") (is (thrown? IllegalArgumentException (key/encode key/string-lexicoder "")) "should not encode empty strings") (is (thrown? IllegalArgumentException (key/decode key/string-lexicoder (byte-array 0))) "should not decode empty bytes")) (testing "basic values" (is-reflexive key/string-lexicoder "foo" "666F6F") (is-reflexive key/string-lexicoder "bar" "626172"))) (deftest ^:generative string-lexicoding (check-lexicoder (gen/return (:string lexicoder-generators)))) (deftest integer-lexicoder (testing "construction" (is (identical? key/integer-lexicoder (key/lexicoder :integer))) (is (= :integer (key/lexicoder-config key/integer-lexicoder))) (is (thrown? Exception (key/lexicoder [:integer :bar])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/integer-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/integer-lexicoder 0.0)) "should not encode non-integers") (is (thrown? IllegalArgumentException (key/decode key/integer-lexicoder (key/parse "80"))) "should not encode too-short keys")) (testing "basic values" (is-reflexive key/integer-lexicoder 0 "8000") (is-reflexive key/integer-lexicoder -1 "7FFF") (is-reflexive key/integer-lexicoder -0x7FFFFFFFFF000000 "788000000001000000"))) (deftest ^:generative integer-lexicoding (check-lexicoder (gen/return (:integer lexicoder-generators)))) (deftest float-lexicoder (testing "construction" (is (identical? key/float-lexicoder (key/lexicoder :float))) (is (= :float (key/lexicoder-config key/float-lexicoder))) (is (thrown? Exception (key/lexicoder [:float :bar])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/float-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/float-lexicoder 123)) "should not encode non-floats") (is (thrown? IllegalArgumentException (key/encode key/float-lexicoder Double/NaN)) "should not encode NaN values")) (testing "basic values" (is-reflexive key/float-lexicoder 0.0 "8000") (is-reflexive key/float-lexicoder 1.0 "873FF0000000000000") (is-reflexive key/float-lexicoder -1.0 "78C00FFFFFFFFFFFFF"))) (deftest ^:generative float-lexicoding (check-lexicoder (gen/return (:float lexicoder-generators)))) (deftest instant-lexicoder (testing "construction" (is (identical? key/instant-lexicoder (key/lexicoder :instant))) (is (= :instant (key/lexicoder-config key/instant-lexicoder))) (is (thrown? Exception (key/lexicoder [:instant :bar])) "should not accept any config parameters")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode key/instant-lexicoder nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode key/instant-lexicoder "")) "should not encode non-instant value"))) (deftest ^:generative instant-lexicoding (check-lexicoder (gen/return (:instant lexicoder-generators)))) (deftest sequence-lexicoder (testing "construction" (is (satisfies? key/Lexicoder (key/lexicoder [:seq :integer]))) (is (= [:seq :integer] (key/lexicoder-config (key/sequence-lexicoder key/integer-lexicoder)))) (is (thrown? Exception (key/lexicoder :seq)) "should require at least one config parameter") (is (thrown? Exception (key/lexicoder [:seq :string :foo])) "should only accept one config parameter")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode (key/sequence-lexicoder key/integer-lexicoder) nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode (key/sequence-lexicoder key/integer-lexicoder) #{123})) "should not encode non-sequential values"))) (deftest ^:generative sequence-lexicoding (check-lexicoder (gen/fmap (fn [[coder arg-gen]] [(key/sequence-lexicoder coder) (gen/vector arg-gen)]) (gen/elements (vals lexicoder-generators))) (lexi-comparator compare))) (deftest tuple-lexicoder (testing "construction" (is (satisfies? key/Lexicoder (key/lexicoder [:tuple :string]))) (is (= [:tuple :integer :string] (key/lexicoder-config (key/tuple-lexicoder key/integer-lexicoder key/string-lexicoder)))) (is (thrown? Exception (key/lexicoder [:tuple])) "should require at least one config parameter")) (testing "bad values" (is (thrown? IllegalArgumentException (key/encode (key/tuple-lexicoder key/integer-lexicoder) nil)) "should not encode nil") (is (thrown? IllegalArgumentException (key/encode (key/tuple-lexicoder key/integer-lexicoder) #{123})) "should not encode non-sequential values") (is (thrown? IllegalArgumentException (key/encode (key/tuple-lexicoder key/integer-lexicoder) [0 0])) "should not encode tuples larger than coders") (is (thrown? IllegalArgumentException (key/encode (key/lexicoder [:tuple :integer :string]) [0])) "should not encode tuples smaller than coders") (is (thrown? IllegalArgumentException (key/decode (key/tuple-lexicoder key/string-lexicoder) (key/encode (key/tuple-lexicoder key/string-lexicoder key/integer-lexicoder) ["foo" 123]))) "should not decode tuple longer than coders"))) (deftest ^:generative tuple-lexicoding (check-lexicoder (gen/fmap (fn [generators] [(apply key/tuple-lexicoder (map first generators)) (apply gen/tuple (map second generators))]) (gen/not-empty (gen/vector (gen/elements (vals lexicoder-generators))))))) (deftest reverse-lexicoder (testing "construction" (is (satisfies? key/Lexicoder (key/lexicoder [:reverse :instant]))) (is (= [:reverse :bytes] (key/lexicoder-config (key/reverse-lexicoder key/bytes-lexicoder)))) (is (thrown? Exception (key/lexicoder [:reverse]))) (is (thrown? Exception (key/lexicoder [:reverse :integer :string]))))) (deftest ^:generative reverse-lexicoding (check-lexicoder (gen/fmap (fn [[coder arg-gen]] [(key/reverse-lexicoder coder) arg-gen]) (gen/elements (vals lexicoder-generators))) (comp - compare)))
[ { "context": "Queue]))\n\n(defonce ^:private non-component-keys #{:position :rotation :scale})\n\n(defn print-tree\n ([^Node node]\n (print-tre", "end": 306, "score": 0.8260732293128967, "start": 281, "tag": "KEY", "value": "position :rotation :scale" } ]
src/main/threeagent/impl/virtual_scene.cljs
darwin/threeagent
0
(ns threeagent.impl.virtual-scene (:require [threeagent.impl.util :refer [log]] [medley.core :as medley] [reagent.ratom :as ratom] [reagent.core :as reagent]) (:import [goog.structs PriorityQueue])) (defonce ^:private non-component-keys #{:position :rotation :scale}) (defn print-tree ([^Node node] (print-tree node "")) ([^Node node p] (let [is-reactive (some? (.-reaction node))] (println p "|-" (.-key node) (str "comp:" (:component-key (.-data node))) (str "dirty:" (.-dirty node)) (str "reactive:" is-reactive)) (doseq [child (es6-iterator-seq (.values (.-children node)))] (print-tree child (str p "\t")))))) (defn node->path ([node] (node->path [] node)) ([path node] (if node (recur (conj path (.-key node)) (.-parent node)) (reverse path)))) (defn get-key [key meta] (:key meta key)) (deftype Node [^Node parent depth key meta data dirty render reaction children] Object (terminal? [this] (= 0 (.-size children))) (for-each-child [this f] (doseq [child (es6-iterator-seq (.values children))] (f child)))) (deftype Scene [root renderQueue] Object (enqueueForRender [this ^Node node] (set! (.-dirty node) true) (.enqueue renderQueue (.-depth node) node))) (defn get-in-node [^Node node path] (if (empty? path) node (recur (.get (.-children node) (first path)) (rest path)))) (defn get-in-scene [^Scene scene path] (get-in-node (.-root scene) (rest path))) (defn- eval-fn [f args] (let [result (apply f args)] (if (fn? result) (recur result args) (if (fn? (first result)) [(fn [] [:object (f)]) [:object result]] [f result])))) (defn- on-react! [ctx] (let [node ^Node (.-node ctx) scene ^Scene (.-scene ctx)] (.enqueueForRender scene node))) (defn- extract-comp-config [config] (let [c (transient config)] (persistent! (reduce #(dissoc! %1 %2) c non-component-keys)))) (defn- node-data [comp-key comp-config] {:position (:position comp-config [0 0 0]) :rotation (:rotation comp-config [0 0 0]) :scale (:scale comp-config [1.0 1.0 1.0]) :component-key comp-key :component-config (extract-comp-config comp-config)}) ;(apply dissoc comp-config non-component-keys)}) (defmulti ->node (fn [^Scene scene ^Node parent key [l & r]] (cond (keyword? l) :keyword (fn? l) :fn (sequential? l) :seq (and (nil? l) (nil? r)) :empty-list :else nil))) (defmethod ->node :default [scene parent key form] (println "Invalid object form:" form)) (defmethod ->node :empty-list [scene parent key form]) (defmethod ->node :seq [scene parent key form] (->node scene parent key (with-meta (into [:object] form) (meta form)))) (defmethod ->node :keyword [scene parent key form] (let [[comp-key & rs] form first-child (first rs) metadata (meta form) key (or (:key metadata) key) comp-config (if (map? first-child) first-child {}) children (filter some? (if (map? first-child) (rest rs) rs)) children-map (js/Map.) data (node-data comp-key comp-config) depth (if parent (inc (.-depth parent)) 0) node (Node. parent depth key metadata data false nil nil children-map)] (doseq [[idx child] (medley/indexed children)] (when-let [child-node (->node scene node idx child)] (.set children-map (.-key child-node) child-node))) node)) (defmethod ->node :fn [scene parent key form] (let [key (or (:key (meta form)) key) [f & args] form reaction-ctx ^js (clj->js {:node nil :reaction nil}) [final-fn result] (ratom/run-in-reaction #(eval-fn f args) reaction-ctx "reaction" on-react! {:no-cache true}) node ^Node (->node scene parent key result)] (set! (.-originalFn node) f) (set! (.-render node) final-fn) (set! (.-form node) form) (set! (.-renderedForm node) result) (when-let [reaction (.-reaction reaction-ctx)] (set! (.-scene reaction-ctx) scene) (set! (.-node reaction-ctx) node) (set! (.-reaction node) reaction)) node)) (defn- form->form-type [[l & r]] (cond (fn? l) :fn (keyword? l) :keyword (sequential? l) :seq (and (nil? l) (nil? r)) :empty-list :else nil)) (defmulti ->node-shallow (fn [key f] (form->form-type f))) (defmethod ->node-shallow :empty-list [key form]) (defmethod ->node-shallow :fn [key [f & args :as form]]) (defmethod ->node-shallow :seq [key form] (when-not (empty? form) (let [m (meta form)] (->node-shallow (get-key key m) (with-meta (into [:object] form) m))))) (defmethod ->node-shallow :keyword [key form] (let [[comp-key & rs] form first-child (first rs) comp-config (if (map? first-child) first-child {}) children (filter #(and (some? %) (not (empty? %))) (if (map? first-child) (rest rs) rs))] {:key key :data (node-data comp-key comp-config) :form form :children-keys (map-indexed #(vector (or (:key (meta %2)) %1) %2) children)})) (defn- dispose-node! [^Node node] (set! (.-disposed node) true) (when-let [reaction (.-reaction node)] (ratom/dispose! reaction)) (.for-each-child node dispose-node!)) (defn- add-node! [^Scene scene ^Node parent-node key form changelog] (when-let [node (->node scene parent-node key form)] (.push changelog [node :add nil (.-data node)]) node)) (defn- remove-node! [^Node node changelog] (.push changelog [node :remove (.-data node) nil]) (set! (.-data node) nil) (set! (.-dirty node) false) (dispose-node! node)) (defn- replace-node! [^Scene scene ^Node node new-form changelog] (let [parent (.-parent node) key (.-key node)] (remove-node! node changelog) (let [new-node (add-node! scene parent key new-form changelog)] (.set (.-children parent) key new-node)))) (defn- diff-fn? [^Node node new-form] (let [original-fn (.-originalFn node)] (and (some? original-fn) (not= original-fn (first new-form))))) (defn- update-node! [^Scene scene ^Node node new-form changelog] (set! (.-dirty node) false) (if (diff-fn? node new-form) (do (replace-node! scene node new-form changelog)) (let [render-fn (.-render node) new-type (form->form-type new-form) rendered-form (if (and render-fn (= :fn new-type)) (apply render-fn (rest new-form)) new-form) old-form (.-renderedForm node)] (when (not= rendered-form old-form) (let [key (.-key node) children (.-children node) old-data (.-data node) shallow-node (->node-shallow key rendered-form) new-data (:data shallow-node) current-keys (set (es6-iterator-seq (.keys children))) new-keys (set (map first (:children-keys shallow-node))) dropped-keys (clojure.set/difference current-keys new-keys)] (set! (.-data node) new-data) (when render-fn (set! (.-form node) (into [render-fn] (rest new-form)))) (set! (.-renderedForm node) new-form) (.push changelog [node :update old-data new-data]) ;; Remove children that no longer exist (doseq [child-key dropped-keys] (let [child-node (.get children child-key)] (remove-node! child-node changelog)) (.delete children child-key)) ;; Update existing children and add new children (doseq [[child-key child-form] (:children-keys shallow-node)] (if-let [child (.get children child-key)] ;; Update existing child (update-node! scene child child-form changelog) ;; Add new child (when-let [child-node (add-node! scene node child-key child-form changelog)] (.set children child-key child-node))))))))) (defn- render-node! [^Scene scene ^Node node changelog] (let [form (.-form node)] (update-node! scene node form changelog))) (defn render! [^Scene scene changelog] (reagent/flush) (let [queue (.-renderQueue scene)] (loop [node ^Node (.dequeue queue)] (when node (do (when (.-dirty node) (render-node! scene node changelog)) (recur ^Node (.dequeue queue))))))) (defn destroy! [^Scene scene] (dispose-node! (.-root scene))) (defn create [root-fn] (let [scene (Scene. nil (PriorityQueue.)) root-node (->node scene nil 0 [root-fn])] (set! (.-root scene) root-node) scene))
13885
(ns threeagent.impl.virtual-scene (:require [threeagent.impl.util :refer [log]] [medley.core :as medley] [reagent.ratom :as ratom] [reagent.core :as reagent]) (:import [goog.structs PriorityQueue])) (defonce ^:private non-component-keys #{:<KEY>}) (defn print-tree ([^Node node] (print-tree node "")) ([^Node node p] (let [is-reactive (some? (.-reaction node))] (println p "|-" (.-key node) (str "comp:" (:component-key (.-data node))) (str "dirty:" (.-dirty node)) (str "reactive:" is-reactive)) (doseq [child (es6-iterator-seq (.values (.-children node)))] (print-tree child (str p "\t")))))) (defn node->path ([node] (node->path [] node)) ([path node] (if node (recur (conj path (.-key node)) (.-parent node)) (reverse path)))) (defn get-key [key meta] (:key meta key)) (deftype Node [^Node parent depth key meta data dirty render reaction children] Object (terminal? [this] (= 0 (.-size children))) (for-each-child [this f] (doseq [child (es6-iterator-seq (.values children))] (f child)))) (deftype Scene [root renderQueue] Object (enqueueForRender [this ^Node node] (set! (.-dirty node) true) (.enqueue renderQueue (.-depth node) node))) (defn get-in-node [^Node node path] (if (empty? path) node (recur (.get (.-children node) (first path)) (rest path)))) (defn get-in-scene [^Scene scene path] (get-in-node (.-root scene) (rest path))) (defn- eval-fn [f args] (let [result (apply f args)] (if (fn? result) (recur result args) (if (fn? (first result)) [(fn [] [:object (f)]) [:object result]] [f result])))) (defn- on-react! [ctx] (let [node ^Node (.-node ctx) scene ^Scene (.-scene ctx)] (.enqueueForRender scene node))) (defn- extract-comp-config [config] (let [c (transient config)] (persistent! (reduce #(dissoc! %1 %2) c non-component-keys)))) (defn- node-data [comp-key comp-config] {:position (:position comp-config [0 0 0]) :rotation (:rotation comp-config [0 0 0]) :scale (:scale comp-config [1.0 1.0 1.0]) :component-key comp-key :component-config (extract-comp-config comp-config)}) ;(apply dissoc comp-config non-component-keys)}) (defmulti ->node (fn [^Scene scene ^Node parent key [l & r]] (cond (keyword? l) :keyword (fn? l) :fn (sequential? l) :seq (and (nil? l) (nil? r)) :empty-list :else nil))) (defmethod ->node :default [scene parent key form] (println "Invalid object form:" form)) (defmethod ->node :empty-list [scene parent key form]) (defmethod ->node :seq [scene parent key form] (->node scene parent key (with-meta (into [:object] form) (meta form)))) (defmethod ->node :keyword [scene parent key form] (let [[comp-key & rs] form first-child (first rs) metadata (meta form) key (or (:key metadata) key) comp-config (if (map? first-child) first-child {}) children (filter some? (if (map? first-child) (rest rs) rs)) children-map (js/Map.) data (node-data comp-key comp-config) depth (if parent (inc (.-depth parent)) 0) node (Node. parent depth key metadata data false nil nil children-map)] (doseq [[idx child] (medley/indexed children)] (when-let [child-node (->node scene node idx child)] (.set children-map (.-key child-node) child-node))) node)) (defmethod ->node :fn [scene parent key form] (let [key (or (:key (meta form)) key) [f & args] form reaction-ctx ^js (clj->js {:node nil :reaction nil}) [final-fn result] (ratom/run-in-reaction #(eval-fn f args) reaction-ctx "reaction" on-react! {:no-cache true}) node ^Node (->node scene parent key result)] (set! (.-originalFn node) f) (set! (.-render node) final-fn) (set! (.-form node) form) (set! (.-renderedForm node) result) (when-let [reaction (.-reaction reaction-ctx)] (set! (.-scene reaction-ctx) scene) (set! (.-node reaction-ctx) node) (set! (.-reaction node) reaction)) node)) (defn- form->form-type [[l & r]] (cond (fn? l) :fn (keyword? l) :keyword (sequential? l) :seq (and (nil? l) (nil? r)) :empty-list :else nil)) (defmulti ->node-shallow (fn [key f] (form->form-type f))) (defmethod ->node-shallow :empty-list [key form]) (defmethod ->node-shallow :fn [key [f & args :as form]]) (defmethod ->node-shallow :seq [key form] (when-not (empty? form) (let [m (meta form)] (->node-shallow (get-key key m) (with-meta (into [:object] form) m))))) (defmethod ->node-shallow :keyword [key form] (let [[comp-key & rs] form first-child (first rs) comp-config (if (map? first-child) first-child {}) children (filter #(and (some? %) (not (empty? %))) (if (map? first-child) (rest rs) rs))] {:key key :data (node-data comp-key comp-config) :form form :children-keys (map-indexed #(vector (or (:key (meta %2)) %1) %2) children)})) (defn- dispose-node! [^Node node] (set! (.-disposed node) true) (when-let [reaction (.-reaction node)] (ratom/dispose! reaction)) (.for-each-child node dispose-node!)) (defn- add-node! [^Scene scene ^Node parent-node key form changelog] (when-let [node (->node scene parent-node key form)] (.push changelog [node :add nil (.-data node)]) node)) (defn- remove-node! [^Node node changelog] (.push changelog [node :remove (.-data node) nil]) (set! (.-data node) nil) (set! (.-dirty node) false) (dispose-node! node)) (defn- replace-node! [^Scene scene ^Node node new-form changelog] (let [parent (.-parent node) key (.-key node)] (remove-node! node changelog) (let [new-node (add-node! scene parent key new-form changelog)] (.set (.-children parent) key new-node)))) (defn- diff-fn? [^Node node new-form] (let [original-fn (.-originalFn node)] (and (some? original-fn) (not= original-fn (first new-form))))) (defn- update-node! [^Scene scene ^Node node new-form changelog] (set! (.-dirty node) false) (if (diff-fn? node new-form) (do (replace-node! scene node new-form changelog)) (let [render-fn (.-render node) new-type (form->form-type new-form) rendered-form (if (and render-fn (= :fn new-type)) (apply render-fn (rest new-form)) new-form) old-form (.-renderedForm node)] (when (not= rendered-form old-form) (let [key (.-key node) children (.-children node) old-data (.-data node) shallow-node (->node-shallow key rendered-form) new-data (:data shallow-node) current-keys (set (es6-iterator-seq (.keys children))) new-keys (set (map first (:children-keys shallow-node))) dropped-keys (clojure.set/difference current-keys new-keys)] (set! (.-data node) new-data) (when render-fn (set! (.-form node) (into [render-fn] (rest new-form)))) (set! (.-renderedForm node) new-form) (.push changelog [node :update old-data new-data]) ;; Remove children that no longer exist (doseq [child-key dropped-keys] (let [child-node (.get children child-key)] (remove-node! child-node changelog)) (.delete children child-key)) ;; Update existing children and add new children (doseq [[child-key child-form] (:children-keys shallow-node)] (if-let [child (.get children child-key)] ;; Update existing child (update-node! scene child child-form changelog) ;; Add new child (when-let [child-node (add-node! scene node child-key child-form changelog)] (.set children child-key child-node))))))))) (defn- render-node! [^Scene scene ^Node node changelog] (let [form (.-form node)] (update-node! scene node form changelog))) (defn render! [^Scene scene changelog] (reagent/flush) (let [queue (.-renderQueue scene)] (loop [node ^Node (.dequeue queue)] (when node (do (when (.-dirty node) (render-node! scene node changelog)) (recur ^Node (.dequeue queue))))))) (defn destroy! [^Scene scene] (dispose-node! (.-root scene))) (defn create [root-fn] (let [scene (Scene. nil (PriorityQueue.)) root-node (->node scene nil 0 [root-fn])] (set! (.-root scene) root-node) scene))
true
(ns threeagent.impl.virtual-scene (:require [threeagent.impl.util :refer [log]] [medley.core :as medley] [reagent.ratom :as ratom] [reagent.core :as reagent]) (:import [goog.structs PriorityQueue])) (defonce ^:private non-component-keys #{:PI:KEY:<KEY>END_PI}) (defn print-tree ([^Node node] (print-tree node "")) ([^Node node p] (let [is-reactive (some? (.-reaction node))] (println p "|-" (.-key node) (str "comp:" (:component-key (.-data node))) (str "dirty:" (.-dirty node)) (str "reactive:" is-reactive)) (doseq [child (es6-iterator-seq (.values (.-children node)))] (print-tree child (str p "\t")))))) (defn node->path ([node] (node->path [] node)) ([path node] (if node (recur (conj path (.-key node)) (.-parent node)) (reverse path)))) (defn get-key [key meta] (:key meta key)) (deftype Node [^Node parent depth key meta data dirty render reaction children] Object (terminal? [this] (= 0 (.-size children))) (for-each-child [this f] (doseq [child (es6-iterator-seq (.values children))] (f child)))) (deftype Scene [root renderQueue] Object (enqueueForRender [this ^Node node] (set! (.-dirty node) true) (.enqueue renderQueue (.-depth node) node))) (defn get-in-node [^Node node path] (if (empty? path) node (recur (.get (.-children node) (first path)) (rest path)))) (defn get-in-scene [^Scene scene path] (get-in-node (.-root scene) (rest path))) (defn- eval-fn [f args] (let [result (apply f args)] (if (fn? result) (recur result args) (if (fn? (first result)) [(fn [] [:object (f)]) [:object result]] [f result])))) (defn- on-react! [ctx] (let [node ^Node (.-node ctx) scene ^Scene (.-scene ctx)] (.enqueueForRender scene node))) (defn- extract-comp-config [config] (let [c (transient config)] (persistent! (reduce #(dissoc! %1 %2) c non-component-keys)))) (defn- node-data [comp-key comp-config] {:position (:position comp-config [0 0 0]) :rotation (:rotation comp-config [0 0 0]) :scale (:scale comp-config [1.0 1.0 1.0]) :component-key comp-key :component-config (extract-comp-config comp-config)}) ;(apply dissoc comp-config non-component-keys)}) (defmulti ->node (fn [^Scene scene ^Node parent key [l & r]] (cond (keyword? l) :keyword (fn? l) :fn (sequential? l) :seq (and (nil? l) (nil? r)) :empty-list :else nil))) (defmethod ->node :default [scene parent key form] (println "Invalid object form:" form)) (defmethod ->node :empty-list [scene parent key form]) (defmethod ->node :seq [scene parent key form] (->node scene parent key (with-meta (into [:object] form) (meta form)))) (defmethod ->node :keyword [scene parent key form] (let [[comp-key & rs] form first-child (first rs) metadata (meta form) key (or (:key metadata) key) comp-config (if (map? first-child) first-child {}) children (filter some? (if (map? first-child) (rest rs) rs)) children-map (js/Map.) data (node-data comp-key comp-config) depth (if parent (inc (.-depth parent)) 0) node (Node. parent depth key metadata data false nil nil children-map)] (doseq [[idx child] (medley/indexed children)] (when-let [child-node (->node scene node idx child)] (.set children-map (.-key child-node) child-node))) node)) (defmethod ->node :fn [scene parent key form] (let [key (or (:key (meta form)) key) [f & args] form reaction-ctx ^js (clj->js {:node nil :reaction nil}) [final-fn result] (ratom/run-in-reaction #(eval-fn f args) reaction-ctx "reaction" on-react! {:no-cache true}) node ^Node (->node scene parent key result)] (set! (.-originalFn node) f) (set! (.-render node) final-fn) (set! (.-form node) form) (set! (.-renderedForm node) result) (when-let [reaction (.-reaction reaction-ctx)] (set! (.-scene reaction-ctx) scene) (set! (.-node reaction-ctx) node) (set! (.-reaction node) reaction)) node)) (defn- form->form-type [[l & r]] (cond (fn? l) :fn (keyword? l) :keyword (sequential? l) :seq (and (nil? l) (nil? r)) :empty-list :else nil)) (defmulti ->node-shallow (fn [key f] (form->form-type f))) (defmethod ->node-shallow :empty-list [key form]) (defmethod ->node-shallow :fn [key [f & args :as form]]) (defmethod ->node-shallow :seq [key form] (when-not (empty? form) (let [m (meta form)] (->node-shallow (get-key key m) (with-meta (into [:object] form) m))))) (defmethod ->node-shallow :keyword [key form] (let [[comp-key & rs] form first-child (first rs) comp-config (if (map? first-child) first-child {}) children (filter #(and (some? %) (not (empty? %))) (if (map? first-child) (rest rs) rs))] {:key key :data (node-data comp-key comp-config) :form form :children-keys (map-indexed #(vector (or (:key (meta %2)) %1) %2) children)})) (defn- dispose-node! [^Node node] (set! (.-disposed node) true) (when-let [reaction (.-reaction node)] (ratom/dispose! reaction)) (.for-each-child node dispose-node!)) (defn- add-node! [^Scene scene ^Node parent-node key form changelog] (when-let [node (->node scene parent-node key form)] (.push changelog [node :add nil (.-data node)]) node)) (defn- remove-node! [^Node node changelog] (.push changelog [node :remove (.-data node) nil]) (set! (.-data node) nil) (set! (.-dirty node) false) (dispose-node! node)) (defn- replace-node! [^Scene scene ^Node node new-form changelog] (let [parent (.-parent node) key (.-key node)] (remove-node! node changelog) (let [new-node (add-node! scene parent key new-form changelog)] (.set (.-children parent) key new-node)))) (defn- diff-fn? [^Node node new-form] (let [original-fn (.-originalFn node)] (and (some? original-fn) (not= original-fn (first new-form))))) (defn- update-node! [^Scene scene ^Node node new-form changelog] (set! (.-dirty node) false) (if (diff-fn? node new-form) (do (replace-node! scene node new-form changelog)) (let [render-fn (.-render node) new-type (form->form-type new-form) rendered-form (if (and render-fn (= :fn new-type)) (apply render-fn (rest new-form)) new-form) old-form (.-renderedForm node)] (when (not= rendered-form old-form) (let [key (.-key node) children (.-children node) old-data (.-data node) shallow-node (->node-shallow key rendered-form) new-data (:data shallow-node) current-keys (set (es6-iterator-seq (.keys children))) new-keys (set (map first (:children-keys shallow-node))) dropped-keys (clojure.set/difference current-keys new-keys)] (set! (.-data node) new-data) (when render-fn (set! (.-form node) (into [render-fn] (rest new-form)))) (set! (.-renderedForm node) new-form) (.push changelog [node :update old-data new-data]) ;; Remove children that no longer exist (doseq [child-key dropped-keys] (let [child-node (.get children child-key)] (remove-node! child-node changelog)) (.delete children child-key)) ;; Update existing children and add new children (doseq [[child-key child-form] (:children-keys shallow-node)] (if-let [child (.get children child-key)] ;; Update existing child (update-node! scene child child-form changelog) ;; Add new child (when-let [child-node (add-node! scene node child-key child-form changelog)] (.set children child-key child-node))))))))) (defn- render-node! [^Scene scene ^Node node changelog] (let [form (.-form node)] (update-node! scene node form changelog))) (defn render! [^Scene scene changelog] (reagent/flush) (let [queue (.-renderQueue scene)] (loop [node ^Node (.dequeue queue)] (when node (do (when (.-dirty node) (render-node! scene node changelog)) (recur ^Node (.dequeue queue))))))) (defn destroy! [^Scene scene] (dispose-node! (.-root scene))) (defn create [root-fn] (let [scene (Scene. nil (PriorityQueue.)) root-node (->node scene nil 0 [root-fn])] (set! (.-root scene) root-node) scene))
[ { "context": "er\n :password password}\n :format (json-reque", "end": 2006, "score": 0.9990419149398804, "start": 1998, "tag": "PASSWORD", "value": "password" } ]
src/app/events.cljs
skilbjo/compojure
1
(ns app.events (:require-macros [cljs-log.core :as log]) (:require [app.db :as db] [app.util :as util] [ajax.core :refer [json-request-format json-response-format]] [clojure.string :as string] [day8.re-frame.http-fx] ;; :http-xhrio self-register with re-frame [day8.re-frame.tracing :refer-macros [fn-traced]] [re-frame.core :as rf])) (goog-define backend-uri "localhost:8080") ;; -- utils ------------------------------------------------------------------- (def set-user-interceptor [(rf/path :user) (rf/after db/set-user-ls) rf/trim-v]) (def remove-user-interceptor [(rf/after db/remove-user-ls)]) (defn endpoint [& params] (let [api-prefix "api/v1" prefix (str backend-uri "/" api-prefix) joined-endpoint (string/join "/" (concat [prefix] params))] (log/debug "endpoint is: " joined-endpoint) joined-endpoint)) (defn auth-header [db] "Get user token and format for API authorization" (let [token (-> db :user :token)] (log/debug "auth-header called. token is: " token) (if token [:Authorization (str "Token " token)] nil))) (defn dispatch-report [db body report] (let [user (-> db :user :user) password (-> db :user :token) report-cached? (some? (util/get-report db report))] (if report-cached? {:db (-> db ; this is the body of the report-success fn (assoc-in [:loading (keyword report)] false) (assoc :active-page (keyword report))) :dispatch-n (list [:complete-request (keyword report)])} {:db (assoc-in db [:loading (-> report keyword)] true) :http-xhrio {:method :get :uri (endpoint "reports" report) :headers (auth-header db) :params {:user user :password password} :format (json-request-format) :response-format (json-response-format {:keywords? true}) :on-success [(-> report name (str "-success") keyword)] :on-failure [:api-request-error (keyword report)]}}))) (defn report-success [db result report] {:db (-> db (assoc-in [:loading (keyword report)] false) (assoc :active-page (keyword report)) (assoc (keyword report) result)) :dispatch-n (list [:complete-request (keyword report)])}) (rf/reg-fx :set-hash (fn [{:keys [hash]}] (set! (.-hash js/location) hash))) ;; -- init -------------------------------------------------------------------- (rf/reg-event-fx ;; usage: (dispatch [:initialise-db]) :initialize-db [(rf/inject-cofx :local-store-user) #_s/check-spec-interceptor] (fn-traced [{:keys [db local-store-user]} _] {:db (-> db/default-db (assoc :user local-store-user))})) (rf/reg-event-fx ;; usage: (dispatch [:set-active-page {:page :home}) :set-active-page ;; when user clicks on a link to go to a another page (fn-traced [{:keys [db]} [_ {:keys [page ;; destructure 2nd parameter slug ;; to obtain keys profile]}]] (let [set-page (assoc db :active-page page)] (case page ;; -- URL @ "/" | "/login" | "/register" --------------------- (:home :login :register) {:db set-page} ;; -- URL @ "/portfolio" ------------------------------------- :portfolio {:dispatch [:portfolio]} ;; -- URL @ "/asset-type" ------------------------------------ :asset-type {:dispatch [:asset-type]} ;; -- URL @ "/investment-style" ------------------------------ :investment-style {:dispatch [:investment-style]} ;; -- URL @ "/capitalization" --------------------------------- :capitalization {:dispatch [:capitalization]} ;; -- URL @ "/location" --------------------------------------- :location {:dispatch [:location]})))) ;; -- POST Login @ /api/login ------------------------------------------------- (rf/reg-event-fx :login (fn-traced [{:keys [db]} [_ body]] {:db (assoc-in db [:loading :login] true) :http-xhrio {:method :post :uri (endpoint "login") :headers (auth-header db) :params body :format (json-request-format) :response-format (json-response-format {:keywords? true}) :on-success [:login-success] :on-failure [:api-request-error :login]}})) (rf/reg-event-fx :login-success set-user-interceptor (fn-traced [{user :db} response] (let [user' (-> response first :user) token (-> response first :token)] {:db (assoc user :user user' :token token) :dispatch-n (list [:complete-request :login] [:set-active-page {:page :home}]) :set-hash {:hash "/"}}))) (rf/reg-event-fx :logout remove-user-interceptor (fn-traced [{:keys [db]} _] {:db (dissoc db :user :portfolio :asset-type :capitalization :investment-style :location :loading :errors :re-frame-datatable.core/re-frame-datatable) :dispatch [:set-active-page {:page :home}] :set-hash {:hash "/"}})) ;; -- GET Portfolio @ api/v1/reports/portfolio -------------------------------- (rf/reg-event-fx :portfolio (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "portfolio"))) (rf/reg-event-fx :portfolio-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "portfolio"))) ;; -- GET Asset-type @ api/v1/reports/asset-type ------------------------------ (rf/reg-event-fx :asset-type (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "asset-type"))) (rf/reg-event-fx :asset-type-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "asset-type"))) ;; -- GET Asset-type @ api/v1/reports/capitalization -------------------------- (rf/reg-event-fx :capitalization (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "capitalization"))) (rf/reg-event-fx :capitalization-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "capitalization"))) ;; -- GET Asset-type @ api/v1/reports/investment-style ------------------------ (rf/reg-event-fx :investment-style (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "investment-style"))) (rf/reg-event-fx :investment-style-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "investment-style"))) ;; -- GET Asset-type @ api/v1/reports/location -------------------------------- (rf/reg-event-fx :location (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "location"))) (rf/reg-event-fx :location-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "location"))) ;; -- Request Handlers ----------------------------------------------------------- (rf/reg-event-db :complete-request (fn-traced [db [_ request-type]] (assoc-in db [:loading request-type] false))) (rf/reg-event-fx :api-request-error (fn-traced [{:keys [db]} [_ request-type response]] {:db (-> db (assoc-in [:errors request-type] (-> response :status-text))) :dispatch [:complete-request request-type]}))
73469
(ns app.events (:require-macros [cljs-log.core :as log]) (:require [app.db :as db] [app.util :as util] [ajax.core :refer [json-request-format json-response-format]] [clojure.string :as string] [day8.re-frame.http-fx] ;; :http-xhrio self-register with re-frame [day8.re-frame.tracing :refer-macros [fn-traced]] [re-frame.core :as rf])) (goog-define backend-uri "localhost:8080") ;; -- utils ------------------------------------------------------------------- (def set-user-interceptor [(rf/path :user) (rf/after db/set-user-ls) rf/trim-v]) (def remove-user-interceptor [(rf/after db/remove-user-ls)]) (defn endpoint [& params] (let [api-prefix "api/v1" prefix (str backend-uri "/" api-prefix) joined-endpoint (string/join "/" (concat [prefix] params))] (log/debug "endpoint is: " joined-endpoint) joined-endpoint)) (defn auth-header [db] "Get user token and format for API authorization" (let [token (-> db :user :token)] (log/debug "auth-header called. token is: " token) (if token [:Authorization (str "Token " token)] nil))) (defn dispatch-report [db body report] (let [user (-> db :user :user) password (-> db :user :token) report-cached? (some? (util/get-report db report))] (if report-cached? {:db (-> db ; this is the body of the report-success fn (assoc-in [:loading (keyword report)] false) (assoc :active-page (keyword report))) :dispatch-n (list [:complete-request (keyword report)])} {:db (assoc-in db [:loading (-> report keyword)] true) :http-xhrio {:method :get :uri (endpoint "reports" report) :headers (auth-header db) :params {:user user :password <PASSWORD>} :format (json-request-format) :response-format (json-response-format {:keywords? true}) :on-success [(-> report name (str "-success") keyword)] :on-failure [:api-request-error (keyword report)]}}))) (defn report-success [db result report] {:db (-> db (assoc-in [:loading (keyword report)] false) (assoc :active-page (keyword report)) (assoc (keyword report) result)) :dispatch-n (list [:complete-request (keyword report)])}) (rf/reg-fx :set-hash (fn [{:keys [hash]}] (set! (.-hash js/location) hash))) ;; -- init -------------------------------------------------------------------- (rf/reg-event-fx ;; usage: (dispatch [:initialise-db]) :initialize-db [(rf/inject-cofx :local-store-user) #_s/check-spec-interceptor] (fn-traced [{:keys [db local-store-user]} _] {:db (-> db/default-db (assoc :user local-store-user))})) (rf/reg-event-fx ;; usage: (dispatch [:set-active-page {:page :home}) :set-active-page ;; when user clicks on a link to go to a another page (fn-traced [{:keys [db]} [_ {:keys [page ;; destructure 2nd parameter slug ;; to obtain keys profile]}]] (let [set-page (assoc db :active-page page)] (case page ;; -- URL @ "/" | "/login" | "/register" --------------------- (:home :login :register) {:db set-page} ;; -- URL @ "/portfolio" ------------------------------------- :portfolio {:dispatch [:portfolio]} ;; -- URL @ "/asset-type" ------------------------------------ :asset-type {:dispatch [:asset-type]} ;; -- URL @ "/investment-style" ------------------------------ :investment-style {:dispatch [:investment-style]} ;; -- URL @ "/capitalization" --------------------------------- :capitalization {:dispatch [:capitalization]} ;; -- URL @ "/location" --------------------------------------- :location {:dispatch [:location]})))) ;; -- POST Login @ /api/login ------------------------------------------------- (rf/reg-event-fx :login (fn-traced [{:keys [db]} [_ body]] {:db (assoc-in db [:loading :login] true) :http-xhrio {:method :post :uri (endpoint "login") :headers (auth-header db) :params body :format (json-request-format) :response-format (json-response-format {:keywords? true}) :on-success [:login-success] :on-failure [:api-request-error :login]}})) (rf/reg-event-fx :login-success set-user-interceptor (fn-traced [{user :db} response] (let [user' (-> response first :user) token (-> response first :token)] {:db (assoc user :user user' :token token) :dispatch-n (list [:complete-request :login] [:set-active-page {:page :home}]) :set-hash {:hash "/"}}))) (rf/reg-event-fx :logout remove-user-interceptor (fn-traced [{:keys [db]} _] {:db (dissoc db :user :portfolio :asset-type :capitalization :investment-style :location :loading :errors :re-frame-datatable.core/re-frame-datatable) :dispatch [:set-active-page {:page :home}] :set-hash {:hash "/"}})) ;; -- GET Portfolio @ api/v1/reports/portfolio -------------------------------- (rf/reg-event-fx :portfolio (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "portfolio"))) (rf/reg-event-fx :portfolio-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "portfolio"))) ;; -- GET Asset-type @ api/v1/reports/asset-type ------------------------------ (rf/reg-event-fx :asset-type (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "asset-type"))) (rf/reg-event-fx :asset-type-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "asset-type"))) ;; -- GET Asset-type @ api/v1/reports/capitalization -------------------------- (rf/reg-event-fx :capitalization (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "capitalization"))) (rf/reg-event-fx :capitalization-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "capitalization"))) ;; -- GET Asset-type @ api/v1/reports/investment-style ------------------------ (rf/reg-event-fx :investment-style (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "investment-style"))) (rf/reg-event-fx :investment-style-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "investment-style"))) ;; -- GET Asset-type @ api/v1/reports/location -------------------------------- (rf/reg-event-fx :location (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "location"))) (rf/reg-event-fx :location-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "location"))) ;; -- Request Handlers ----------------------------------------------------------- (rf/reg-event-db :complete-request (fn-traced [db [_ request-type]] (assoc-in db [:loading request-type] false))) (rf/reg-event-fx :api-request-error (fn-traced [{:keys [db]} [_ request-type response]] {:db (-> db (assoc-in [:errors request-type] (-> response :status-text))) :dispatch [:complete-request request-type]}))
true
(ns app.events (:require-macros [cljs-log.core :as log]) (:require [app.db :as db] [app.util :as util] [ajax.core :refer [json-request-format json-response-format]] [clojure.string :as string] [day8.re-frame.http-fx] ;; :http-xhrio self-register with re-frame [day8.re-frame.tracing :refer-macros [fn-traced]] [re-frame.core :as rf])) (goog-define backend-uri "localhost:8080") ;; -- utils ------------------------------------------------------------------- (def set-user-interceptor [(rf/path :user) (rf/after db/set-user-ls) rf/trim-v]) (def remove-user-interceptor [(rf/after db/remove-user-ls)]) (defn endpoint [& params] (let [api-prefix "api/v1" prefix (str backend-uri "/" api-prefix) joined-endpoint (string/join "/" (concat [prefix] params))] (log/debug "endpoint is: " joined-endpoint) joined-endpoint)) (defn auth-header [db] "Get user token and format for API authorization" (let [token (-> db :user :token)] (log/debug "auth-header called. token is: " token) (if token [:Authorization (str "Token " token)] nil))) (defn dispatch-report [db body report] (let [user (-> db :user :user) password (-> db :user :token) report-cached? (some? (util/get-report db report))] (if report-cached? {:db (-> db ; this is the body of the report-success fn (assoc-in [:loading (keyword report)] false) (assoc :active-page (keyword report))) :dispatch-n (list [:complete-request (keyword report)])} {:db (assoc-in db [:loading (-> report keyword)] true) :http-xhrio {:method :get :uri (endpoint "reports" report) :headers (auth-header db) :params {:user user :password PI:PASSWORD:<PASSWORD>END_PI} :format (json-request-format) :response-format (json-response-format {:keywords? true}) :on-success [(-> report name (str "-success") keyword)] :on-failure [:api-request-error (keyword report)]}}))) (defn report-success [db result report] {:db (-> db (assoc-in [:loading (keyword report)] false) (assoc :active-page (keyword report)) (assoc (keyword report) result)) :dispatch-n (list [:complete-request (keyword report)])}) (rf/reg-fx :set-hash (fn [{:keys [hash]}] (set! (.-hash js/location) hash))) ;; -- init -------------------------------------------------------------------- (rf/reg-event-fx ;; usage: (dispatch [:initialise-db]) :initialize-db [(rf/inject-cofx :local-store-user) #_s/check-spec-interceptor] (fn-traced [{:keys [db local-store-user]} _] {:db (-> db/default-db (assoc :user local-store-user))})) (rf/reg-event-fx ;; usage: (dispatch [:set-active-page {:page :home}) :set-active-page ;; when user clicks on a link to go to a another page (fn-traced [{:keys [db]} [_ {:keys [page ;; destructure 2nd parameter slug ;; to obtain keys profile]}]] (let [set-page (assoc db :active-page page)] (case page ;; -- URL @ "/" | "/login" | "/register" --------------------- (:home :login :register) {:db set-page} ;; -- URL @ "/portfolio" ------------------------------------- :portfolio {:dispatch [:portfolio]} ;; -- URL @ "/asset-type" ------------------------------------ :asset-type {:dispatch [:asset-type]} ;; -- URL @ "/investment-style" ------------------------------ :investment-style {:dispatch [:investment-style]} ;; -- URL @ "/capitalization" --------------------------------- :capitalization {:dispatch [:capitalization]} ;; -- URL @ "/location" --------------------------------------- :location {:dispatch [:location]})))) ;; -- POST Login @ /api/login ------------------------------------------------- (rf/reg-event-fx :login (fn-traced [{:keys [db]} [_ body]] {:db (assoc-in db [:loading :login] true) :http-xhrio {:method :post :uri (endpoint "login") :headers (auth-header db) :params body :format (json-request-format) :response-format (json-response-format {:keywords? true}) :on-success [:login-success] :on-failure [:api-request-error :login]}})) (rf/reg-event-fx :login-success set-user-interceptor (fn-traced [{user :db} response] (let [user' (-> response first :user) token (-> response first :token)] {:db (assoc user :user user' :token token) :dispatch-n (list [:complete-request :login] [:set-active-page {:page :home}]) :set-hash {:hash "/"}}))) (rf/reg-event-fx :logout remove-user-interceptor (fn-traced [{:keys [db]} _] {:db (dissoc db :user :portfolio :asset-type :capitalization :investment-style :location :loading :errors :re-frame-datatable.core/re-frame-datatable) :dispatch [:set-active-page {:page :home}] :set-hash {:hash "/"}})) ;; -- GET Portfolio @ api/v1/reports/portfolio -------------------------------- (rf/reg-event-fx :portfolio (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "portfolio"))) (rf/reg-event-fx :portfolio-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "portfolio"))) ;; -- GET Asset-type @ api/v1/reports/asset-type ------------------------------ (rf/reg-event-fx :asset-type (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "asset-type"))) (rf/reg-event-fx :asset-type-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "asset-type"))) ;; -- GET Asset-type @ api/v1/reports/capitalization -------------------------- (rf/reg-event-fx :capitalization (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "capitalization"))) (rf/reg-event-fx :capitalization-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "capitalization"))) ;; -- GET Asset-type @ api/v1/reports/investment-style ------------------------ (rf/reg-event-fx :investment-style (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "investment-style"))) (rf/reg-event-fx :investment-style-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "investment-style"))) ;; -- GET Asset-type @ api/v1/reports/location -------------------------------- (rf/reg-event-fx :location (fn-traced [{:keys [db]} [_ body]] (dispatch-report db body "location"))) (rf/reg-event-fx :location-success (fn-traced [{:keys [db]} [_ {result :body}]] (report-success db result "location"))) ;; -- Request Handlers ----------------------------------------------------------- (rf/reg-event-db :complete-request (fn-traced [db [_ request-type]] (assoc-in db [:loading request-type] false))) (rf/reg-event-fx :api-request-error (fn-traced [{:keys [db]} [_ request-type response]] {:db (-> db (assoc-in [:errors request-type] (-> response :status-text))) :dispatch [:complete-request request-type]}))
[ { "context": "; Copyright 2015 Zalando SE\n;\n; Licensed under the Apache License, Version 2.", "end": 27, "score": 0.8787415027618408, "start": 17, "tag": "NAME", "value": "Zalando SE" }, { "context": " :tokens {\"http-audit-logger\" [\"uid\"]}}))]\n\n (system/run configuration system)))\n\n", "end": 2469, "score": 0.49089187383651733, "start": 2466, "tag": "KEY", "value": "uid" } ]
src/org/zalando/stups/kio/core.clj
oporkka/kio
25
; Copyright 2015 Zalando SE ; ; 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 org.zalando.stups.kio.core (:require [com.stuartsierra.component :refer [using system-map]] [org.zalando.stups.friboo.config :as config] [org.zalando.stups.friboo.system :as system] [org.zalando.stups.kio.sql :as sql] [org.zalando.stups.kio.api :as api] [org.zalando.stups.kio.metrics :as app-metrics] [org.zalando.stups.friboo.system.oauth2 :as o2] [org.zalando.stups.friboo.system.audit-logger.http :as http-logger] [org.zalando.stups.friboo.log :as log]) (:gen-class)) (defn run "Initializes and starts the whole system." [default-configuration] (let [configuration (config/load-configuration (system/default-http-namespaces-and :db :oauth2 :httplogger) [sql/default-db-configuration api/default-http-configuration default-configuration]) system (system/http-system-map configuration api/map->API [:db :http-audit-logger :app-metrics] :db (sql/map->DB {:configuration (:db configuration)}) :app-metrics (using (app-metrics/map->DeprecationMetrics {}) [:metrics]) :http-audit-logger (using (http-logger/map->HTTP {:configuration (assoc (:httplogger configuration) :token-name "http-audit-logger")}) [:tokens]) :tokens (o2/map->OAuth2TokenRefresher {:configuration (:oauth2 configuration) :tokens {"http-audit-logger" ["uid"]}}))] (system/run configuration system))) (defn -main "The actual main for our uberjar." [& args] (try (run {}) (catch Exception e (log/error e "Could not start system because of %s." (str e)) (System/exit 1))))
96108
; Copyright 2015 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns org.zalando.stups.kio.core (:require [com.stuartsierra.component :refer [using system-map]] [org.zalando.stups.friboo.config :as config] [org.zalando.stups.friboo.system :as system] [org.zalando.stups.kio.sql :as sql] [org.zalando.stups.kio.api :as api] [org.zalando.stups.kio.metrics :as app-metrics] [org.zalando.stups.friboo.system.oauth2 :as o2] [org.zalando.stups.friboo.system.audit-logger.http :as http-logger] [org.zalando.stups.friboo.log :as log]) (:gen-class)) (defn run "Initializes and starts the whole system." [default-configuration] (let [configuration (config/load-configuration (system/default-http-namespaces-and :db :oauth2 :httplogger) [sql/default-db-configuration api/default-http-configuration default-configuration]) system (system/http-system-map configuration api/map->API [:db :http-audit-logger :app-metrics] :db (sql/map->DB {:configuration (:db configuration)}) :app-metrics (using (app-metrics/map->DeprecationMetrics {}) [:metrics]) :http-audit-logger (using (http-logger/map->HTTP {:configuration (assoc (:httplogger configuration) :token-name "http-audit-logger")}) [:tokens]) :tokens (o2/map->OAuth2TokenRefresher {:configuration (:oauth2 configuration) :tokens {"http-audit-logger" ["<KEY>"]}}))] (system/run configuration system))) (defn -main "The actual main for our uberjar." [& args] (try (run {}) (catch Exception e (log/error e "Could not start system because of %s." (str e)) (System/exit 1))))
true
; Copyright 2015 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns org.zalando.stups.kio.core (:require [com.stuartsierra.component :refer [using system-map]] [org.zalando.stups.friboo.config :as config] [org.zalando.stups.friboo.system :as system] [org.zalando.stups.kio.sql :as sql] [org.zalando.stups.kio.api :as api] [org.zalando.stups.kio.metrics :as app-metrics] [org.zalando.stups.friboo.system.oauth2 :as o2] [org.zalando.stups.friboo.system.audit-logger.http :as http-logger] [org.zalando.stups.friboo.log :as log]) (:gen-class)) (defn run "Initializes and starts the whole system." [default-configuration] (let [configuration (config/load-configuration (system/default-http-namespaces-and :db :oauth2 :httplogger) [sql/default-db-configuration api/default-http-configuration default-configuration]) system (system/http-system-map configuration api/map->API [:db :http-audit-logger :app-metrics] :db (sql/map->DB {:configuration (:db configuration)}) :app-metrics (using (app-metrics/map->DeprecationMetrics {}) [:metrics]) :http-audit-logger (using (http-logger/map->HTTP {:configuration (assoc (:httplogger configuration) :token-name "http-audit-logger")}) [:tokens]) :tokens (o2/map->OAuth2TokenRefresher {:configuration (:oauth2 configuration) :tokens {"http-audit-logger" ["PI:KEY:<KEY>END_PI"]}}))] (system/run configuration system))) (defn -main "The actual main for our uberjar." [& args] (try (run {}) (catch Exception e (log/error e "Could not start system because of %s." (str e)) (System/exit 1))))
[ { "context": ";; The MIT License (MIT)\n\n;; Copyright (c) 2016 Stuart Sierra\n\n;; Permission is hereby granted, free of charge,", "end": 61, "score": 0.999854564666748, "start": 48, "tag": "NAME", "value": "Stuart Sierra" } ]
test/com/stuartsierra/mapgraph/spec.clj
vimsical/mapgraph
69
;; The MIT License (MIT) ;; Copyright (c) 2016 Stuart Sierra ;; 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 com.stuartsierra.mapgraph.spec "clojure.spec definitions for mapgraph functions. Requires Clojure 1.9.0." (:require [clojure.spec :as s] [com.stuartsierra.mapgraph :as mg])) (s/def ::mg/db mg/db?) (s/def ::mg/entity (s/map-of keyword? ::s/any)) (s/def ::mg/reference (s/and vector? (s/tuple keyword? ::s/any))) (s/def ::mg/pull-pattern (s/* (s/or :attr keyword? :star #{'*} :join (s/map-of keyword? ::mg/pull-pattern)))) (s/fdef mg/add-id-attr :args (s/cat :db ::mg/db :idents (s/* keyword?)) :ret ::mg/db) (s/fdef mg/add :args (s/& (s/cat :db ::mg/db :entities (s/* ::mg/entity)) (fn [{:keys [db entities]}] (every? #(mg/entity? db %) entities))) :ret ::mg/db :fn (fn [{:keys [ret args]}] (let [{:keys [db entities]} args] (every? #(contains? ret (mg/ref-to db %)) entities)))) (s/fdef mg/pull :args (s/& (s/cat :db ::mg/db :pull (s/spec ::mg/pull-pattern) :ref ::mg/reference) (fn [{:keys [db ref]}] (mg/ref? db ref))) :ret (s/nilable map?)) ;; Local Variables: ;; eval: (put-clojure-indent 'fdef :defn) ;; End:
120999
;; The MIT License (MIT) ;; Copyright (c) 2016 <NAME> ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns com.stuartsierra.mapgraph.spec "clojure.spec definitions for mapgraph functions. Requires Clojure 1.9.0." (:require [clojure.spec :as s] [com.stuartsierra.mapgraph :as mg])) (s/def ::mg/db mg/db?) (s/def ::mg/entity (s/map-of keyword? ::s/any)) (s/def ::mg/reference (s/and vector? (s/tuple keyword? ::s/any))) (s/def ::mg/pull-pattern (s/* (s/or :attr keyword? :star #{'*} :join (s/map-of keyword? ::mg/pull-pattern)))) (s/fdef mg/add-id-attr :args (s/cat :db ::mg/db :idents (s/* keyword?)) :ret ::mg/db) (s/fdef mg/add :args (s/& (s/cat :db ::mg/db :entities (s/* ::mg/entity)) (fn [{:keys [db entities]}] (every? #(mg/entity? db %) entities))) :ret ::mg/db :fn (fn [{:keys [ret args]}] (let [{:keys [db entities]} args] (every? #(contains? ret (mg/ref-to db %)) entities)))) (s/fdef mg/pull :args (s/& (s/cat :db ::mg/db :pull (s/spec ::mg/pull-pattern) :ref ::mg/reference) (fn [{:keys [db ref]}] (mg/ref? db ref))) :ret (s/nilable map?)) ;; Local Variables: ;; eval: (put-clojure-indent 'fdef :defn) ;; End:
true
;; The MIT License (MIT) ;; Copyright (c) 2016 PI:NAME:<NAME>END_PI ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns com.stuartsierra.mapgraph.spec "clojure.spec definitions for mapgraph functions. Requires Clojure 1.9.0." (:require [clojure.spec :as s] [com.stuartsierra.mapgraph :as mg])) (s/def ::mg/db mg/db?) (s/def ::mg/entity (s/map-of keyword? ::s/any)) (s/def ::mg/reference (s/and vector? (s/tuple keyword? ::s/any))) (s/def ::mg/pull-pattern (s/* (s/or :attr keyword? :star #{'*} :join (s/map-of keyword? ::mg/pull-pattern)))) (s/fdef mg/add-id-attr :args (s/cat :db ::mg/db :idents (s/* keyword?)) :ret ::mg/db) (s/fdef mg/add :args (s/& (s/cat :db ::mg/db :entities (s/* ::mg/entity)) (fn [{:keys [db entities]}] (every? #(mg/entity? db %) entities))) :ret ::mg/db :fn (fn [{:keys [ret args]}] (let [{:keys [db entities]} args] (every? #(contains? ret (mg/ref-to db %)) entities)))) (s/fdef mg/pull :args (s/& (s/cat :db ::mg/db :pull (s/spec ::mg/pull-pattern) :ref ::mg/reference) (fn [{:keys [db ref]}] (mg/ref? db ref))) :ret (s/nilable map?)) ;; Local Variables: ;; eval: (put-clojure-indent 'fdef :defn) ;; End:
[ { "context": "p-tools!)\n (setup-deps!))\n\n\n;; TODO: [2022-02-11, ilshat@sultanov.team] Add a global shortcut to search for a library or", "end": 2364, "score": 0.9999113082885742, "start": 2344, "tag": "EMAIL", "value": "ilshat@sultanov.team" } ]
src/main/clojure/metaverse/runner.cljs
sultanov-team/metaverse
1
(ns metaverse.runner (:require [clojure.string :as str] [metaverse.common.logger :as log :include-macros true] [metaverse.common.supabase :as supabase] [metaverse.common.utils.transit :as t] [metaverse.runner.api :as api] [metaverse.runner.api.auth] [metaverse.runner.api.news] [metaverse.runner.config :as config] [metaverse.runner.electron.app :as app] [metaverse.runner.electron.ipc-main :as ipc-main] [metaverse.runner.electron.menu :as menu] [metaverse.runner.electron.tray :as tray] [metaverse.runner.electron.window :as window] [metaverse.runner.main.menu :as main.menu] [metaverse.runner.main.tray :as main.tray] [metaverse.runner.main.window :as main.window] [metaverse.runner.sentry :as sentry] [metaverse.runner.utils.platform :as platform] [tenet.response :as r])) (declare mount dispatch) ;; ;; Event handlers ;; (defn activate-handler [] (when (window/recreate-window?) (mount))) (defn open-url-handler [_event url] (when (str/starts-with? url "metaverse://app") (dispatch (r/as-success [:open-url url])))) (defn closed-handler {:dev/before-load true} [] (main.tray/destroy!) (main.window/destroy!)) (defn ready-to-show-handler [_window _tray] (fn [])) (defn window-all-closed-handler [] (when-not platform/mac-os? (app/quit))) (defn tray-click-handler [window] (fn [_event bounds] (let [bounds (main.window/calculate-window-position window bounds)] (window/set-bounds window bounds) (window/toggle-window window)))) (defn invoke-handler [ipc-event event] (when-some [event (t/read event)] (-> (api/invoke ipc-event event) (t/then-write)))) (defn send-handler [ipc-event event] (when-some [event (t/read event)] (api/invoke ipc-event event))) (defn dispatch "Dispatch event on renderer. Runner => Renderer (one way)" [event] (let [window ^js/electron.BrowserWindow (main.window/get-instance) web-contents ^js/electron.BrowserWindow.webContents (.. window -webContents)] (.send web-contents "dispatch" (t/write event)))) ;; ;; Initializers ;; (defn setup-tools! [] (log/init!) (sentry/init!)) (defn setup-deps! [] (supabase/init!)) (defn setup! [] (setup-tools!) (setup-deps!)) ;; TODO: [2022-02-11, ilshat@sultanov.team] Add a global shortcut to search for a library or docs / to create a new project? ;; example: (keyboard/register-global-shortcut! "Alt+CommandOrControl+I" #(window/toggle-devtools window)) (defn setup-global-shortcuts! [_window]) ;; ;; Mount root ;; (defn mount {:dev/after-load true} [] (when (window/recreate-window?) (let [window (main.window/create-window) menu (main.menu/create-menu window) tray (main.tray/create-tray window)] (app/dock-hide) (app/set-as-default-protocol-client "metaverse") (setup-global-shortcuts! window) (tray/set-tooltip tray config/title) (menu/set-application-menu menu) (main.window/hide-traffic-lights! window) (main.window/set-instance! window) (main.window/load-app window) (window/on "closed" window closed-handler) (window/on "ready-to-show" window (ready-to-show-handler window tray)) (tray/on "click" tray (tray-click-handler window))))) ;; ;; Entry point ;; (defn -main "Runner entry point." {:export true} [& _args] (setup!) (app/on "ready" (fn [] (mount) (app/on "activate" activate-handler) (app/on "open-url" open-url-handler) (app/on "window-all-closed" window-all-closed-handler) (ipc-main/remove-all-listeners!) (ipc-main/handle "invoke" invoke-handler) (ipc-main/on "send" send-handler))))
56042
(ns metaverse.runner (:require [clojure.string :as str] [metaverse.common.logger :as log :include-macros true] [metaverse.common.supabase :as supabase] [metaverse.common.utils.transit :as t] [metaverse.runner.api :as api] [metaverse.runner.api.auth] [metaverse.runner.api.news] [metaverse.runner.config :as config] [metaverse.runner.electron.app :as app] [metaverse.runner.electron.ipc-main :as ipc-main] [metaverse.runner.electron.menu :as menu] [metaverse.runner.electron.tray :as tray] [metaverse.runner.electron.window :as window] [metaverse.runner.main.menu :as main.menu] [metaverse.runner.main.tray :as main.tray] [metaverse.runner.main.window :as main.window] [metaverse.runner.sentry :as sentry] [metaverse.runner.utils.platform :as platform] [tenet.response :as r])) (declare mount dispatch) ;; ;; Event handlers ;; (defn activate-handler [] (when (window/recreate-window?) (mount))) (defn open-url-handler [_event url] (when (str/starts-with? url "metaverse://app") (dispatch (r/as-success [:open-url url])))) (defn closed-handler {:dev/before-load true} [] (main.tray/destroy!) (main.window/destroy!)) (defn ready-to-show-handler [_window _tray] (fn [])) (defn window-all-closed-handler [] (when-not platform/mac-os? (app/quit))) (defn tray-click-handler [window] (fn [_event bounds] (let [bounds (main.window/calculate-window-position window bounds)] (window/set-bounds window bounds) (window/toggle-window window)))) (defn invoke-handler [ipc-event event] (when-some [event (t/read event)] (-> (api/invoke ipc-event event) (t/then-write)))) (defn send-handler [ipc-event event] (when-some [event (t/read event)] (api/invoke ipc-event event))) (defn dispatch "Dispatch event on renderer. Runner => Renderer (one way)" [event] (let [window ^js/electron.BrowserWindow (main.window/get-instance) web-contents ^js/electron.BrowserWindow.webContents (.. window -webContents)] (.send web-contents "dispatch" (t/write event)))) ;; ;; Initializers ;; (defn setup-tools! [] (log/init!) (sentry/init!)) (defn setup-deps! [] (supabase/init!)) (defn setup! [] (setup-tools!) (setup-deps!)) ;; TODO: [2022-02-11, <EMAIL>] Add a global shortcut to search for a library or docs / to create a new project? ;; example: (keyboard/register-global-shortcut! "Alt+CommandOrControl+I" #(window/toggle-devtools window)) (defn setup-global-shortcuts! [_window]) ;; ;; Mount root ;; (defn mount {:dev/after-load true} [] (when (window/recreate-window?) (let [window (main.window/create-window) menu (main.menu/create-menu window) tray (main.tray/create-tray window)] (app/dock-hide) (app/set-as-default-protocol-client "metaverse") (setup-global-shortcuts! window) (tray/set-tooltip tray config/title) (menu/set-application-menu menu) (main.window/hide-traffic-lights! window) (main.window/set-instance! window) (main.window/load-app window) (window/on "closed" window closed-handler) (window/on "ready-to-show" window (ready-to-show-handler window tray)) (tray/on "click" tray (tray-click-handler window))))) ;; ;; Entry point ;; (defn -main "Runner entry point." {:export true} [& _args] (setup!) (app/on "ready" (fn [] (mount) (app/on "activate" activate-handler) (app/on "open-url" open-url-handler) (app/on "window-all-closed" window-all-closed-handler) (ipc-main/remove-all-listeners!) (ipc-main/handle "invoke" invoke-handler) (ipc-main/on "send" send-handler))))
true
(ns metaverse.runner (:require [clojure.string :as str] [metaverse.common.logger :as log :include-macros true] [metaverse.common.supabase :as supabase] [metaverse.common.utils.transit :as t] [metaverse.runner.api :as api] [metaverse.runner.api.auth] [metaverse.runner.api.news] [metaverse.runner.config :as config] [metaverse.runner.electron.app :as app] [metaverse.runner.electron.ipc-main :as ipc-main] [metaverse.runner.electron.menu :as menu] [metaverse.runner.electron.tray :as tray] [metaverse.runner.electron.window :as window] [metaverse.runner.main.menu :as main.menu] [metaverse.runner.main.tray :as main.tray] [metaverse.runner.main.window :as main.window] [metaverse.runner.sentry :as sentry] [metaverse.runner.utils.platform :as platform] [tenet.response :as r])) (declare mount dispatch) ;; ;; Event handlers ;; (defn activate-handler [] (when (window/recreate-window?) (mount))) (defn open-url-handler [_event url] (when (str/starts-with? url "metaverse://app") (dispatch (r/as-success [:open-url url])))) (defn closed-handler {:dev/before-load true} [] (main.tray/destroy!) (main.window/destroy!)) (defn ready-to-show-handler [_window _tray] (fn [])) (defn window-all-closed-handler [] (when-not platform/mac-os? (app/quit))) (defn tray-click-handler [window] (fn [_event bounds] (let [bounds (main.window/calculate-window-position window bounds)] (window/set-bounds window bounds) (window/toggle-window window)))) (defn invoke-handler [ipc-event event] (when-some [event (t/read event)] (-> (api/invoke ipc-event event) (t/then-write)))) (defn send-handler [ipc-event event] (when-some [event (t/read event)] (api/invoke ipc-event event))) (defn dispatch "Dispatch event on renderer. Runner => Renderer (one way)" [event] (let [window ^js/electron.BrowserWindow (main.window/get-instance) web-contents ^js/electron.BrowserWindow.webContents (.. window -webContents)] (.send web-contents "dispatch" (t/write event)))) ;; ;; Initializers ;; (defn setup-tools! [] (log/init!) (sentry/init!)) (defn setup-deps! [] (supabase/init!)) (defn setup! [] (setup-tools!) (setup-deps!)) ;; TODO: [2022-02-11, PI:EMAIL:<EMAIL>END_PI] Add a global shortcut to search for a library or docs / to create a new project? ;; example: (keyboard/register-global-shortcut! "Alt+CommandOrControl+I" #(window/toggle-devtools window)) (defn setup-global-shortcuts! [_window]) ;; ;; Mount root ;; (defn mount {:dev/after-load true} [] (when (window/recreate-window?) (let [window (main.window/create-window) menu (main.menu/create-menu window) tray (main.tray/create-tray window)] (app/dock-hide) (app/set-as-default-protocol-client "metaverse") (setup-global-shortcuts! window) (tray/set-tooltip tray config/title) (menu/set-application-menu menu) (main.window/hide-traffic-lights! window) (main.window/set-instance! window) (main.window/load-app window) (window/on "closed" window closed-handler) (window/on "ready-to-show" window (ready-to-show-handler window tray)) (tray/on "click" tray (tray-click-handler window))))) ;; ;; Entry point ;; (defn -main "Runner entry point." {:export true} [& _args] (setup!) (app/on "ready" (fn [] (mount) (app/on "activate" activate-handler) (app/on "open-url" open-url-handler) (app/on "window-all-closed" window-all-closed-handler) (ipc-main/remove-all-listeners!) (ipc-main/handle "invoke" invoke-handler) (ipc-main/on "send" send-handler))))
[ { "context": "d)\n [:div.form-inline\n (fm/text-field :username)\n (fm/submit-button \"OK\")])]])\n\n(defn html-", "end": 1000, "score": 0.6561862230300903, "start": 992, "tag": "USERNAME", "value": "username" }, { "context": " [:br] [:br]\n (html-table [\"message id\" \"username\" \"liker name\" \"liker count\"] rows)])])\n", "end": 1796, "score": 0.9993901252746582, "start": 1788, "tag": "USERNAME", "value": "username" }, { "context": "[:br]\n (html-table [\"message id\" \"username\" \"liker name\" \"liker count\"] rows)])])\n", "end": 1809, "score": 0.8153700828552246, "start": 1799, "tag": "NAME", "value": "liker name" } ]
src/api_octopus/web/layout.clj
0x7c48/dribbble-stats
2
(ns api-octopus.web.layout (:require [ring.util.anti-forgery :refer [anti-forgery-field]] [hiccup.page :refer [html5 include-css include-js]] [hiccup [core :as hi] [form :as fm] [element :as el]])) (defn application [title & content] (html5 {:ng-app "app" :lang "en"} [:head [:title title] (include-css "http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css") (include-js "/js/main.js") [:body [:div {:class "container"} content ]]])) (defn index [] [:div {:id "content"} [:h1 "api-octopus - dribbble.com stats project"] [:div (el/ordered-list ["For a given Dribbble user find all followers" "For each follower find all shots" "For each shot find all 'likers'" "Calculate Top 10 'likers'"])] [:div.form-group (fm/form-to [:post "/username"] (anti-forgery-field) [:div.form-inline (fm/text-field :username) (fm/submit-button "OK")])]]) (defn html-table [colls rows] [:table [:thead [:tr (for [coll colls] [:td (str coll)])]] [:tbody (for [{:keys [message_id username likername liker_count] :as row} rows] [:tr [:td (str message_id)] [:td (str username)] [:td (str likername)] [:td (str liker_count)]])]]) (defn index-post [data] [:div {:id "content"} [:h1 {:class "text-success"} "Username sent to Kafka"] [:div [:p (str (:username data) " " (:message_id data))]] [:div (el/link-to (str "/top10?username=" (:username data) "&message_id=" (:message_id data)) "Get top 10 likers")] (when-let [rows (:rows data)] [:div.mid [:br] [:br] (html-table ["message id" "username" "liker name" "liker count"] rows)])])
8682
(ns api-octopus.web.layout (:require [ring.util.anti-forgery :refer [anti-forgery-field]] [hiccup.page :refer [html5 include-css include-js]] [hiccup [core :as hi] [form :as fm] [element :as el]])) (defn application [title & content] (html5 {:ng-app "app" :lang "en"} [:head [:title title] (include-css "http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css") (include-js "/js/main.js") [:body [:div {:class "container"} content ]]])) (defn index [] [:div {:id "content"} [:h1 "api-octopus - dribbble.com stats project"] [:div (el/ordered-list ["For a given Dribbble user find all followers" "For each follower find all shots" "For each shot find all 'likers'" "Calculate Top 10 'likers'"])] [:div.form-group (fm/form-to [:post "/username"] (anti-forgery-field) [:div.form-inline (fm/text-field :username) (fm/submit-button "OK")])]]) (defn html-table [colls rows] [:table [:thead [:tr (for [coll colls] [:td (str coll)])]] [:tbody (for [{:keys [message_id username likername liker_count] :as row} rows] [:tr [:td (str message_id)] [:td (str username)] [:td (str likername)] [:td (str liker_count)]])]]) (defn index-post [data] [:div {:id "content"} [:h1 {:class "text-success"} "Username sent to Kafka"] [:div [:p (str (:username data) " " (:message_id data))]] [:div (el/link-to (str "/top10?username=" (:username data) "&message_id=" (:message_id data)) "Get top 10 likers")] (when-let [rows (:rows data)] [:div.mid [:br] [:br] (html-table ["message id" "username" "<NAME>" "liker count"] rows)])])
true
(ns api-octopus.web.layout (:require [ring.util.anti-forgery :refer [anti-forgery-field]] [hiccup.page :refer [html5 include-css include-js]] [hiccup [core :as hi] [form :as fm] [element :as el]])) (defn application [title & content] (html5 {:ng-app "app" :lang "en"} [:head [:title title] (include-css "http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css") (include-js "/js/main.js") [:body [:div {:class "container"} content ]]])) (defn index [] [:div {:id "content"} [:h1 "api-octopus - dribbble.com stats project"] [:div (el/ordered-list ["For a given Dribbble user find all followers" "For each follower find all shots" "For each shot find all 'likers'" "Calculate Top 10 'likers'"])] [:div.form-group (fm/form-to [:post "/username"] (anti-forgery-field) [:div.form-inline (fm/text-field :username) (fm/submit-button "OK")])]]) (defn html-table [colls rows] [:table [:thead [:tr (for [coll colls] [:td (str coll)])]] [:tbody (for [{:keys [message_id username likername liker_count] :as row} rows] [:tr [:td (str message_id)] [:td (str username)] [:td (str likername)] [:td (str liker_count)]])]]) (defn index-post [data] [:div {:id "content"} [:h1 {:class "text-success"} "Username sent to Kafka"] [:div [:p (str (:username data) " " (:message_id data))]] [:div (el/link-to (str "/top10?username=" (:username data) "&message_id=" (:message_id data)) "Get top 10 likers")] (when-let [rows (:rows data)] [:div.mid [:br] [:br] (html-table ["message id" "username" "PI:NAME:<NAME>END_PI" "liker count"] rows)])])
[ { "context": "db-fixture)\n\n;; Test content\n\n(def test-username \"DonaldChamberlin123\") ; co-inventor of SQL\n\n(def test-password \"iLove", "end": 525, "score": 0.9996387958526611, "start": 506, "tag": "USERNAME", "value": "DonaldChamberlin123" }, { "context": "in123\") ; co-inventor of SQL\n\n(def test-password \"iLoveSql\")\n\n;; Tests\n\n(deftest admin-test\n (let [sys (su", "end": 578, "score": 0.9992271065711975, "start": 570, "tag": "PASSWORD", "value": "iLoveSql" }, { "context": "(-> (adp/-authenticate-account lrs test-username \"badPass\")\n :result\n (= :lrsql.a", "end": 1424, "score": 0.9571545124053955, "start": 1417, "tag": "USERNAME", "value": "badPass" } ]
src/test/lrsql/admin/protocol_test.clj
ccasey3/lrsql
0
(ns lrsql.admin.protocol-test "Test the protocol fns of `AdminAccountManager` and `APIKeyManager` directly." (:require [clojure.test :refer [deftest testing is use-fixtures]] [com.stuartsierra.component :as component] [xapi-schema.spec.regex :refer [Base64RegEx]] [lrsql.admin.protocol :as adp] [lrsql.test-support :as support])) ;; Init (support/instrument-lrsql) (use-fixtures :each support/fresh-db-fixture) ;; Test content (def test-username "DonaldChamberlin123") ; co-inventor of SQL (def test-password "iLoveSql") ;; Tests (deftest admin-test (let [sys (support/test-system) sys' (component/start sys) lrs (:lrs sys')] (testing "Admin account insertion" (is (-> (adp/-create-account lrs test-username test-password) :result uuid?)) (is (-> (adp/-create-account lrs test-username test-password) :result (= :lrsql.admin/existing-account-error)))) (testing "Admin account get" (let [accounts (adp/-get-accounts lrs)] (is (vector? accounts)) (is (some (fn [acct] (= (:username acct) test-username)) accounts)))) (testing "Admin account authentication" (is (-> (adp/-authenticate-account lrs test-username test-password) :result uuid?)) (is (-> (adp/-authenticate-account lrs test-username "badPass") :result (= :lrsql.admin/invalid-password-error))) (is (-> (adp/-authenticate-account lrs "foo" "bar") :result (= :lrsql.admin/missing-account-error)))) (testing "Admin account existence check" (let [account-id (-> (adp/-authenticate-account lrs test-username test-password) :result)] (is (adp/-existing-account? lrs account-id))) (let [bad-account-id #uuid "00000000-0000-4000-8000-000000000000"] (is (not (adp/-existing-account? lrs bad-account-id))))) (testing "Admin account deletion" (let [account-id (-> (adp/-authenticate-account lrs test-username test-password) :result)] (adp/-delete-account lrs account-id) (is (-> (adp/-authenticate-account lrs test-username test-password) :result (= :lrsql.admin/missing-account-error))))) (component/stop sys'))) ;; TODO: Add tests for creds with no explicit scopes, once ;; `statements/read/mine` is implemented (deftest auth-test (let [sys (support/test-system) sys' (component/start sys) lrs (:lrs sys') acc-id (:result (adp/-create-account lrs test-username test-password))] (testing "Credential creation" (let [{:keys [api-key secret-key] :as key-pair} (adp/-create-api-keys lrs acc-id #{"all" "all/read"})] (is (re-matches Base64RegEx api-key)) (is (re-matches Base64RegEx secret-key)) (is (= {:api-key api-key :secret-key secret-key :scopes #{"all" "all/read"}} key-pair)) (testing "and credential retrieval" (is (= [{:api-key api-key :secret-key secret-key :scopes #{"all" "all/read"}}] (adp/-get-api-keys lrs acc-id)))) (testing "and credential update" (is (= {:api-key api-key :secret-key secret-key :scopes #{"all/read" "statements/read"}} (adp/-update-api-keys lrs acc-id api-key secret-key #{"all/read" "statements/read"}))) (is (= [{:api-key api-key :secret-key secret-key :scopes #{"all/read" "statements/read"}}] (adp/-get-api-keys lrs acc-id)))) (testing "and credential deletion" (adp/-delete-api-keys lrs acc-id api-key secret-key) (is (= [] (adp/-get-api-keys lrs acc-id)))))) (component/stop sys')))
51200
(ns lrsql.admin.protocol-test "Test the protocol fns of `AdminAccountManager` and `APIKeyManager` directly." (:require [clojure.test :refer [deftest testing is use-fixtures]] [com.stuartsierra.component :as component] [xapi-schema.spec.regex :refer [Base64RegEx]] [lrsql.admin.protocol :as adp] [lrsql.test-support :as support])) ;; Init (support/instrument-lrsql) (use-fixtures :each support/fresh-db-fixture) ;; Test content (def test-username "DonaldChamberlin123") ; co-inventor of SQL (def test-password "<PASSWORD>") ;; Tests (deftest admin-test (let [sys (support/test-system) sys' (component/start sys) lrs (:lrs sys')] (testing "Admin account insertion" (is (-> (adp/-create-account lrs test-username test-password) :result uuid?)) (is (-> (adp/-create-account lrs test-username test-password) :result (= :lrsql.admin/existing-account-error)))) (testing "Admin account get" (let [accounts (adp/-get-accounts lrs)] (is (vector? accounts)) (is (some (fn [acct] (= (:username acct) test-username)) accounts)))) (testing "Admin account authentication" (is (-> (adp/-authenticate-account lrs test-username test-password) :result uuid?)) (is (-> (adp/-authenticate-account lrs test-username "badPass") :result (= :lrsql.admin/invalid-password-error))) (is (-> (adp/-authenticate-account lrs "foo" "bar") :result (= :lrsql.admin/missing-account-error)))) (testing "Admin account existence check" (let [account-id (-> (adp/-authenticate-account lrs test-username test-password) :result)] (is (adp/-existing-account? lrs account-id))) (let [bad-account-id #uuid "00000000-0000-4000-8000-000000000000"] (is (not (adp/-existing-account? lrs bad-account-id))))) (testing "Admin account deletion" (let [account-id (-> (adp/-authenticate-account lrs test-username test-password) :result)] (adp/-delete-account lrs account-id) (is (-> (adp/-authenticate-account lrs test-username test-password) :result (= :lrsql.admin/missing-account-error))))) (component/stop sys'))) ;; TODO: Add tests for creds with no explicit scopes, once ;; `statements/read/mine` is implemented (deftest auth-test (let [sys (support/test-system) sys' (component/start sys) lrs (:lrs sys') acc-id (:result (adp/-create-account lrs test-username test-password))] (testing "Credential creation" (let [{:keys [api-key secret-key] :as key-pair} (adp/-create-api-keys lrs acc-id #{"all" "all/read"})] (is (re-matches Base64RegEx api-key)) (is (re-matches Base64RegEx secret-key)) (is (= {:api-key api-key :secret-key secret-key :scopes #{"all" "all/read"}} key-pair)) (testing "and credential retrieval" (is (= [{:api-key api-key :secret-key secret-key :scopes #{"all" "all/read"}}] (adp/-get-api-keys lrs acc-id)))) (testing "and credential update" (is (= {:api-key api-key :secret-key secret-key :scopes #{"all/read" "statements/read"}} (adp/-update-api-keys lrs acc-id api-key secret-key #{"all/read" "statements/read"}))) (is (= [{:api-key api-key :secret-key secret-key :scopes #{"all/read" "statements/read"}}] (adp/-get-api-keys lrs acc-id)))) (testing "and credential deletion" (adp/-delete-api-keys lrs acc-id api-key secret-key) (is (= [] (adp/-get-api-keys lrs acc-id)))))) (component/stop sys')))
true
(ns lrsql.admin.protocol-test "Test the protocol fns of `AdminAccountManager` and `APIKeyManager` directly." (:require [clojure.test :refer [deftest testing is use-fixtures]] [com.stuartsierra.component :as component] [xapi-schema.spec.regex :refer [Base64RegEx]] [lrsql.admin.protocol :as adp] [lrsql.test-support :as support])) ;; Init (support/instrument-lrsql) (use-fixtures :each support/fresh-db-fixture) ;; Test content (def test-username "DonaldChamberlin123") ; co-inventor of SQL (def test-password "PI:PASSWORD:<PASSWORD>END_PI") ;; Tests (deftest admin-test (let [sys (support/test-system) sys' (component/start sys) lrs (:lrs sys')] (testing "Admin account insertion" (is (-> (adp/-create-account lrs test-username test-password) :result uuid?)) (is (-> (adp/-create-account lrs test-username test-password) :result (= :lrsql.admin/existing-account-error)))) (testing "Admin account get" (let [accounts (adp/-get-accounts lrs)] (is (vector? accounts)) (is (some (fn [acct] (= (:username acct) test-username)) accounts)))) (testing "Admin account authentication" (is (-> (adp/-authenticate-account lrs test-username test-password) :result uuid?)) (is (-> (adp/-authenticate-account lrs test-username "badPass") :result (= :lrsql.admin/invalid-password-error))) (is (-> (adp/-authenticate-account lrs "foo" "bar") :result (= :lrsql.admin/missing-account-error)))) (testing "Admin account existence check" (let [account-id (-> (adp/-authenticate-account lrs test-username test-password) :result)] (is (adp/-existing-account? lrs account-id))) (let [bad-account-id #uuid "00000000-0000-4000-8000-000000000000"] (is (not (adp/-existing-account? lrs bad-account-id))))) (testing "Admin account deletion" (let [account-id (-> (adp/-authenticate-account lrs test-username test-password) :result)] (adp/-delete-account lrs account-id) (is (-> (adp/-authenticate-account lrs test-username test-password) :result (= :lrsql.admin/missing-account-error))))) (component/stop sys'))) ;; TODO: Add tests for creds with no explicit scopes, once ;; `statements/read/mine` is implemented (deftest auth-test (let [sys (support/test-system) sys' (component/start sys) lrs (:lrs sys') acc-id (:result (adp/-create-account lrs test-username test-password))] (testing "Credential creation" (let [{:keys [api-key secret-key] :as key-pair} (adp/-create-api-keys lrs acc-id #{"all" "all/read"})] (is (re-matches Base64RegEx api-key)) (is (re-matches Base64RegEx secret-key)) (is (= {:api-key api-key :secret-key secret-key :scopes #{"all" "all/read"}} key-pair)) (testing "and credential retrieval" (is (= [{:api-key api-key :secret-key secret-key :scopes #{"all" "all/read"}}] (adp/-get-api-keys lrs acc-id)))) (testing "and credential update" (is (= {:api-key api-key :secret-key secret-key :scopes #{"all/read" "statements/read"}} (adp/-update-api-keys lrs acc-id api-key secret-key #{"all/read" "statements/read"}))) (is (= [{:api-key api-key :secret-key secret-key :scopes #{"all/read" "statements/read"}}] (adp/-get-api-keys lrs acc-id)))) (testing "and credential deletion" (adp/-delete-api-keys lrs acc-id api-key secret-key) (is (= [] (adp/-get-api-keys lrs acc-id)))))) (component/stop sys')))
[ { "context": "; Copyright (c) 2019-present Walmart, Inc.\n;\n; Licensed under the Apache License, Vers", "end": 36, "score": 0.6879880428314209, "start": 29, "tag": "NAME", "value": "Walmart" } ]
test/com/walmartlabs/lacinia/field_tests.clj
hagenek/lacinia
1,762
; Copyright (c) 2019-present Walmart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.field-tests (:require [clojure.test :refer [deftest is]] [com.walmartlabs.test-utils :refer [expect-exception]] [com.walmartlabs.lacinia.schema :as schema])) (deftest field-references-unknown-type (expect-exception "Field `Insect/legs' references unknown type `Six'." {:field-name :Insect/legs :schema-types {:object [:Insect :Mutation :Query :Subscription] :scalar [:Boolean :Float :ID :Int :String]}} (schema/compile {:objects {:Insect {:fields {:legs {:type :Six}}}}})))
11768
; Copyright (c) 2019-present <NAME>, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.field-tests (:require [clojure.test :refer [deftest is]] [com.walmartlabs.test-utils :refer [expect-exception]] [com.walmartlabs.lacinia.schema :as schema])) (deftest field-references-unknown-type (expect-exception "Field `Insect/legs' references unknown type `Six'." {:field-name :Insect/legs :schema-types {:object [:Insect :Mutation :Query :Subscription] :scalar [:Boolean :Float :ID :Int :String]}} (schema/compile {:objects {:Insect {:fields {:legs {:type :Six}}}}})))
true
; Copyright (c) 2019-present PI:NAME:<NAME>END_PI, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.field-tests (:require [clojure.test :refer [deftest is]] [com.walmartlabs.test-utils :refer [expect-exception]] [com.walmartlabs.lacinia.schema :as schema])) (deftest field-references-unknown-type (expect-exception "Field `Insect/legs' references unknown type `Six'." {:field-name :Insect/legs :schema-types {:object [:Insect :Mutation :Query :Subscription] :scalar [:Boolean :Float :ID :Int :String]}} (schema/compile {:objects {:Insect {:fields {:legs {:type :Six}}}}})))
[ { "context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 33, "score": 0.9036318063735962, "start": 30, "tag": "NAME", "value": "Net" } ]
pigpen-viz/src/main/clojure/pigpen/viz.clj
ombagus/Netflix
327
;; ;; ;; Copyright 2013-2015 Netflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.viz "Functions to create graph-viz graphs from PigPen queries. " (:require [rhizome.viz :as viz] [pigpen.oven :as oven])) (set! *warn-on-reflection* true) (defn ^:private command->description [{:keys [id]}] "Returns a simple human readable description of a command" (str id)) (defn ^:private command->description+ [{:keys [id description]}] "Returns a verbose human readable description of a command" (if description (str id "\n\n" description) (str id))) (def ^:private line-len 50) (def ^:private max-lines 10) (defn ^:private fix-label [label] (let [lines (clojure.string/split-lines label) label' (->> lines (map (fn [l] (if (-> l count (> line-len)) (str (subs l 0 line-len) "...") l))) (take max-lines) (clojure.string/join "\\l"))] (if (> (count lines) max-lines) (str label' "\\l...") label'))) (defn ^:private view-graph [command->description commands] (viz/view-graph (filter #(contains? % :id) commands) (fn [parent] (filter (fn [child] ((-> child :ancestors set) (:id parent))) commands)) :node->descriptor (fn [c] {:label (fix-label (command->description c)) :shape :box}))) (defn show "Generates a graph image for a PigPen query. This allows you to see what steps will be executed when the script is run. The image is opened in another window. This command uses a terse description for each operation. Example: (pigpen.core/show foo) See also: pigpen.core/show+ " {:added "0.1.0"} [query] (->> query (oven/bake :viz {} {}) (view-graph command->description))) (defn show+ "Generates a graph image for a PigPen query. This allows you to see what steps will be executed when the script is run. The image is opened in another window. This command uses a verbose description for each operation, including user code. Example: (pigpen.core/show+ foo) See also: pigpen.core/show " {:added "0.1.0"} [query] (->> query (oven/bake :viz {} {}) (view-graph command->description+)))
11544
;; ;; ;; Copyright 2013-2015 <NAME>flix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.viz "Functions to create graph-viz graphs from PigPen queries. " (:require [rhizome.viz :as viz] [pigpen.oven :as oven])) (set! *warn-on-reflection* true) (defn ^:private command->description [{:keys [id]}] "Returns a simple human readable description of a command" (str id)) (defn ^:private command->description+ [{:keys [id description]}] "Returns a verbose human readable description of a command" (if description (str id "\n\n" description) (str id))) (def ^:private line-len 50) (def ^:private max-lines 10) (defn ^:private fix-label [label] (let [lines (clojure.string/split-lines label) label' (->> lines (map (fn [l] (if (-> l count (> line-len)) (str (subs l 0 line-len) "...") l))) (take max-lines) (clojure.string/join "\\l"))] (if (> (count lines) max-lines) (str label' "\\l...") label'))) (defn ^:private view-graph [command->description commands] (viz/view-graph (filter #(contains? % :id) commands) (fn [parent] (filter (fn [child] ((-> child :ancestors set) (:id parent))) commands)) :node->descriptor (fn [c] {:label (fix-label (command->description c)) :shape :box}))) (defn show "Generates a graph image for a PigPen query. This allows you to see what steps will be executed when the script is run. The image is opened in another window. This command uses a terse description for each operation. Example: (pigpen.core/show foo) See also: pigpen.core/show+ " {:added "0.1.0"} [query] (->> query (oven/bake :viz {} {}) (view-graph command->description))) (defn show+ "Generates a graph image for a PigPen query. This allows you to see what steps will be executed when the script is run. The image is opened in another window. This command uses a verbose description for each operation, including user code. Example: (pigpen.core/show+ foo) See also: pigpen.core/show " {:added "0.1.0"} [query] (->> query (oven/bake :viz {} {}) (view-graph command->description+)))
true
;; ;; ;; Copyright 2013-2015 PI:NAME:<NAME>END_PIflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.viz "Functions to create graph-viz graphs from PigPen queries. " (:require [rhizome.viz :as viz] [pigpen.oven :as oven])) (set! *warn-on-reflection* true) (defn ^:private command->description [{:keys [id]}] "Returns a simple human readable description of a command" (str id)) (defn ^:private command->description+ [{:keys [id description]}] "Returns a verbose human readable description of a command" (if description (str id "\n\n" description) (str id))) (def ^:private line-len 50) (def ^:private max-lines 10) (defn ^:private fix-label [label] (let [lines (clojure.string/split-lines label) label' (->> lines (map (fn [l] (if (-> l count (> line-len)) (str (subs l 0 line-len) "...") l))) (take max-lines) (clojure.string/join "\\l"))] (if (> (count lines) max-lines) (str label' "\\l...") label'))) (defn ^:private view-graph [command->description commands] (viz/view-graph (filter #(contains? % :id) commands) (fn [parent] (filter (fn [child] ((-> child :ancestors set) (:id parent))) commands)) :node->descriptor (fn [c] {:label (fix-label (command->description c)) :shape :box}))) (defn show "Generates a graph image for a PigPen query. This allows you to see what steps will be executed when the script is run. The image is opened in another window. This command uses a terse description for each operation. Example: (pigpen.core/show foo) See also: pigpen.core/show+ " {:added "0.1.0"} [query] (->> query (oven/bake :viz {} {}) (view-graph command->description))) (defn show+ "Generates a graph image for a PigPen query. This allows you to see what steps will be executed when the script is run. The image is opened in another window. This command uses a verbose description for each operation, including user code. Example: (pigpen.core/show+ foo) See also: pigpen.core/show " {:added "0.1.0"} [query] (->> query (oven/bake :viz {} {}) (view-graph command->description+)))
[ { "context": " \"/api\")\n :username \"redshirt\"\n :password \"scotty\"}\n ", "end": 2706, "score": 0.9995080828666687, "start": 2698, "tag": "USERNAME", "value": "redshirt" }, { "context": "e \"redshirt\"\n :password \"scotty\"}\n :service_instance_url (str \"/v2/ser", "end": 2751, "score": 0.9991830587387085, "start": 2745, "tag": "PASSWORD", "value": "scotty" }, { "context": "eyword service-name)\n {:credentials {:password \"scotty\"\n :url (str \"https://gateway.wat", "end": 6651, "score": 0.9992852210998535, "start": 6645, "tag": "PASSWORD", "value": "scotty" }, { "context": " \"/api\")\n :username \"redshirt\"}\n :guid guid,\n :type service-type\n :pla", "end": 6833, "score": 0.999427318572998, "start": 6825, "tag": "USERNAME", "value": "redshirt" } ]
test/kale/cloud_foundry_constants.clj
IBM-Watson/kale
13
;; ;; (C) Copyright IBM Corp. 2016 All Rights Reserved. ;; (ns kale.cloud-foundry-constants) (def template-response {:status 200 :headers {"Content-Type" "application/json"} :request-time 100 :body ""}) (defn service-entity [guid service-name service-type] {:guid guid :name service-name :last_operation {:type "create" :state "succeeded" :description "" :updated_at nil :created_at "DATE"} :service_plan {:guid (str "PLAN_" guid) :name "standard" :service {:guid (str "TYPE_" guid) :label service-type :provider nil :version nil}}}) (def space-summary-response {:guid "SPACE_GUID" :name "dev" :apps [] :services [(service-entity "RNR_GUID" "rnr-service" "retrieve_and_rank") (service-entity "DC_GUID" "dc-service" "document_conversion")]}) (defn service-instance-entity [guid service-name] {:metadata {:guid guid :url (str "/v2/service_instances/" guid) :created_at "DATE" :updated_at nil} :entity {:name service-name :credentials {} :service_plan_guid (str "PLAN_" guid) :space_guid (str "SPACE_" guid) :gateway_data nil :dashboard_url "https://www.ibm.com/service-dashboard.html" :type "managed_service_instance" :last_operation {:type "create" :state "succeeded" :description "" :updated_at nil :created_at "DATE"} :tags [] :space_url (str "/v2/spaces/SPACE_" guid) :service_plan_url (str "/v2/service_plans/PLAN_" guid) :service_bindings_url (str "/v2/service_instances/" guid "/service_bindings") :service_keys_url (str "/v2/service_instances/" guid "/service_keys") :routes_url (str "/v2/service_instances/" guid "/routes")}}) (defn service-key-entity [guid service-type] {:metadata {:guid (str "KEY_" guid) :url (str "/v2/service_keys/KEY_" guid) :created_at "DATE" :updated_at nil} :entity {:name "credentials" :service_instance_guid guid :credentials {:url (str "https://gateway.watsonplatform.net/" service-type "/api") :username "redshirt" :password "scotty"} :service_instance_url (str "/v2/service_instances/" guid)}}) (defn org-entity [guid name] {:metadata {:guid guid :url (str "/v2/organizations/" guid) :created_at "DATE" :updated_at nil} :entity {:managers_url (str "/v2/organizations/" guid "/managers") :private_domains_url (str "/v2/organizations/" guid "/private_domains") :name name :billing_enabled false :spaces_url (str "/v2/organizations/" guid "/spaces") :status "active" :domains_url (str "/v2/organizations/" guid "/domains") :users_url (str "/v2/organizations/" guid "/users")}}) (defn space-entity [guid name] {:metadata {:guid guid :url (str "/v2/spaces/" guid) :created_at "DATE" :updated_at nil} :entity {:apps_url (str "/v2/spaces/" guid) :allow_ssh true :developers_url (str "/v2/spaces/" guid "/developers") :name name :organization_url "/v2/organizations/ORG_GUID" :service_instances_url (str "/v2/spaces/" guid "/service_instances") :routes_url (str "/v2/spaces/" guid "/routes") :domains_url (str "/v2/spaces/" guid "/domains") :organization_guid "ORG_GUID"}}) (defn service-type-entity [guid name] {:metadata {:guid guid :url (str "/v2/services/" guid) :created_at "DATE" :updated_at "DATE"} :entity {:label name :description "This is a service description." :long_description nil :version nil :active true :bindable true :unique_id (str "UNIQUE_" guid) :extra "" :documentation_url nil :service_broker_guid (str "BROKER_" guid) :plan_updateable false :service_plans_url (str "/v2/services/" guid "/service_plans")}}) (defn service-plan-entity [guid name] {:metadata {:guid guid :url (str "/v2/service_plans/" guid) :created_at "DATE" :updated_at "DATE"} :entity {:name name :free false :description "Details on how services are charged." :service_guid (str "TYPE_" guid) :extra "" :unique_id (str "UNIQUE_" guid) :public true :active true :service_url (str "/v2/services/TYPE_" guid) :service_instances_url (str "/v2/service_plans/" guid "/service_instances")}}) (defn results-response [resources] {:total_results (count resources) :total_pages 1 :prev_url nil :next_url nil :resources resources}) (def service-keys-response (results-response [(service-key-entity "RNR_GUID" "retrieve_and_rank") (service-key-entity "DC_GUID" "document_conversion")])) (def orgs-response (results-response [(org-entity "ORG_GUID1" "org1") (org-entity "ORG_GUID2" "org2")])) (def spaces-response (results-response [(space-entity "SPACE_GUID1" "space1") (space-entity "SPACE_GUID2" "space2")])) (def service-type-response (results-response [(service-type-entity "TYPE_GUID" "service-type")])) (def service-plan-response (results-response [(service-plan-entity "PLAN_GUID" "standard")])) (defn respond [partial-response] (merge template-response partial-response)) (def cf-auth {:url "https://api.ng.bluemix.net" :token "TOKEN"}) (defn cf-url [tail] (-> cf-auth :url (str tail))) (defn service-entry [guid service-name service-type] {(keyword service-name) {:credentials {:password "scotty" :url (str "https://gateway.watsonplatform.net/" service-type "/api") :username "redshirt"} :guid guid, :type service-type :plan "standard" :key-guid (str "KEY_" guid)}}) (def entry1 (service-entry "RNR_GUID" "rnr-service" "retrieve_and_rank")) (def entry2 (service-entry "DC_GUID" "dc-service" "document_conversion")) (def org-space-entry {:org "org-name" :space "space-name" :guid {:org "ORG_GUID" :space "SPACE_GUID"}})
59411
;; ;; (C) Copyright IBM Corp. 2016 All Rights Reserved. ;; (ns kale.cloud-foundry-constants) (def template-response {:status 200 :headers {"Content-Type" "application/json"} :request-time 100 :body ""}) (defn service-entity [guid service-name service-type] {:guid guid :name service-name :last_operation {:type "create" :state "succeeded" :description "" :updated_at nil :created_at "DATE"} :service_plan {:guid (str "PLAN_" guid) :name "standard" :service {:guid (str "TYPE_" guid) :label service-type :provider nil :version nil}}}) (def space-summary-response {:guid "SPACE_GUID" :name "dev" :apps [] :services [(service-entity "RNR_GUID" "rnr-service" "retrieve_and_rank") (service-entity "DC_GUID" "dc-service" "document_conversion")]}) (defn service-instance-entity [guid service-name] {:metadata {:guid guid :url (str "/v2/service_instances/" guid) :created_at "DATE" :updated_at nil} :entity {:name service-name :credentials {} :service_plan_guid (str "PLAN_" guid) :space_guid (str "SPACE_" guid) :gateway_data nil :dashboard_url "https://www.ibm.com/service-dashboard.html" :type "managed_service_instance" :last_operation {:type "create" :state "succeeded" :description "" :updated_at nil :created_at "DATE"} :tags [] :space_url (str "/v2/spaces/SPACE_" guid) :service_plan_url (str "/v2/service_plans/PLAN_" guid) :service_bindings_url (str "/v2/service_instances/" guid "/service_bindings") :service_keys_url (str "/v2/service_instances/" guid "/service_keys") :routes_url (str "/v2/service_instances/" guid "/routes")}}) (defn service-key-entity [guid service-type] {:metadata {:guid (str "KEY_" guid) :url (str "/v2/service_keys/KEY_" guid) :created_at "DATE" :updated_at nil} :entity {:name "credentials" :service_instance_guid guid :credentials {:url (str "https://gateway.watsonplatform.net/" service-type "/api") :username "redshirt" :password "<PASSWORD>"} :service_instance_url (str "/v2/service_instances/" guid)}}) (defn org-entity [guid name] {:metadata {:guid guid :url (str "/v2/organizations/" guid) :created_at "DATE" :updated_at nil} :entity {:managers_url (str "/v2/organizations/" guid "/managers") :private_domains_url (str "/v2/organizations/" guid "/private_domains") :name name :billing_enabled false :spaces_url (str "/v2/organizations/" guid "/spaces") :status "active" :domains_url (str "/v2/organizations/" guid "/domains") :users_url (str "/v2/organizations/" guid "/users")}}) (defn space-entity [guid name] {:metadata {:guid guid :url (str "/v2/spaces/" guid) :created_at "DATE" :updated_at nil} :entity {:apps_url (str "/v2/spaces/" guid) :allow_ssh true :developers_url (str "/v2/spaces/" guid "/developers") :name name :organization_url "/v2/organizations/ORG_GUID" :service_instances_url (str "/v2/spaces/" guid "/service_instances") :routes_url (str "/v2/spaces/" guid "/routes") :domains_url (str "/v2/spaces/" guid "/domains") :organization_guid "ORG_GUID"}}) (defn service-type-entity [guid name] {:metadata {:guid guid :url (str "/v2/services/" guid) :created_at "DATE" :updated_at "DATE"} :entity {:label name :description "This is a service description." :long_description nil :version nil :active true :bindable true :unique_id (str "UNIQUE_" guid) :extra "" :documentation_url nil :service_broker_guid (str "BROKER_" guid) :plan_updateable false :service_plans_url (str "/v2/services/" guid "/service_plans")}}) (defn service-plan-entity [guid name] {:metadata {:guid guid :url (str "/v2/service_plans/" guid) :created_at "DATE" :updated_at "DATE"} :entity {:name name :free false :description "Details on how services are charged." :service_guid (str "TYPE_" guid) :extra "" :unique_id (str "UNIQUE_" guid) :public true :active true :service_url (str "/v2/services/TYPE_" guid) :service_instances_url (str "/v2/service_plans/" guid "/service_instances")}}) (defn results-response [resources] {:total_results (count resources) :total_pages 1 :prev_url nil :next_url nil :resources resources}) (def service-keys-response (results-response [(service-key-entity "RNR_GUID" "retrieve_and_rank") (service-key-entity "DC_GUID" "document_conversion")])) (def orgs-response (results-response [(org-entity "ORG_GUID1" "org1") (org-entity "ORG_GUID2" "org2")])) (def spaces-response (results-response [(space-entity "SPACE_GUID1" "space1") (space-entity "SPACE_GUID2" "space2")])) (def service-type-response (results-response [(service-type-entity "TYPE_GUID" "service-type")])) (def service-plan-response (results-response [(service-plan-entity "PLAN_GUID" "standard")])) (defn respond [partial-response] (merge template-response partial-response)) (def cf-auth {:url "https://api.ng.bluemix.net" :token "TOKEN"}) (defn cf-url [tail] (-> cf-auth :url (str tail))) (defn service-entry [guid service-name service-type] {(keyword service-name) {:credentials {:password "<PASSWORD>" :url (str "https://gateway.watsonplatform.net/" service-type "/api") :username "redshirt"} :guid guid, :type service-type :plan "standard" :key-guid (str "KEY_" guid)}}) (def entry1 (service-entry "RNR_GUID" "rnr-service" "retrieve_and_rank")) (def entry2 (service-entry "DC_GUID" "dc-service" "document_conversion")) (def org-space-entry {:org "org-name" :space "space-name" :guid {:org "ORG_GUID" :space "SPACE_GUID"}})
true
;; ;; (C) Copyright IBM Corp. 2016 All Rights Reserved. ;; (ns kale.cloud-foundry-constants) (def template-response {:status 200 :headers {"Content-Type" "application/json"} :request-time 100 :body ""}) (defn service-entity [guid service-name service-type] {:guid guid :name service-name :last_operation {:type "create" :state "succeeded" :description "" :updated_at nil :created_at "DATE"} :service_plan {:guid (str "PLAN_" guid) :name "standard" :service {:guid (str "TYPE_" guid) :label service-type :provider nil :version nil}}}) (def space-summary-response {:guid "SPACE_GUID" :name "dev" :apps [] :services [(service-entity "RNR_GUID" "rnr-service" "retrieve_and_rank") (service-entity "DC_GUID" "dc-service" "document_conversion")]}) (defn service-instance-entity [guid service-name] {:metadata {:guid guid :url (str "/v2/service_instances/" guid) :created_at "DATE" :updated_at nil} :entity {:name service-name :credentials {} :service_plan_guid (str "PLAN_" guid) :space_guid (str "SPACE_" guid) :gateway_data nil :dashboard_url "https://www.ibm.com/service-dashboard.html" :type "managed_service_instance" :last_operation {:type "create" :state "succeeded" :description "" :updated_at nil :created_at "DATE"} :tags [] :space_url (str "/v2/spaces/SPACE_" guid) :service_plan_url (str "/v2/service_plans/PLAN_" guid) :service_bindings_url (str "/v2/service_instances/" guid "/service_bindings") :service_keys_url (str "/v2/service_instances/" guid "/service_keys") :routes_url (str "/v2/service_instances/" guid "/routes")}}) (defn service-key-entity [guid service-type] {:metadata {:guid (str "KEY_" guid) :url (str "/v2/service_keys/KEY_" guid) :created_at "DATE" :updated_at nil} :entity {:name "credentials" :service_instance_guid guid :credentials {:url (str "https://gateway.watsonplatform.net/" service-type "/api") :username "redshirt" :password "PI:PASSWORD:<PASSWORD>END_PI"} :service_instance_url (str "/v2/service_instances/" guid)}}) (defn org-entity [guid name] {:metadata {:guid guid :url (str "/v2/organizations/" guid) :created_at "DATE" :updated_at nil} :entity {:managers_url (str "/v2/organizations/" guid "/managers") :private_domains_url (str "/v2/organizations/" guid "/private_domains") :name name :billing_enabled false :spaces_url (str "/v2/organizations/" guid "/spaces") :status "active" :domains_url (str "/v2/organizations/" guid "/domains") :users_url (str "/v2/organizations/" guid "/users")}}) (defn space-entity [guid name] {:metadata {:guid guid :url (str "/v2/spaces/" guid) :created_at "DATE" :updated_at nil} :entity {:apps_url (str "/v2/spaces/" guid) :allow_ssh true :developers_url (str "/v2/spaces/" guid "/developers") :name name :organization_url "/v2/organizations/ORG_GUID" :service_instances_url (str "/v2/spaces/" guid "/service_instances") :routes_url (str "/v2/spaces/" guid "/routes") :domains_url (str "/v2/spaces/" guid "/domains") :organization_guid "ORG_GUID"}}) (defn service-type-entity [guid name] {:metadata {:guid guid :url (str "/v2/services/" guid) :created_at "DATE" :updated_at "DATE"} :entity {:label name :description "This is a service description." :long_description nil :version nil :active true :bindable true :unique_id (str "UNIQUE_" guid) :extra "" :documentation_url nil :service_broker_guid (str "BROKER_" guid) :plan_updateable false :service_plans_url (str "/v2/services/" guid "/service_plans")}}) (defn service-plan-entity [guid name] {:metadata {:guid guid :url (str "/v2/service_plans/" guid) :created_at "DATE" :updated_at "DATE"} :entity {:name name :free false :description "Details on how services are charged." :service_guid (str "TYPE_" guid) :extra "" :unique_id (str "UNIQUE_" guid) :public true :active true :service_url (str "/v2/services/TYPE_" guid) :service_instances_url (str "/v2/service_plans/" guid "/service_instances")}}) (defn results-response [resources] {:total_results (count resources) :total_pages 1 :prev_url nil :next_url nil :resources resources}) (def service-keys-response (results-response [(service-key-entity "RNR_GUID" "retrieve_and_rank") (service-key-entity "DC_GUID" "document_conversion")])) (def orgs-response (results-response [(org-entity "ORG_GUID1" "org1") (org-entity "ORG_GUID2" "org2")])) (def spaces-response (results-response [(space-entity "SPACE_GUID1" "space1") (space-entity "SPACE_GUID2" "space2")])) (def service-type-response (results-response [(service-type-entity "TYPE_GUID" "service-type")])) (def service-plan-response (results-response [(service-plan-entity "PLAN_GUID" "standard")])) (defn respond [partial-response] (merge template-response partial-response)) (def cf-auth {:url "https://api.ng.bluemix.net" :token "TOKEN"}) (defn cf-url [tail] (-> cf-auth :url (str tail))) (defn service-entry [guid service-name service-type] {(keyword service-name) {:credentials {:password "PI:PASSWORD:<PASSWORD>END_PI" :url (str "https://gateway.watsonplatform.net/" service-type "/api") :username "redshirt"} :guid guid, :type service-type :plan "standard" :key-guid (str "KEY_" guid)}}) (def entry1 (service-entry "RNR_GUID" "rnr-service" "retrieve_and_rank")) (def entry2 (service-entry "DC_GUID" "dc-service" "document_conversion")) (def org-space-entry {:org "org-name" :space "space-name" :guid {:org "ORG_GUID" :space "SPACE_GUID"}})
[ { "context": " \"uS\"\n :data-key \"conductivity\"\n :id \"condu", "end": 1431, "score": 0.725775420665741, "start": 1419, "tag": "KEY", "value": "conductivity" } ]
src/main/app/ui/dashboard/conductivity.cljs
joshuawood2894/fulcro_postgresql_mqtt_template
0
(ns app.ui.dashboard.conductivity (:require [app.model.dashboard.conductivity :as mc] [app.ui.dashboard.config :as dc] [app.ui.antd.components :as ant] [app.ui.data-logger.conductivity :as dl] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.dom :as dom :refer [div ul li h3 p]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]])) (defsc ConductivityChart [this props] (ant/card {:style {:width 500 :textAlign "center"} :bodyStyle {:margin "0px" :padding "0px"} :headStyle {:backgroundColor "#001529" :color "white"} :title (dc/create-card-title "Conductivity in Microseimens" mc/toggle-conductivity-settings! (:toggle-settings props)) :cover (if (empty? (:conductivity props)) (div {:style {:width 485 :height 275}} (ant/ant-empty {:style {:paddingTop "15%"}})) (dc/create-rechart (:chart-type props) {:data (:conductivity props) :x-axis-label "Time" :y-axis-label "Conductivity in Microsiemens" :unit-symbol "uS" :data-key "conductivity" :id "conductivity-id" :color (:color props) :min-bound (:min-bound props) :max-bound (:max-bound props)})) :actions (dc/create-dropdown-settings (:toggle-settings props) mc/set-conductivity-start-end-datetime! mc/set-conductivity-color! mc/set-conductivity-min-bound! mc/set-conductivity-max-bound! mc/redo-conductivity-min-max-bound! (:chart-type props) mc/set-conductivity-chart-type!)})) (def ui-conductivity-chart (comp/factory ConductivityChart)) (defsc ConductivityData [this {:conductivity-data/keys [conductivity start-date end-date toggle-settings color min-bound max-bound chart-type] :as props}] {:query [{:conductivity-data/conductivity (comp/get-query dl/ConductivityReading)} :conductivity-data/start-date :conductivity-data/end-date :conductivity-data/toggle-settings :conductivity-data/color :conductivity-data/min-bound :conductivity-data/max-bound :conductivity-data/chart-type] :ident (fn [] [:component/id :conductivity-data]) :initial-state {:conductivity-data/toggle-settings false :conductivity-data/min-bound js/NaN :conductivity-data/max-bound js/NaN :conductivity-data/chart-type "line" :conductivity-data/color ant/blue-primary :conductivity-data/start-date (js/Date.) :conductivity-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24))) :conductivity-data/conductivity [{:id 1 :time (js/Date. "March 17, 2021 15:24:00") :conductivity 110} {:id 2 :time (js/Date. "March 17, 2021 15:25:00") :conductivity 270} {:id 3 :time (js/Date. "March 17, 2021 15:26:00") :conductivity 250} {:id 4 :time (js/Date. "March 17, 2021 15:27:00") :conductivity 180} {:id 5 :time (js/Date. "March 17, 2021 15:28:00") :conductivity 175} {:id 6 :time (js/Date. "March 17, 2021 15:29:00") :conductivity 200} {:id 7 :time (js/Date. "March 17, 2021 15:30:00") :conductivity 175}]}} (ui-conductivity-chart {:conductivity conductivity :toggle-settings toggle-settings :color color :min-bound min-bound :max-bound max-bound :chart-type chart-type})) (def ui-conductivity-data (comp/factory ConductivityData))
27562
(ns app.ui.dashboard.conductivity (:require [app.model.dashboard.conductivity :as mc] [app.ui.dashboard.config :as dc] [app.ui.antd.components :as ant] [app.ui.data-logger.conductivity :as dl] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.dom :as dom :refer [div ul li h3 p]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]])) (defsc ConductivityChart [this props] (ant/card {:style {:width 500 :textAlign "center"} :bodyStyle {:margin "0px" :padding "0px"} :headStyle {:backgroundColor "#001529" :color "white"} :title (dc/create-card-title "Conductivity in Microseimens" mc/toggle-conductivity-settings! (:toggle-settings props)) :cover (if (empty? (:conductivity props)) (div {:style {:width 485 :height 275}} (ant/ant-empty {:style {:paddingTop "15%"}})) (dc/create-rechart (:chart-type props) {:data (:conductivity props) :x-axis-label "Time" :y-axis-label "Conductivity in Microsiemens" :unit-symbol "uS" :data-key "<KEY>" :id "conductivity-id" :color (:color props) :min-bound (:min-bound props) :max-bound (:max-bound props)})) :actions (dc/create-dropdown-settings (:toggle-settings props) mc/set-conductivity-start-end-datetime! mc/set-conductivity-color! mc/set-conductivity-min-bound! mc/set-conductivity-max-bound! mc/redo-conductivity-min-max-bound! (:chart-type props) mc/set-conductivity-chart-type!)})) (def ui-conductivity-chart (comp/factory ConductivityChart)) (defsc ConductivityData [this {:conductivity-data/keys [conductivity start-date end-date toggle-settings color min-bound max-bound chart-type] :as props}] {:query [{:conductivity-data/conductivity (comp/get-query dl/ConductivityReading)} :conductivity-data/start-date :conductivity-data/end-date :conductivity-data/toggle-settings :conductivity-data/color :conductivity-data/min-bound :conductivity-data/max-bound :conductivity-data/chart-type] :ident (fn [] [:component/id :conductivity-data]) :initial-state {:conductivity-data/toggle-settings false :conductivity-data/min-bound js/NaN :conductivity-data/max-bound js/NaN :conductivity-data/chart-type "line" :conductivity-data/color ant/blue-primary :conductivity-data/start-date (js/Date.) :conductivity-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24))) :conductivity-data/conductivity [{:id 1 :time (js/Date. "March 17, 2021 15:24:00") :conductivity 110} {:id 2 :time (js/Date. "March 17, 2021 15:25:00") :conductivity 270} {:id 3 :time (js/Date. "March 17, 2021 15:26:00") :conductivity 250} {:id 4 :time (js/Date. "March 17, 2021 15:27:00") :conductivity 180} {:id 5 :time (js/Date. "March 17, 2021 15:28:00") :conductivity 175} {:id 6 :time (js/Date. "March 17, 2021 15:29:00") :conductivity 200} {:id 7 :time (js/Date. "March 17, 2021 15:30:00") :conductivity 175}]}} (ui-conductivity-chart {:conductivity conductivity :toggle-settings toggle-settings :color color :min-bound min-bound :max-bound max-bound :chart-type chart-type})) (def ui-conductivity-data (comp/factory ConductivityData))
true
(ns app.ui.dashboard.conductivity (:require [app.model.dashboard.conductivity :as mc] [app.ui.dashboard.config :as dc] [app.ui.antd.components :as ant] [app.ui.data-logger.conductivity :as dl] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.dom :as dom :refer [div ul li h3 p]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]])) (defsc ConductivityChart [this props] (ant/card {:style {:width 500 :textAlign "center"} :bodyStyle {:margin "0px" :padding "0px"} :headStyle {:backgroundColor "#001529" :color "white"} :title (dc/create-card-title "Conductivity in Microseimens" mc/toggle-conductivity-settings! (:toggle-settings props)) :cover (if (empty? (:conductivity props)) (div {:style {:width 485 :height 275}} (ant/ant-empty {:style {:paddingTop "15%"}})) (dc/create-rechart (:chart-type props) {:data (:conductivity props) :x-axis-label "Time" :y-axis-label "Conductivity in Microsiemens" :unit-symbol "uS" :data-key "PI:KEY:<KEY>END_PI" :id "conductivity-id" :color (:color props) :min-bound (:min-bound props) :max-bound (:max-bound props)})) :actions (dc/create-dropdown-settings (:toggle-settings props) mc/set-conductivity-start-end-datetime! mc/set-conductivity-color! mc/set-conductivity-min-bound! mc/set-conductivity-max-bound! mc/redo-conductivity-min-max-bound! (:chart-type props) mc/set-conductivity-chart-type!)})) (def ui-conductivity-chart (comp/factory ConductivityChart)) (defsc ConductivityData [this {:conductivity-data/keys [conductivity start-date end-date toggle-settings color min-bound max-bound chart-type] :as props}] {:query [{:conductivity-data/conductivity (comp/get-query dl/ConductivityReading)} :conductivity-data/start-date :conductivity-data/end-date :conductivity-data/toggle-settings :conductivity-data/color :conductivity-data/min-bound :conductivity-data/max-bound :conductivity-data/chart-type] :ident (fn [] [:component/id :conductivity-data]) :initial-state {:conductivity-data/toggle-settings false :conductivity-data/min-bound js/NaN :conductivity-data/max-bound js/NaN :conductivity-data/chart-type "line" :conductivity-data/color ant/blue-primary :conductivity-data/start-date (js/Date.) :conductivity-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24))) :conductivity-data/conductivity [{:id 1 :time (js/Date. "March 17, 2021 15:24:00") :conductivity 110} {:id 2 :time (js/Date. "March 17, 2021 15:25:00") :conductivity 270} {:id 3 :time (js/Date. "March 17, 2021 15:26:00") :conductivity 250} {:id 4 :time (js/Date. "March 17, 2021 15:27:00") :conductivity 180} {:id 5 :time (js/Date. "March 17, 2021 15:28:00") :conductivity 175} {:id 6 :time (js/Date. "March 17, 2021 15:29:00") :conductivity 200} {:id 7 :time (js/Date. "March 17, 2021 15:30:00") :conductivity 175}]}} (ui-conductivity-chart {:conductivity conductivity :toggle-settings toggle-settings :color color :min-bound min-bound :max-bound max-bound :chart-type chart-type})) (def ui-conductivity-data (comp/factory ConductivityData))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998093247413635, "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.9998276233673096, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/background.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.background (:require [dynamo.graph :as g] [editor.geom :as geom] [editor.gl :as gl] [editor.colors :as colors] [editor.gl.pass :as pass]) (:import [com.jogamp.opengl GL2] [editor.types Region])) (set! *warn-on-reflection* true) (defn render-background [^GL2 gl render-args renderables count] (let [viewport ^Region (:viewport render-args) x0 (.left viewport) x1 (.right viewport) y0 (.top viewport) y1 (.bottom viewport)] (gl/gl-quads gl (gl/gl-color colors/scene-background) (gl/gl-vertex-2f x0 y1) (gl/gl-vertex-2f x1 y1) (gl/gl-vertex-2f x1 y0) (gl/gl-vertex-2f x0 y0)))) (g/defnode Background (output renderable pass/RenderData (g/fnk [] {pass/background [{:world-transform geom/Identity4d :render-fn render-background}]})))
54061
;; 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.background (:require [dynamo.graph :as g] [editor.geom :as geom] [editor.gl :as gl] [editor.colors :as colors] [editor.gl.pass :as pass]) (:import [com.jogamp.opengl GL2] [editor.types Region])) (set! *warn-on-reflection* true) (defn render-background [^GL2 gl render-args renderables count] (let [viewport ^Region (:viewport render-args) x0 (.left viewport) x1 (.right viewport) y0 (.top viewport) y1 (.bottom viewport)] (gl/gl-quads gl (gl/gl-color colors/scene-background) (gl/gl-vertex-2f x0 y1) (gl/gl-vertex-2f x1 y1) (gl/gl-vertex-2f x1 y0) (gl/gl-vertex-2f x0 y0)))) (g/defnode Background (output renderable pass/RenderData (g/fnk [] {pass/background [{:world-transform geom/Identity4d :render-fn render-background}]})))
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.background (:require [dynamo.graph :as g] [editor.geom :as geom] [editor.gl :as gl] [editor.colors :as colors] [editor.gl.pass :as pass]) (:import [com.jogamp.opengl GL2] [editor.types Region])) (set! *warn-on-reflection* true) (defn render-background [^GL2 gl render-args renderables count] (let [viewport ^Region (:viewport render-args) x0 (.left viewport) x1 (.right viewport) y0 (.top viewport) y1 (.bottom viewport)] (gl/gl-quads gl (gl/gl-color colors/scene-background) (gl/gl-vertex-2f x0 y1) (gl/gl-vertex-2f x1 y1) (gl/gl-vertex-2f x1 y0) (gl/gl-vertex-2f x0 y0)))) (g/defnode Background (output renderable pass/RenderData (g/fnk [] {pass/background [{:world-transform geom/Identity4d :render-fn render-background}]})))
[ { "context": "; MIT License\n;\n; Copyright (c) 2017 Frederic Merizen & Kenny Williams\n;\n; Permission is hereby granted", "end": 53, "score": 0.9998371005058289, "start": 37, "tag": "NAME", "value": "Frederic Merizen" }, { "context": " License\n;\n; Copyright (c) 2017 Frederic Merizen & Kenny Williams\n;\n; Permission is hereby granted, free of charge,", "end": 70, "score": 0.9997790455818176, "start": 56, "tag": "NAME", "value": "Kenny Williams" }, { "context": "re test.\"\n :url \"https://github.com/plumula/mimolette\"\n :scm {:url \"https://git", "end": 2842, "score": 0.9996718764305115, "start": 2835, "tag": "USERNAME", "value": "plumula" }, { "context": "te\"\n :scm {:url \"https://github.com/plumula/mimolette\"}\n :license {\"MIT\" \"https://o", "end": 2907, "score": 0.9996849894523621, "start": 2900, "tag": "USERNAME", "value": "plumula" } ]
build.boot
plumula/mimolette
3
; MIT License ; ; Copyright (c) 2017 Frederic Merizen & Kenny Williams ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in all ; copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ; SOFTWARE. (def +project+ 'plumula/mimolette) (def +version+ "0.2.1") (set-env! :dependencies '[[plumula/soles "0.5.0" :scope "test"]]) (require '[plumula.soles :refer [add-dir! add-dependencies! testing deploy-local deploy-snapshot deploy-release]]) (add-dependencies! '(:provided [org.clojure/clojure "1.9.0-alpha8"] [org.clojure/clojurescript "1.9.183"]) '(:compile [org.clojure/test.check "0.9.0"]) '(:test [adzerk/boot-cljs "2.0.0"] [adzerk/boot-cljs-repl "0.3.3"] [adzerk/boot-reload "0.5.1"] [adzerk/boot-test "1.2.0"] [com.cemerick/piggieback "0.2.1"] [crisptrutski/boot-cljs-test "0.3.0"] [doo "0.1.7"] [org.clojure/tools.nrepl "0.2.12"] [pandeiro/boot-http "0.8.3"] [weasel "0.7.0"])) (require '[adzerk.boot-cljs :refer [cljs]] '[adzerk.boot-cljs-repl :refer [cljs-repl start-repl]] '[adzerk.boot-reload :refer [reload]] '[adzerk.boot-test :as test] '[adzerk.bootlaces :refer [bootlaces!]] '[crisptrutski.boot-cljs-test :refer [test-cljs report-errors!]] '[boot.lein :as lein] '[pandeiro.boot-http :refer [serve]]) (add-dir! :source-paths "src") (bootlaces! +version+) (lein/generate) (task-options! cljs { :compiler-options {:infer-externs true}} pom {:project +project+ :version +version+ :description "Run clojure spec tests from clojure test." :url "https://github.com/plumula/mimolette" :scm {:url "https://github.com/plumula/mimolette"} :license {"MIT" "https://opensource.org/licenses/MIT"}} serve {:dir "target"} test-cljs {:js-env :node :update-fs? true :keep-errors? true :optimizations :simple} test/test {:exclude #"^plumula.mimolette.alpha$"}) (deftask dev "Launch Immediate Feedback Development Environment." [] (comp (testing) (serve) (watch) (test-cljs) (test/test) (report-errors!) (reload) (cljs-repl) (cljs) (target)))
11693
; MIT License ; ; Copyright (c) 2017 <NAME> & <NAME> ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in all ; copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ; SOFTWARE. (def +project+ 'plumula/mimolette) (def +version+ "0.2.1") (set-env! :dependencies '[[plumula/soles "0.5.0" :scope "test"]]) (require '[plumula.soles :refer [add-dir! add-dependencies! testing deploy-local deploy-snapshot deploy-release]]) (add-dependencies! '(:provided [org.clojure/clojure "1.9.0-alpha8"] [org.clojure/clojurescript "1.9.183"]) '(:compile [org.clojure/test.check "0.9.0"]) '(:test [adzerk/boot-cljs "2.0.0"] [adzerk/boot-cljs-repl "0.3.3"] [adzerk/boot-reload "0.5.1"] [adzerk/boot-test "1.2.0"] [com.cemerick/piggieback "0.2.1"] [crisptrutski/boot-cljs-test "0.3.0"] [doo "0.1.7"] [org.clojure/tools.nrepl "0.2.12"] [pandeiro/boot-http "0.8.3"] [weasel "0.7.0"])) (require '[adzerk.boot-cljs :refer [cljs]] '[adzerk.boot-cljs-repl :refer [cljs-repl start-repl]] '[adzerk.boot-reload :refer [reload]] '[adzerk.boot-test :as test] '[adzerk.bootlaces :refer [bootlaces!]] '[crisptrutski.boot-cljs-test :refer [test-cljs report-errors!]] '[boot.lein :as lein] '[pandeiro.boot-http :refer [serve]]) (add-dir! :source-paths "src") (bootlaces! +version+) (lein/generate) (task-options! cljs { :compiler-options {:infer-externs true}} pom {:project +project+ :version +version+ :description "Run clojure spec tests from clojure test." :url "https://github.com/plumula/mimolette" :scm {:url "https://github.com/plumula/mimolette"} :license {"MIT" "https://opensource.org/licenses/MIT"}} serve {:dir "target"} test-cljs {:js-env :node :update-fs? true :keep-errors? true :optimizations :simple} test/test {:exclude #"^plumula.mimolette.alpha$"}) (deftask dev "Launch Immediate Feedback Development Environment." [] (comp (testing) (serve) (watch) (test-cljs) (test/test) (report-errors!) (reload) (cljs-repl) (cljs) (target)))
true
; MIT License ; ; Copyright (c) 2017 PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in all ; copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ; SOFTWARE. (def +project+ 'plumula/mimolette) (def +version+ "0.2.1") (set-env! :dependencies '[[plumula/soles "0.5.0" :scope "test"]]) (require '[plumula.soles :refer [add-dir! add-dependencies! testing deploy-local deploy-snapshot deploy-release]]) (add-dependencies! '(:provided [org.clojure/clojure "1.9.0-alpha8"] [org.clojure/clojurescript "1.9.183"]) '(:compile [org.clojure/test.check "0.9.0"]) '(:test [adzerk/boot-cljs "2.0.0"] [adzerk/boot-cljs-repl "0.3.3"] [adzerk/boot-reload "0.5.1"] [adzerk/boot-test "1.2.0"] [com.cemerick/piggieback "0.2.1"] [crisptrutski/boot-cljs-test "0.3.0"] [doo "0.1.7"] [org.clojure/tools.nrepl "0.2.12"] [pandeiro/boot-http "0.8.3"] [weasel "0.7.0"])) (require '[adzerk.boot-cljs :refer [cljs]] '[adzerk.boot-cljs-repl :refer [cljs-repl start-repl]] '[adzerk.boot-reload :refer [reload]] '[adzerk.boot-test :as test] '[adzerk.bootlaces :refer [bootlaces!]] '[crisptrutski.boot-cljs-test :refer [test-cljs report-errors!]] '[boot.lein :as lein] '[pandeiro.boot-http :refer [serve]]) (add-dir! :source-paths "src") (bootlaces! +version+) (lein/generate) (task-options! cljs { :compiler-options {:infer-externs true}} pom {:project +project+ :version +version+ :description "Run clojure spec tests from clojure test." :url "https://github.com/plumula/mimolette" :scm {:url "https://github.com/plumula/mimolette"} :license {"MIT" "https://opensource.org/licenses/MIT"}} serve {:dir "target"} test-cljs {:js-env :node :update-fs? true :keep-errors? true :optimizations :simple} test/test {:exclude #"^plumula.mimolette.alpha$"}) (deftask dev "Launch Immediate Feedback Development Environment." [] (comp (testing) (serve) (watch) (test-cljs) (test/test) (report-errors!) (reload) (cljs-repl) (cljs) (target)))
[ { "context": " Rasta\"\n [email attachment]\n (update-in email [\"rasta@metabase.com\" 0] #(update % :body conj attachment)))\n\n\n;;; +--", "end": 6609, "score": 0.9999223351478577, "start": 6591, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": "he assert results\n (update-in [\"rasta@metabase.com\" 0 :body] (comp vector first))\n ", "end": 11456, "score": 0.9999165534973145, "start": 11438, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": "e assert results\n (update-in [\"rasta@metabase.com\" 0 :body] (comp vector first))\n ", "end": 12069, "score": 0.9999065399169922, "start": 12051, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": "nnelRecipient [_ {:user_id (mt/user->id :crowberto)\n ", "end": 14847, "score": 0.9983224272727966, "start": 14838, "tag": "USERNAME", "value": "crowberto" }, { "context": " :to #{\"rasta@metabase.com\" \"crowberto@metabase.com\"}\n ", "end": 15249, "score": 0.999925971031189, "start": 15231, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": " :to #{\"rasta@metabase.com\" \"crowberto@metabase.com\"}\n ", "end": 15274, "score": 0.9999247789382935, "start": 15252, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "emp Card [{card-id :id} {:name \"Test card\"\n :dat", "end": 24379, "score": 0.9271267652511597, "start": 24375, "tag": "NAME", "value": "Test" }, { "context": "s (= {:subject \"Pulse: Pulse Name\", :recipients [\"rasta@metabase.com\"], :message-type :attachments}\n ", "end": 32459, "score": 0.9999213814735413, "start": 32441, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": "12]]\n (send-pulse-created-by-user!* :crowberto)))\n (is (thrown-with-msg?\n clojure", "end": 34134, "score": 0.6163632869720459, "start": 34126, "tag": "USERNAME", "value": "rowberto" } ]
c#-metabase/test/metabase/pulse_test.clj
hanakhry/Crime_Admin
0
(ns metabase.pulse-test (:require [clojure.java.io :as io] [clojure.string :as str] [clojure.test :refer :all] [medley.core :as m] [metabase.models :refer [Card Collection Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group] [metabase.models.pulse :as models.pulse] [metabase.pulse :as pulse] [metabase.pulse.render :as render] [metabase.pulse.render.body :as render.body] [metabase.pulse.test-util :refer :all] [metabase.query-processor.middleware.constraints :as constraints] [metabase.test :as mt] [metabase.util :as u] [schema.core :as s] [toucan.db :as db])) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Util Fns & Macros | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- rasta-pulse-email [& [email]] (mt/email-to :rasta (merge {:subject "Pulse: Pulse Name", :body [{"Pulse Name" true} png-attachment]} email))) (defn- rasta-alert-email [subject email-body] (mt/email-to :rasta {:subject subject :body email-body})) (defn- do-with-pulse-for-card "Creates a Pulse and other relevant rows for a `card` (using `pulse` and `pulse-card` properties if specified), then invokes (f pulse)" [{:keys [pulse pulse-card channel card] :or {channel :email}} f] (mt/with-temp* [Pulse [{pulse-id :id, :as pulse} (-> pulse (merge {:name "Pulse Name"}))] PulseCard [_ (merge {:pulse_id pulse-id :card_id (u/the-id card) :position 0} pulse-card)] PulseChannel [{pc-id :id} (case channel :email {:pulse_id pulse-id} :slack {:pulse_id pulse-id :channel_type "slack" :details {:channel "#general"}})]] (if (= channel :email) (mt/with-temp PulseChannelRecipient [_ {:user_id (rasta-id) :pulse_channel_id pc-id}] (f pulse)) (f pulse)))) (defmacro ^:private with-pulse-for-card "e.g. (with-pulse-for-card [pulse {:card my-card, :pulse pulse-properties, ...}] ...)" [[pulse-binding properties] & body] `(do-with-pulse-for-card ~properties (fn [~pulse-binding] ~@body))) (defn- do-test "Run a single Pulse test with a standard set of boilerplate. Creates Card, Pulse, and other related objects using `card`, `pulse`, `pulse-card` properties, then sends the Pulse; finally, test assertions in `assert` are invoked. `assert` can contain `:email` and/or `:slack` assertions, which are used to test an email and Slack version of that Pulse respectively. `:assert` functions have the signature (f object-ids send-pulse!-response) Example: (do-test {:card {:dataset_query (mt/mbql-query checkins)} :assert {:slack (fn [{:keys [pulse-id]} response] (is (= {:sent pulse-id} response)))}})" [{:keys [card pulse pulse-card fixture], assertions :assert}] {:pre [(map? assertions) ((some-fn :email :slack) assertions)]} (doseq [channel-type [:email :slack] :let [f (get assertions channel-type)] :when f] (assert (fn? f)) (testing (format "sent to %s channel" channel-type) (mt/with-temp* [Card [{card-id :id} (merge {:name card-name} card)]] (with-pulse-for-card [{pulse-id :id} {:card card-id :pulse pulse :pulse-card pulse-card :channel channel-type}] (letfn [(thunk* [] (f {:card-id card-id, :pulse-id pulse-id} (pulse/send-pulse! (models.pulse/retrieve-notification pulse-id)))) (thunk [] (if fixture (fixture {:card-id card-id, :pulse-id pulse-id} thunk*) (thunk*)))] (case channel-type :email (email-test-setup (thunk)) :slack (slack-test-setup (thunk))))))))) (defn- tests "Convenience for writing multiple tests using `do-test`. `common` is a map of shared properties as passed to `do-test` that is deeply merged with the individual maps for each test. Other args are alternating `testing` context messages and properties as passed to `do-test`: (tests ;; shared properties used for both tests {:card {:dataset_query (mt/mbql-query)}} \"Test 1\" {:assert {:email (fn [_ _] (is ...))}} \"Test 2\" ;; override just the :display property of the Card {:card {:display \"table\"} :assert {:email (fn [_ _] (is ...))}})" {:style/indent 1} [common & {:as message->m}] (doseq [[message m] message->m] (testing message (do-test (merge-with merge common m))))) (def ^:private test-card-result {card-name true}) (def ^:private test-card-regex (re-pattern card-name)) (defn- produces-bytes? [{:keys [rendered-info]}] (when rendered-info (pos? (alength (or (render/png-from-render-info rendered-info 500) (byte-array 0)))))) (defn- email-body? [{message-type :type, ^String content :content}] (and (= "text/html; charset=utf-8" message-type) (string? content) (.startsWith content "<html>"))) (defn- attachment? [{message-type :type, content-type :content-type, content :content}] (and (= :inline message-type) (= "image/png" content-type) (instance? java.net.URL content))) (defn- add-rasta-attachment "Append `attachment` to the first email found for Rasta" [email attachment] (update-in email ["rasta@metabase.com" 0] #(update % :body conj attachment))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Tests | ;;; +----------------------------------------------------------------------------------------------------------------+ (deftest basic-timeseries-test (do-test {:card (checkins-query-card {:breakout [!day.date]}) :pulse {:skip_if_empty false} :assert {:email (fn [_ _] (is (= (rasta-pulse-email) (mt/summarize-multipart-email #"Pulse Name")))) :slack (fn [{:keys [card-id]} [pulse-results]] (is (= {:channel-id "#general" :message "Pulse: Pulse Name" :attachments [{:title card-name :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id) :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean pulse-results))))}})) (deftest basic-table-test (tests {:pulse {:skip_if_empty false}} "19 results, so no attachment" {:card (checkins-query-card {:aggregation nil, :limit 19}) :fixture (fn [_ thunk] (with-redefs [render.body/attached-results-text (wrap-function @#'render.body/attached-results-text)] (thunk))) :assert {:email (fn [_ _] (is (= (rasta-pulse-email {:body [{"Pulse Name" true "More results have been included" false "ID</th>" true "<a href=\\\"https://metabase.com/testmb/dashboard/" false}]}) (mt/summarize-multipart-email #"Pulse Name" #"More results have been included" #"ID</th>" #"<a href=\"https://metabase.com/testmb/dashboard/")))) :slack (fn [{:keys [card-id]} [pulse-results]] (testing "\"more results in attachment\" text should not be present for Slack Pulses" (testing "Pulse results" (is (= {:channel-id "#general" :message "Pulse: Pulse Name" :attachments [{:title card-name :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id) :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean pulse-results)))) (testing "attached-results-text should be invoked exactly once" (is (= 1 (count (input @#'render.body/attached-results-text))))) (testing "attached-results-text should return nil since it's a slack message" (is (= [nil] (output @#'render.body/attached-results-text))))))}} "21 results results in a CSV being attached and a table being sent" {:card (checkins-query-card {:aggregation nil, :limit 21}) :assert {:email (fn [_ _] (is (= (rasta-pulse-email {:body [{"Pulse Name" true "More results have been included" true "ID</th>" true} csv-attachment]}) (mt/summarize-multipart-email #"Pulse Name" #"More results have been included" #"ID</th>"))))}})) (deftest csv-test (tests {:pulse {:skip_if_empty false} :card (checkins-query-card {:breakout [!day.date]})} "alert with a CSV" {:pulse-card {:include_csv true} :assert {:email (fn [_ _] (is (= (rasta-alert-email "Pulse: Pulse Name" [test-card-result png-attachment csv-attachment]) (mt/summarize-multipart-email test-card-regex))))}} "With a \"rows\" type of pulse (table visualization) we should include the CSV by default" {:card {:dataset_query (mt/mbql-query checkins)} :assert {:email (fn [_ _] (is (= (-> (rasta-pulse-email) ;; There's no PNG with a table visualization, remove it from the assert results (update-in ["rasta@metabase.com" 0 :body] (comp vector first)) (add-rasta-attachment csv-attachment)) (mt/summarize-multipart-email #"Pulse Name"))))}})) (deftest xls-test (testing "If the pulse is already configured to send an XLS, no need to include a CSV" (do-test {:card {:dataset_query (mt/mbql-query checkins)} :pulse-card {:include_xls true} :assert {:email (fn [_ _] (is (= (-> (rasta-pulse-email) ;; There's no PNG with a table visualization, remove it from the assert results (update-in ["rasta@metabase.com" 0 :body] (comp vector first)) (add-rasta-attachment xls-attachment)) (mt/summarize-multipart-email #"Pulse Name"))))}}))) ;; Not really sure how this is significantly different from `xls-test` (deftest xls-test-2 (testing "Basic test, 1 card, 1 recipient, with XLS attachment" (do-test {:card (checkins-query-card {:breakout [!day.date]}) :pulse-card {:include_xls true} :assert {:email (fn [_ _] (is (= (add-rasta-attachment (rasta-pulse-email) xls-attachment) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest csv-xls-no-data-test (testing "card with CSV and XLS attachments, but no data. Should not include an attachment" (do-test {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]}) :pulse {:skip_if_empty false} :pulse-card {:include_csv true :include_xls true} :assert {:email (fn [_ _] (is (= (rasta-pulse-email) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest ensure-constraints-test (testing "Validate pulse queries are limited by `default-query-constraints`" (do-test {:card (checkins-query-card {:aggregation nil}) :fixture (fn [_ thunk] (with-redefs [constraints/default-query-constraints {:max-results 10000 :max-results-bare-rows 30}] (thunk))) :assert {:email (fn [_ _] (let [first-message (-> @mt/inbox vals ffirst)] (is (= true (some? first-message)) "Should have a message in the inbox") (when first-message (let [filename (-> first-message :body last :content) exists? (some-> filename io/file .exists)] (testing "File should exist" (is (= true exists?))) (testing (str "tmp file = %s" filename) (testing "Slurp in the generated CSV and count the lines found in the file" (when exists? (testing "Should return 30 results (the redef'd limit) plus the header row" (is (= 31 (-> (slurp filename) str/split-lines count)))))))))))}}))) (deftest multiple-recipients-test (testing "Pulse should be sent to two recipients" (do-test {:card (checkins-query-card {:breakout [!day.date]}) :fixture (fn [{:keys [pulse-id]} thunk] (mt/with-temp PulseChannelRecipient [_ {:user_id (mt/user->id :crowberto) :pulse_channel_id (db/select-one-id PulseChannel :pulse_id pulse-id)}] (thunk))) :assert {:email (fn [_ _] (is (= (into {} (map (fn [user-kwd] (mt/email-to user-kwd {:subject "Pulse: Pulse Name", :to #{"rasta@metabase.com" "crowberto@metabase.com"} :body [{"Pulse Name" true} png-attachment]})) [:rasta :crowberto])) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest two-cards-in-one-pulse-test (testing "1 pulse that has 2 cards, should contain two attachments" (do-test {:card (assoc (checkins-query-card {:breakout [!day.date]}) :name "card 1") :fixture (fn [{:keys [pulse-id]} thunk] (mt/with-temp* [Card [{card-id-2 :id} (assoc (checkins-query-card {:breakout [!month.date]}) :name "card 2")] PulseCard [_ {:pulse_id pulse-id :card_id card-id-2 :position 1}]] (thunk))) :assert {:email (fn [_ _] (is (= (rasta-pulse-email {:body [{"Pulse Name" true} png-attachment png-attachment]}) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest empty-results-test (testing "Pulse where the card has no results" (tests {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]})} "skip if empty = false" {:pulse {:skip_if_empty false} :assert {:email (fn [_ _] (is (= (rasta-pulse-email) (mt/summarize-multipart-email #"Pulse Name"))))}} "skip if empty = true" {:pulse {:skip_if_empty true} :assert {:email (fn [_ _] (is (= {} (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest rows-alert-test (testing "Rows alert" (tests {:pulse {:alert_condition "rows", :alert_first_only false}} "with data" {:card (checkins-query-card {:breakout [!day.date]}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [(assoc test-card-result "More results have been included" false) png-attachment]) (mt/summarize-multipart-email test-card-regex #"More results have been included")))) :slack (fn [{:keys [card-id]} [result]] (is (= {:channel-id "#general", :message "Alert: Test card", :attachments [{:title card-name :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id) :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean result))) (is (every? produces-bytes? (:attachments result))))}} "with no data" {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]}) :assert {:email (fn [_ _] (is (= {} @mt/inbox)))}} "too much data" {:card (checkins-query-card {:limit 21, :aggregation nil}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [(merge test-card-result {"More results have been included" true "ID</th>" true}) csv-attachment]) (mt/summarize-multipart-email test-card-regex #"More results have been included" #"ID</th>"))))}} "with data and a CSV + XLS attachment" {:card (checkins-query-card {:breakout [!day.date]}) :pulse-card {:include_csv true, :include_xls true} :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [test-card-result png-attachment csv-attachment xls-attachment]) (mt/summarize-multipart-email test-card-regex))))}}))) (deftest alert-first-run-only-test (tests {:pulse {:alert_condition "rows", :alert_first_only true}} "first run only with data" {:card (checkins-query-card {:breakout [!day.date]}) :assert {:email (fn [{:keys [pulse-id]} _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [(assoc test-card-result "stop sending you alerts" true) png-attachment]) (mt/summarize-multipart-email test-card-regex #"stop sending you alerts"))) (testing "Pulse should be deleted" (is (= false (db/exists? Pulse :id pulse-id)))))}} "first run alert with no data" {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]}) :assert {:email (fn [{:keys [pulse-id]} _] (is (= {} @mt/inbox)) (testing "Pulse should still exist" (is (= true (db/exists? Pulse :id pulse-id)))))}})) (deftest above-goal-alert-test (testing "above goal alert" (tests {:pulse {:alert_condition "goal" :alert_first_only false :alert_above_goal true}} "with data" {:card (merge (checkins-query-card {:filter [:between $date "2014-04-01" "2014-06-01"] :breakout [!day.date]}) {:display :line :visualization_settings {:graph.show_goal true :graph.goal_value 5.9}}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has reached its goal" [test-card-result, png-attachment]) (mt/summarize-multipart-email test-card-regex))))}} "no data" {:card (merge (checkins-query-card {:filter [:between $date "2014-02-01" "2014-04-01"] :breakout [!day.date]}) {:display :area :visualization_settings {:graph.show_goal true :graph.goal_value 5.9}}) :assert {:email (fn [_ _] (is (= {} @mt/inbox)))}} "with progress bar" {:card (merge (venues-query-card "max") {:display :progress :visualization_settings {:progress.goal 3}}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has reached its goal" [test-card-result]) (mt/summarize-multipart-email test-card-regex))))}}))) (deftest below-goal-alert-test (testing "Below goal alert" (tests {:card {:display :bar :visualization_settings {:graph.show_goal true :graph.goal_value 1.1}} :pulse {:alert_condition "goal" :alert_first_only false :alert_above_goal false}} "with data" {:card (checkins-query-card {:filter [:between $date "2014-02-12" "2014-02-17"] :breakout [!day.date]}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has gone below its goal" [test-card-result png-attachment]) (mt/summarize-multipart-email test-card-regex))))}} "with no satisfying data" {:card (checkins-query-card {:filter [:between $date "2014-02-10" "2014-02-12"] :breakout [!day.date]}) :assert {:email (fn [_ _] (is (= {} @mt/inbox)))}} "with progress bar" {:card (merge (venues-query-card "min") {:display :progress :visualization_settings {:progress.goal 2}}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has gone below its goal" [test-card-result]) (mt/summarize-multipart-email test-card-regex))))}}))) (deftest native-query-with-user-specified-axes-test (testing "Native query with user-specified x and y axis" (mt/with-temp Card [{card-id :id} {:name "Test card" :dataset_query {:database (mt/id) :type :native :native {:query (str "select count(*) as total_per_day, date as the_day " "from checkins " "group by date")}} :display :line :visualization_settings {:graph.show_goal true :graph.goal_value 5.9 :graph.dimensions ["the_day"] :graph.metrics ["total_per_day"]}}] (with-pulse-for-card [{pulse-id :id} {:card card-id, :pulse {:alert_condition "goal" :alert_first_only false :alert_above_goal true}}] (email-test-setup (pulse/send-pulse! (models.pulse/retrieve-notification pulse-id)) (is (= (rasta-alert-email "Metabase alert: Test card has reached its goal" [test-card-result png-attachment]) (mt/summarize-multipart-email test-card-regex)))))))) (deftest basic-slack-test-2 (testing "Basic slack test, 2 cards, 1 recipient channel" (mt/with-temp* [Card [{card-id-1 :id} (checkins-query-card {:breakout [!day.date]})] Card [{card-id-2 :id} (-> {:breakout [[:datetime-field (mt/id :checkins :date) "minute"]]} checkins-query-card (assoc :name "Test card 2"))] Pulse [{pulse-id :id} {:name "Pulse Name" :skip_if_empty false}] PulseCard [_ {:pulse_id pulse-id :card_id card-id-1 :position 0}] PulseCard [_ {:pulse_id pulse-id :card_id card-id-2 :position 1}] PulseChannel [{pc-id :id} {:pulse_id pulse-id :channel_type "slack" :details {:channel "#general"}}]] (slack-test-setup (let [[slack-data] (pulse/send-pulse! (models.pulse/retrieve-pulse pulse-id))] (is (= {:channel-id "#general", :message "Pulse: Pulse Name", :attachments [{:title card-name, :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id-1), :attachment-name "image.png", :channel-id "FOO", :fallback card-name} {:title "Test card 2", :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id-2), :attachment-name "image.png", :channel-id "FOO", :fallback "Test card 2"}]} (thunk->boolean slack-data))) (testing "attachments" (is (true? (every? produces-bytes? (:attachments slack-data)))))))))) (deftest create-and-upload-slack-attachments!-test (let [slack-uploader (fn [storage] (fn [_bytes attachment-name _channel-id] (swap! storage conj attachment-name) (str "http://uploaded/" attachment-name)))] (testing "Uploads files" (let [titles (atom []) attachments [{:title "a" :attachment-name "a.png" :rendered-info {:attachments nil :content [:div "hi"]} :channel-id "FOO"} {:title "b" :attachment-name "b.png" :rendered-info {:attachments nil :content [:div "hi again"]} :channel-id "FOO"}] processed (pulse/create-and-upload-slack-attachments! attachments (slack-uploader titles))] (is (= [{:title "a", :image_url "http://uploaded/a.png"} {:title "b", :image_url "http://uploaded/b.png"}] processed)) (is (= @titles ["a.png" "b.png"])))) (testing "Uses the raw text when present" (let [titles (atom []) attachments [{:title "a" :attachment-name "a.png" :rendered-info {:attachments nil :content [:div "hi"]} :channel-id "FOO"} {:title "b" :attachment-name "b.png" :rendered-info {:attachments nil :content [:div "hi again"] :render/text "hi again"} :channel-id "FOO"}] processed (pulse/create-and-upload-slack-attachments! attachments (slack-uploader titles))] (is (= [{:title "a", :image_url "http://uploaded/a.png"} {:title "b", :text "hi again"}] processed)) (is (= @titles ["a.png"])))))) (deftest multi-channel-test (testing "Test with a slack channel and an email" (mt/with-temp Card [{card-id :id} (checkins-query-card {:breakout [!day.date]})] ;; create a Pulse with an email channel (with-pulse-for-card [{pulse-id :id} {:card card-id, :pulse {:skip_if_empty false}}] ;; add additional Slack channel (mt/with-temp PulseChannel [_ {:pulse_id pulse-id :channel_type "slack" :details {:channel "#general"}}] (slack-test-setup (let [pulse-data (pulse/send-pulse! (models.pulse/retrieve-pulse pulse-id)) slack-data (m/find-first #(contains? % :channel-id) pulse-data) email-data (m/find-first #(contains? % :subject) pulse-data)] (is (= {:channel-id "#general" :message "Pulse: Pulse Name" :attachments [{:title card-name :title_link (str "https://metabase.com/testmb/question/" card-id) :rendered-info {:attachments false :content true} :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean slack-data))) (is (= [true] (map (comp some? :content :rendered-info) (:attachments slack-data)))) (is (= {:subject "Pulse: Pulse Name", :recipients ["rasta@metabase.com"], :message-type :attachments} (select-keys email-data [:subject :recipients :message-type]))) (is (= 2 (count (:message email-data)))) (is (email-body? (first (:message email-data)))) (is (attachment? (second (:message email-data))))))))))) (deftest dont-run-async-test (testing "even if Card is saved as `:async?` we shouldn't run the query async" (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :venues)} :async? true}}] (is (schema= {:card (s/pred map?) :result (s/pred map?)} (pulse/execute-card {:creator_id (mt/user->id :rasta)} card)))))) (deftest pulse-permissions-test (testing "Pulses should be sent with the Permissions of the user that created them." (letfn [(send-pulse-created-by-user!* [user-kw] (mt/with-temp* [Collection [coll] Card [card {:dataset_query (mt/mbql-query checkins {:order-by [[:asc $id]] :limit 1}) :collection_id (:id coll)}]] (perms/revoke-collection-permissions! (group/all-users) coll) (send-pulse-created-by-user! user-kw card)))] (is (= [[1 "2014-04-07T00:00:00Z" 5 12]] (send-pulse-created-by-user!* :crowberto))) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"^You do not have permissions to view Card [\d,]+." (mt/suppress-output (send-pulse-created-by-user!* :rasta))) "If the current user doesn't have permissions to execute the Card for a Pulse, an Exception should be thrown."))))
97094
(ns metabase.pulse-test (:require [clojure.java.io :as io] [clojure.string :as str] [clojure.test :refer :all] [medley.core :as m] [metabase.models :refer [Card Collection Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group] [metabase.models.pulse :as models.pulse] [metabase.pulse :as pulse] [metabase.pulse.render :as render] [metabase.pulse.render.body :as render.body] [metabase.pulse.test-util :refer :all] [metabase.query-processor.middleware.constraints :as constraints] [metabase.test :as mt] [metabase.util :as u] [schema.core :as s] [toucan.db :as db])) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Util Fns & Macros | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- rasta-pulse-email [& [email]] (mt/email-to :rasta (merge {:subject "Pulse: Pulse Name", :body [{"Pulse Name" true} png-attachment]} email))) (defn- rasta-alert-email [subject email-body] (mt/email-to :rasta {:subject subject :body email-body})) (defn- do-with-pulse-for-card "Creates a Pulse and other relevant rows for a `card` (using `pulse` and `pulse-card` properties if specified), then invokes (f pulse)" [{:keys [pulse pulse-card channel card] :or {channel :email}} f] (mt/with-temp* [Pulse [{pulse-id :id, :as pulse} (-> pulse (merge {:name "Pulse Name"}))] PulseCard [_ (merge {:pulse_id pulse-id :card_id (u/the-id card) :position 0} pulse-card)] PulseChannel [{pc-id :id} (case channel :email {:pulse_id pulse-id} :slack {:pulse_id pulse-id :channel_type "slack" :details {:channel "#general"}})]] (if (= channel :email) (mt/with-temp PulseChannelRecipient [_ {:user_id (rasta-id) :pulse_channel_id pc-id}] (f pulse)) (f pulse)))) (defmacro ^:private with-pulse-for-card "e.g. (with-pulse-for-card [pulse {:card my-card, :pulse pulse-properties, ...}] ...)" [[pulse-binding properties] & body] `(do-with-pulse-for-card ~properties (fn [~pulse-binding] ~@body))) (defn- do-test "Run a single Pulse test with a standard set of boilerplate. Creates Card, Pulse, and other related objects using `card`, `pulse`, `pulse-card` properties, then sends the Pulse; finally, test assertions in `assert` are invoked. `assert` can contain `:email` and/or `:slack` assertions, which are used to test an email and Slack version of that Pulse respectively. `:assert` functions have the signature (f object-ids send-pulse!-response) Example: (do-test {:card {:dataset_query (mt/mbql-query checkins)} :assert {:slack (fn [{:keys [pulse-id]} response] (is (= {:sent pulse-id} response)))}})" [{:keys [card pulse pulse-card fixture], assertions :assert}] {:pre [(map? assertions) ((some-fn :email :slack) assertions)]} (doseq [channel-type [:email :slack] :let [f (get assertions channel-type)] :when f] (assert (fn? f)) (testing (format "sent to %s channel" channel-type) (mt/with-temp* [Card [{card-id :id} (merge {:name card-name} card)]] (with-pulse-for-card [{pulse-id :id} {:card card-id :pulse pulse :pulse-card pulse-card :channel channel-type}] (letfn [(thunk* [] (f {:card-id card-id, :pulse-id pulse-id} (pulse/send-pulse! (models.pulse/retrieve-notification pulse-id)))) (thunk [] (if fixture (fixture {:card-id card-id, :pulse-id pulse-id} thunk*) (thunk*)))] (case channel-type :email (email-test-setup (thunk)) :slack (slack-test-setup (thunk))))))))) (defn- tests "Convenience for writing multiple tests using `do-test`. `common` is a map of shared properties as passed to `do-test` that is deeply merged with the individual maps for each test. Other args are alternating `testing` context messages and properties as passed to `do-test`: (tests ;; shared properties used for both tests {:card {:dataset_query (mt/mbql-query)}} \"Test 1\" {:assert {:email (fn [_ _] (is ...))}} \"Test 2\" ;; override just the :display property of the Card {:card {:display \"table\"} :assert {:email (fn [_ _] (is ...))}})" {:style/indent 1} [common & {:as message->m}] (doseq [[message m] message->m] (testing message (do-test (merge-with merge common m))))) (def ^:private test-card-result {card-name true}) (def ^:private test-card-regex (re-pattern card-name)) (defn- produces-bytes? [{:keys [rendered-info]}] (when rendered-info (pos? (alength (or (render/png-from-render-info rendered-info 500) (byte-array 0)))))) (defn- email-body? [{message-type :type, ^String content :content}] (and (= "text/html; charset=utf-8" message-type) (string? content) (.startsWith content "<html>"))) (defn- attachment? [{message-type :type, content-type :content-type, content :content}] (and (= :inline message-type) (= "image/png" content-type) (instance? java.net.URL content))) (defn- add-rasta-attachment "Append `attachment` to the first email found for Rasta" [email attachment] (update-in email ["<EMAIL>" 0] #(update % :body conj attachment))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Tests | ;;; +----------------------------------------------------------------------------------------------------------------+ (deftest basic-timeseries-test (do-test {:card (checkins-query-card {:breakout [!day.date]}) :pulse {:skip_if_empty false} :assert {:email (fn [_ _] (is (= (rasta-pulse-email) (mt/summarize-multipart-email #"Pulse Name")))) :slack (fn [{:keys [card-id]} [pulse-results]] (is (= {:channel-id "#general" :message "Pulse: Pulse Name" :attachments [{:title card-name :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id) :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean pulse-results))))}})) (deftest basic-table-test (tests {:pulse {:skip_if_empty false}} "19 results, so no attachment" {:card (checkins-query-card {:aggregation nil, :limit 19}) :fixture (fn [_ thunk] (with-redefs [render.body/attached-results-text (wrap-function @#'render.body/attached-results-text)] (thunk))) :assert {:email (fn [_ _] (is (= (rasta-pulse-email {:body [{"Pulse Name" true "More results have been included" false "ID</th>" true "<a href=\\\"https://metabase.com/testmb/dashboard/" false}]}) (mt/summarize-multipart-email #"Pulse Name" #"More results have been included" #"ID</th>" #"<a href=\"https://metabase.com/testmb/dashboard/")))) :slack (fn [{:keys [card-id]} [pulse-results]] (testing "\"more results in attachment\" text should not be present for Slack Pulses" (testing "Pulse results" (is (= {:channel-id "#general" :message "Pulse: Pulse Name" :attachments [{:title card-name :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id) :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean pulse-results)))) (testing "attached-results-text should be invoked exactly once" (is (= 1 (count (input @#'render.body/attached-results-text))))) (testing "attached-results-text should return nil since it's a slack message" (is (= [nil] (output @#'render.body/attached-results-text))))))}} "21 results results in a CSV being attached and a table being sent" {:card (checkins-query-card {:aggregation nil, :limit 21}) :assert {:email (fn [_ _] (is (= (rasta-pulse-email {:body [{"Pulse Name" true "More results have been included" true "ID</th>" true} csv-attachment]}) (mt/summarize-multipart-email #"Pulse Name" #"More results have been included" #"ID</th>"))))}})) (deftest csv-test (tests {:pulse {:skip_if_empty false} :card (checkins-query-card {:breakout [!day.date]})} "alert with a CSV" {:pulse-card {:include_csv true} :assert {:email (fn [_ _] (is (= (rasta-alert-email "Pulse: Pulse Name" [test-card-result png-attachment csv-attachment]) (mt/summarize-multipart-email test-card-regex))))}} "With a \"rows\" type of pulse (table visualization) we should include the CSV by default" {:card {:dataset_query (mt/mbql-query checkins)} :assert {:email (fn [_ _] (is (= (-> (rasta-pulse-email) ;; There's no PNG with a table visualization, remove it from the assert results (update-in ["<EMAIL>" 0 :body] (comp vector first)) (add-rasta-attachment csv-attachment)) (mt/summarize-multipart-email #"Pulse Name"))))}})) (deftest xls-test (testing "If the pulse is already configured to send an XLS, no need to include a CSV" (do-test {:card {:dataset_query (mt/mbql-query checkins)} :pulse-card {:include_xls true} :assert {:email (fn [_ _] (is (= (-> (rasta-pulse-email) ;; There's no PNG with a table visualization, remove it from the assert results (update-in ["<EMAIL>" 0 :body] (comp vector first)) (add-rasta-attachment xls-attachment)) (mt/summarize-multipart-email #"Pulse Name"))))}}))) ;; Not really sure how this is significantly different from `xls-test` (deftest xls-test-2 (testing "Basic test, 1 card, 1 recipient, with XLS attachment" (do-test {:card (checkins-query-card {:breakout [!day.date]}) :pulse-card {:include_xls true} :assert {:email (fn [_ _] (is (= (add-rasta-attachment (rasta-pulse-email) xls-attachment) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest csv-xls-no-data-test (testing "card with CSV and XLS attachments, but no data. Should not include an attachment" (do-test {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]}) :pulse {:skip_if_empty false} :pulse-card {:include_csv true :include_xls true} :assert {:email (fn [_ _] (is (= (rasta-pulse-email) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest ensure-constraints-test (testing "Validate pulse queries are limited by `default-query-constraints`" (do-test {:card (checkins-query-card {:aggregation nil}) :fixture (fn [_ thunk] (with-redefs [constraints/default-query-constraints {:max-results 10000 :max-results-bare-rows 30}] (thunk))) :assert {:email (fn [_ _] (let [first-message (-> @mt/inbox vals ffirst)] (is (= true (some? first-message)) "Should have a message in the inbox") (when first-message (let [filename (-> first-message :body last :content) exists? (some-> filename io/file .exists)] (testing "File should exist" (is (= true exists?))) (testing (str "tmp file = %s" filename) (testing "Slurp in the generated CSV and count the lines found in the file" (when exists? (testing "Should return 30 results (the redef'd limit) plus the header row" (is (= 31 (-> (slurp filename) str/split-lines count)))))))))))}}))) (deftest multiple-recipients-test (testing "Pulse should be sent to two recipients" (do-test {:card (checkins-query-card {:breakout [!day.date]}) :fixture (fn [{:keys [pulse-id]} thunk] (mt/with-temp PulseChannelRecipient [_ {:user_id (mt/user->id :crowberto) :pulse_channel_id (db/select-one-id PulseChannel :pulse_id pulse-id)}] (thunk))) :assert {:email (fn [_ _] (is (= (into {} (map (fn [user-kwd] (mt/email-to user-kwd {:subject "Pulse: Pulse Name", :to #{"<EMAIL>" "<EMAIL>"} :body [{"Pulse Name" true} png-attachment]})) [:rasta :crowberto])) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest two-cards-in-one-pulse-test (testing "1 pulse that has 2 cards, should contain two attachments" (do-test {:card (assoc (checkins-query-card {:breakout [!day.date]}) :name "card 1") :fixture (fn [{:keys [pulse-id]} thunk] (mt/with-temp* [Card [{card-id-2 :id} (assoc (checkins-query-card {:breakout [!month.date]}) :name "card 2")] PulseCard [_ {:pulse_id pulse-id :card_id card-id-2 :position 1}]] (thunk))) :assert {:email (fn [_ _] (is (= (rasta-pulse-email {:body [{"Pulse Name" true} png-attachment png-attachment]}) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest empty-results-test (testing "Pulse where the card has no results" (tests {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]})} "skip if empty = false" {:pulse {:skip_if_empty false} :assert {:email (fn [_ _] (is (= (rasta-pulse-email) (mt/summarize-multipart-email #"Pulse Name"))))}} "skip if empty = true" {:pulse {:skip_if_empty true} :assert {:email (fn [_ _] (is (= {} (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest rows-alert-test (testing "Rows alert" (tests {:pulse {:alert_condition "rows", :alert_first_only false}} "with data" {:card (checkins-query-card {:breakout [!day.date]}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [(assoc test-card-result "More results have been included" false) png-attachment]) (mt/summarize-multipart-email test-card-regex #"More results have been included")))) :slack (fn [{:keys [card-id]} [result]] (is (= {:channel-id "#general", :message "Alert: Test card", :attachments [{:title card-name :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id) :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean result))) (is (every? produces-bytes? (:attachments result))))}} "with no data" {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]}) :assert {:email (fn [_ _] (is (= {} @mt/inbox)))}} "too much data" {:card (checkins-query-card {:limit 21, :aggregation nil}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [(merge test-card-result {"More results have been included" true "ID</th>" true}) csv-attachment]) (mt/summarize-multipart-email test-card-regex #"More results have been included" #"ID</th>"))))}} "with data and a CSV + XLS attachment" {:card (checkins-query-card {:breakout [!day.date]}) :pulse-card {:include_csv true, :include_xls true} :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [test-card-result png-attachment csv-attachment xls-attachment]) (mt/summarize-multipart-email test-card-regex))))}}))) (deftest alert-first-run-only-test (tests {:pulse {:alert_condition "rows", :alert_first_only true}} "first run only with data" {:card (checkins-query-card {:breakout [!day.date]}) :assert {:email (fn [{:keys [pulse-id]} _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [(assoc test-card-result "stop sending you alerts" true) png-attachment]) (mt/summarize-multipart-email test-card-regex #"stop sending you alerts"))) (testing "Pulse should be deleted" (is (= false (db/exists? Pulse :id pulse-id)))))}} "first run alert with no data" {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]}) :assert {:email (fn [{:keys [pulse-id]} _] (is (= {} @mt/inbox)) (testing "Pulse should still exist" (is (= true (db/exists? Pulse :id pulse-id)))))}})) (deftest above-goal-alert-test (testing "above goal alert" (tests {:pulse {:alert_condition "goal" :alert_first_only false :alert_above_goal true}} "with data" {:card (merge (checkins-query-card {:filter [:between $date "2014-04-01" "2014-06-01"] :breakout [!day.date]}) {:display :line :visualization_settings {:graph.show_goal true :graph.goal_value 5.9}}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has reached its goal" [test-card-result, png-attachment]) (mt/summarize-multipart-email test-card-regex))))}} "no data" {:card (merge (checkins-query-card {:filter [:between $date "2014-02-01" "2014-04-01"] :breakout [!day.date]}) {:display :area :visualization_settings {:graph.show_goal true :graph.goal_value 5.9}}) :assert {:email (fn [_ _] (is (= {} @mt/inbox)))}} "with progress bar" {:card (merge (venues-query-card "max") {:display :progress :visualization_settings {:progress.goal 3}}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has reached its goal" [test-card-result]) (mt/summarize-multipart-email test-card-regex))))}}))) (deftest below-goal-alert-test (testing "Below goal alert" (tests {:card {:display :bar :visualization_settings {:graph.show_goal true :graph.goal_value 1.1}} :pulse {:alert_condition "goal" :alert_first_only false :alert_above_goal false}} "with data" {:card (checkins-query-card {:filter [:between $date "2014-02-12" "2014-02-17"] :breakout [!day.date]}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has gone below its goal" [test-card-result png-attachment]) (mt/summarize-multipart-email test-card-regex))))}} "with no satisfying data" {:card (checkins-query-card {:filter [:between $date "2014-02-10" "2014-02-12"] :breakout [!day.date]}) :assert {:email (fn [_ _] (is (= {} @mt/inbox)))}} "with progress bar" {:card (merge (venues-query-card "min") {:display :progress :visualization_settings {:progress.goal 2}}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has gone below its goal" [test-card-result]) (mt/summarize-multipart-email test-card-regex))))}}))) (deftest native-query-with-user-specified-axes-test (testing "Native query with user-specified x and y axis" (mt/with-temp Card [{card-id :id} {:name "<NAME> card" :dataset_query {:database (mt/id) :type :native :native {:query (str "select count(*) as total_per_day, date as the_day " "from checkins " "group by date")}} :display :line :visualization_settings {:graph.show_goal true :graph.goal_value 5.9 :graph.dimensions ["the_day"] :graph.metrics ["total_per_day"]}}] (with-pulse-for-card [{pulse-id :id} {:card card-id, :pulse {:alert_condition "goal" :alert_first_only false :alert_above_goal true}}] (email-test-setup (pulse/send-pulse! (models.pulse/retrieve-notification pulse-id)) (is (= (rasta-alert-email "Metabase alert: Test card has reached its goal" [test-card-result png-attachment]) (mt/summarize-multipart-email test-card-regex)))))))) (deftest basic-slack-test-2 (testing "Basic slack test, 2 cards, 1 recipient channel" (mt/with-temp* [Card [{card-id-1 :id} (checkins-query-card {:breakout [!day.date]})] Card [{card-id-2 :id} (-> {:breakout [[:datetime-field (mt/id :checkins :date) "minute"]]} checkins-query-card (assoc :name "Test card 2"))] Pulse [{pulse-id :id} {:name "Pulse Name" :skip_if_empty false}] PulseCard [_ {:pulse_id pulse-id :card_id card-id-1 :position 0}] PulseCard [_ {:pulse_id pulse-id :card_id card-id-2 :position 1}] PulseChannel [{pc-id :id} {:pulse_id pulse-id :channel_type "slack" :details {:channel "#general"}}]] (slack-test-setup (let [[slack-data] (pulse/send-pulse! (models.pulse/retrieve-pulse pulse-id))] (is (= {:channel-id "#general", :message "Pulse: Pulse Name", :attachments [{:title card-name, :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id-1), :attachment-name "image.png", :channel-id "FOO", :fallback card-name} {:title "Test card 2", :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id-2), :attachment-name "image.png", :channel-id "FOO", :fallback "Test card 2"}]} (thunk->boolean slack-data))) (testing "attachments" (is (true? (every? produces-bytes? (:attachments slack-data)))))))))) (deftest create-and-upload-slack-attachments!-test (let [slack-uploader (fn [storage] (fn [_bytes attachment-name _channel-id] (swap! storage conj attachment-name) (str "http://uploaded/" attachment-name)))] (testing "Uploads files" (let [titles (atom []) attachments [{:title "a" :attachment-name "a.png" :rendered-info {:attachments nil :content [:div "hi"]} :channel-id "FOO"} {:title "b" :attachment-name "b.png" :rendered-info {:attachments nil :content [:div "hi again"]} :channel-id "FOO"}] processed (pulse/create-and-upload-slack-attachments! attachments (slack-uploader titles))] (is (= [{:title "a", :image_url "http://uploaded/a.png"} {:title "b", :image_url "http://uploaded/b.png"}] processed)) (is (= @titles ["a.png" "b.png"])))) (testing "Uses the raw text when present" (let [titles (atom []) attachments [{:title "a" :attachment-name "a.png" :rendered-info {:attachments nil :content [:div "hi"]} :channel-id "FOO"} {:title "b" :attachment-name "b.png" :rendered-info {:attachments nil :content [:div "hi again"] :render/text "hi again"} :channel-id "FOO"}] processed (pulse/create-and-upload-slack-attachments! attachments (slack-uploader titles))] (is (= [{:title "a", :image_url "http://uploaded/a.png"} {:title "b", :text "hi again"}] processed)) (is (= @titles ["a.png"])))))) (deftest multi-channel-test (testing "Test with a slack channel and an email" (mt/with-temp Card [{card-id :id} (checkins-query-card {:breakout [!day.date]})] ;; create a Pulse with an email channel (with-pulse-for-card [{pulse-id :id} {:card card-id, :pulse {:skip_if_empty false}}] ;; add additional Slack channel (mt/with-temp PulseChannel [_ {:pulse_id pulse-id :channel_type "slack" :details {:channel "#general"}}] (slack-test-setup (let [pulse-data (pulse/send-pulse! (models.pulse/retrieve-pulse pulse-id)) slack-data (m/find-first #(contains? % :channel-id) pulse-data) email-data (m/find-first #(contains? % :subject) pulse-data)] (is (= {:channel-id "#general" :message "Pulse: Pulse Name" :attachments [{:title card-name :title_link (str "https://metabase.com/testmb/question/" card-id) :rendered-info {:attachments false :content true} :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean slack-data))) (is (= [true] (map (comp some? :content :rendered-info) (:attachments slack-data)))) (is (= {:subject "Pulse: Pulse Name", :recipients ["<EMAIL>"], :message-type :attachments} (select-keys email-data [:subject :recipients :message-type]))) (is (= 2 (count (:message email-data)))) (is (email-body? (first (:message email-data)))) (is (attachment? (second (:message email-data))))))))))) (deftest dont-run-async-test (testing "even if Card is saved as `:async?` we shouldn't run the query async" (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :venues)} :async? true}}] (is (schema= {:card (s/pred map?) :result (s/pred map?)} (pulse/execute-card {:creator_id (mt/user->id :rasta)} card)))))) (deftest pulse-permissions-test (testing "Pulses should be sent with the Permissions of the user that created them." (letfn [(send-pulse-created-by-user!* [user-kw] (mt/with-temp* [Collection [coll] Card [card {:dataset_query (mt/mbql-query checkins {:order-by [[:asc $id]] :limit 1}) :collection_id (:id coll)}]] (perms/revoke-collection-permissions! (group/all-users) coll) (send-pulse-created-by-user! user-kw card)))] (is (= [[1 "2014-04-07T00:00:00Z" 5 12]] (send-pulse-created-by-user!* :crowberto))) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"^You do not have permissions to view Card [\d,]+." (mt/suppress-output (send-pulse-created-by-user!* :rasta))) "If the current user doesn't have permissions to execute the Card for a Pulse, an Exception should be thrown."))))
true
(ns metabase.pulse-test (:require [clojure.java.io :as io] [clojure.string :as str] [clojure.test :refer :all] [medley.core :as m] [metabase.models :refer [Card Collection Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group] [metabase.models.pulse :as models.pulse] [metabase.pulse :as pulse] [metabase.pulse.render :as render] [metabase.pulse.render.body :as render.body] [metabase.pulse.test-util :refer :all] [metabase.query-processor.middleware.constraints :as constraints] [metabase.test :as mt] [metabase.util :as u] [schema.core :as s] [toucan.db :as db])) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Util Fns & Macros | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- rasta-pulse-email [& [email]] (mt/email-to :rasta (merge {:subject "Pulse: Pulse Name", :body [{"Pulse Name" true} png-attachment]} email))) (defn- rasta-alert-email [subject email-body] (mt/email-to :rasta {:subject subject :body email-body})) (defn- do-with-pulse-for-card "Creates a Pulse and other relevant rows for a `card` (using `pulse` and `pulse-card` properties if specified), then invokes (f pulse)" [{:keys [pulse pulse-card channel card] :or {channel :email}} f] (mt/with-temp* [Pulse [{pulse-id :id, :as pulse} (-> pulse (merge {:name "Pulse Name"}))] PulseCard [_ (merge {:pulse_id pulse-id :card_id (u/the-id card) :position 0} pulse-card)] PulseChannel [{pc-id :id} (case channel :email {:pulse_id pulse-id} :slack {:pulse_id pulse-id :channel_type "slack" :details {:channel "#general"}})]] (if (= channel :email) (mt/with-temp PulseChannelRecipient [_ {:user_id (rasta-id) :pulse_channel_id pc-id}] (f pulse)) (f pulse)))) (defmacro ^:private with-pulse-for-card "e.g. (with-pulse-for-card [pulse {:card my-card, :pulse pulse-properties, ...}] ...)" [[pulse-binding properties] & body] `(do-with-pulse-for-card ~properties (fn [~pulse-binding] ~@body))) (defn- do-test "Run a single Pulse test with a standard set of boilerplate. Creates Card, Pulse, and other related objects using `card`, `pulse`, `pulse-card` properties, then sends the Pulse; finally, test assertions in `assert` are invoked. `assert` can contain `:email` and/or `:slack` assertions, which are used to test an email and Slack version of that Pulse respectively. `:assert` functions have the signature (f object-ids send-pulse!-response) Example: (do-test {:card {:dataset_query (mt/mbql-query checkins)} :assert {:slack (fn [{:keys [pulse-id]} response] (is (= {:sent pulse-id} response)))}})" [{:keys [card pulse pulse-card fixture], assertions :assert}] {:pre [(map? assertions) ((some-fn :email :slack) assertions)]} (doseq [channel-type [:email :slack] :let [f (get assertions channel-type)] :when f] (assert (fn? f)) (testing (format "sent to %s channel" channel-type) (mt/with-temp* [Card [{card-id :id} (merge {:name card-name} card)]] (with-pulse-for-card [{pulse-id :id} {:card card-id :pulse pulse :pulse-card pulse-card :channel channel-type}] (letfn [(thunk* [] (f {:card-id card-id, :pulse-id pulse-id} (pulse/send-pulse! (models.pulse/retrieve-notification pulse-id)))) (thunk [] (if fixture (fixture {:card-id card-id, :pulse-id pulse-id} thunk*) (thunk*)))] (case channel-type :email (email-test-setup (thunk)) :slack (slack-test-setup (thunk))))))))) (defn- tests "Convenience for writing multiple tests using `do-test`. `common` is a map of shared properties as passed to `do-test` that is deeply merged with the individual maps for each test. Other args are alternating `testing` context messages and properties as passed to `do-test`: (tests ;; shared properties used for both tests {:card {:dataset_query (mt/mbql-query)}} \"Test 1\" {:assert {:email (fn [_ _] (is ...))}} \"Test 2\" ;; override just the :display property of the Card {:card {:display \"table\"} :assert {:email (fn [_ _] (is ...))}})" {:style/indent 1} [common & {:as message->m}] (doseq [[message m] message->m] (testing message (do-test (merge-with merge common m))))) (def ^:private test-card-result {card-name true}) (def ^:private test-card-regex (re-pattern card-name)) (defn- produces-bytes? [{:keys [rendered-info]}] (when rendered-info (pos? (alength (or (render/png-from-render-info rendered-info 500) (byte-array 0)))))) (defn- email-body? [{message-type :type, ^String content :content}] (and (= "text/html; charset=utf-8" message-type) (string? content) (.startsWith content "<html>"))) (defn- attachment? [{message-type :type, content-type :content-type, content :content}] (and (= :inline message-type) (= "image/png" content-type) (instance? java.net.URL content))) (defn- add-rasta-attachment "Append `attachment` to the first email found for Rasta" [email attachment] (update-in email ["PI:EMAIL:<EMAIL>END_PI" 0] #(update % :body conj attachment))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Tests | ;;; +----------------------------------------------------------------------------------------------------------------+ (deftest basic-timeseries-test (do-test {:card (checkins-query-card {:breakout [!day.date]}) :pulse {:skip_if_empty false} :assert {:email (fn [_ _] (is (= (rasta-pulse-email) (mt/summarize-multipart-email #"Pulse Name")))) :slack (fn [{:keys [card-id]} [pulse-results]] (is (= {:channel-id "#general" :message "Pulse: Pulse Name" :attachments [{:title card-name :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id) :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean pulse-results))))}})) (deftest basic-table-test (tests {:pulse {:skip_if_empty false}} "19 results, so no attachment" {:card (checkins-query-card {:aggregation nil, :limit 19}) :fixture (fn [_ thunk] (with-redefs [render.body/attached-results-text (wrap-function @#'render.body/attached-results-text)] (thunk))) :assert {:email (fn [_ _] (is (= (rasta-pulse-email {:body [{"Pulse Name" true "More results have been included" false "ID</th>" true "<a href=\\\"https://metabase.com/testmb/dashboard/" false}]}) (mt/summarize-multipart-email #"Pulse Name" #"More results have been included" #"ID</th>" #"<a href=\"https://metabase.com/testmb/dashboard/")))) :slack (fn [{:keys [card-id]} [pulse-results]] (testing "\"more results in attachment\" text should not be present for Slack Pulses" (testing "Pulse results" (is (= {:channel-id "#general" :message "Pulse: Pulse Name" :attachments [{:title card-name :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id) :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean pulse-results)))) (testing "attached-results-text should be invoked exactly once" (is (= 1 (count (input @#'render.body/attached-results-text))))) (testing "attached-results-text should return nil since it's a slack message" (is (= [nil] (output @#'render.body/attached-results-text))))))}} "21 results results in a CSV being attached and a table being sent" {:card (checkins-query-card {:aggregation nil, :limit 21}) :assert {:email (fn [_ _] (is (= (rasta-pulse-email {:body [{"Pulse Name" true "More results have been included" true "ID</th>" true} csv-attachment]}) (mt/summarize-multipart-email #"Pulse Name" #"More results have been included" #"ID</th>"))))}})) (deftest csv-test (tests {:pulse {:skip_if_empty false} :card (checkins-query-card {:breakout [!day.date]})} "alert with a CSV" {:pulse-card {:include_csv true} :assert {:email (fn [_ _] (is (= (rasta-alert-email "Pulse: Pulse Name" [test-card-result png-attachment csv-attachment]) (mt/summarize-multipart-email test-card-regex))))}} "With a \"rows\" type of pulse (table visualization) we should include the CSV by default" {:card {:dataset_query (mt/mbql-query checkins)} :assert {:email (fn [_ _] (is (= (-> (rasta-pulse-email) ;; There's no PNG with a table visualization, remove it from the assert results (update-in ["PI:EMAIL:<EMAIL>END_PI" 0 :body] (comp vector first)) (add-rasta-attachment csv-attachment)) (mt/summarize-multipart-email #"Pulse Name"))))}})) (deftest xls-test (testing "If the pulse is already configured to send an XLS, no need to include a CSV" (do-test {:card {:dataset_query (mt/mbql-query checkins)} :pulse-card {:include_xls true} :assert {:email (fn [_ _] (is (= (-> (rasta-pulse-email) ;; There's no PNG with a table visualization, remove it from the assert results (update-in ["PI:EMAIL:<EMAIL>END_PI" 0 :body] (comp vector first)) (add-rasta-attachment xls-attachment)) (mt/summarize-multipart-email #"Pulse Name"))))}}))) ;; Not really sure how this is significantly different from `xls-test` (deftest xls-test-2 (testing "Basic test, 1 card, 1 recipient, with XLS attachment" (do-test {:card (checkins-query-card {:breakout [!day.date]}) :pulse-card {:include_xls true} :assert {:email (fn [_ _] (is (= (add-rasta-attachment (rasta-pulse-email) xls-attachment) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest csv-xls-no-data-test (testing "card with CSV and XLS attachments, but no data. Should not include an attachment" (do-test {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]}) :pulse {:skip_if_empty false} :pulse-card {:include_csv true :include_xls true} :assert {:email (fn [_ _] (is (= (rasta-pulse-email) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest ensure-constraints-test (testing "Validate pulse queries are limited by `default-query-constraints`" (do-test {:card (checkins-query-card {:aggregation nil}) :fixture (fn [_ thunk] (with-redefs [constraints/default-query-constraints {:max-results 10000 :max-results-bare-rows 30}] (thunk))) :assert {:email (fn [_ _] (let [first-message (-> @mt/inbox vals ffirst)] (is (= true (some? first-message)) "Should have a message in the inbox") (when first-message (let [filename (-> first-message :body last :content) exists? (some-> filename io/file .exists)] (testing "File should exist" (is (= true exists?))) (testing (str "tmp file = %s" filename) (testing "Slurp in the generated CSV and count the lines found in the file" (when exists? (testing "Should return 30 results (the redef'd limit) plus the header row" (is (= 31 (-> (slurp filename) str/split-lines count)))))))))))}}))) (deftest multiple-recipients-test (testing "Pulse should be sent to two recipients" (do-test {:card (checkins-query-card {:breakout [!day.date]}) :fixture (fn [{:keys [pulse-id]} thunk] (mt/with-temp PulseChannelRecipient [_ {:user_id (mt/user->id :crowberto) :pulse_channel_id (db/select-one-id PulseChannel :pulse_id pulse-id)}] (thunk))) :assert {:email (fn [_ _] (is (= (into {} (map (fn [user-kwd] (mt/email-to user-kwd {:subject "Pulse: Pulse Name", :to #{"PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI"} :body [{"Pulse Name" true} png-attachment]})) [:rasta :crowberto])) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest two-cards-in-one-pulse-test (testing "1 pulse that has 2 cards, should contain two attachments" (do-test {:card (assoc (checkins-query-card {:breakout [!day.date]}) :name "card 1") :fixture (fn [{:keys [pulse-id]} thunk] (mt/with-temp* [Card [{card-id-2 :id} (assoc (checkins-query-card {:breakout [!month.date]}) :name "card 2")] PulseCard [_ {:pulse_id pulse-id :card_id card-id-2 :position 1}]] (thunk))) :assert {:email (fn [_ _] (is (= (rasta-pulse-email {:body [{"Pulse Name" true} png-attachment png-attachment]}) (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest empty-results-test (testing "Pulse where the card has no results" (tests {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]})} "skip if empty = false" {:pulse {:skip_if_empty false} :assert {:email (fn [_ _] (is (= (rasta-pulse-email) (mt/summarize-multipart-email #"Pulse Name"))))}} "skip if empty = true" {:pulse {:skip_if_empty true} :assert {:email (fn [_ _] (is (= {} (mt/summarize-multipart-email #"Pulse Name"))))}}))) (deftest rows-alert-test (testing "Rows alert" (tests {:pulse {:alert_condition "rows", :alert_first_only false}} "with data" {:card (checkins-query-card {:breakout [!day.date]}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [(assoc test-card-result "More results have been included" false) png-attachment]) (mt/summarize-multipart-email test-card-regex #"More results have been included")))) :slack (fn [{:keys [card-id]} [result]] (is (= {:channel-id "#general", :message "Alert: Test card", :attachments [{:title card-name :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id) :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean result))) (is (every? produces-bytes? (:attachments result))))}} "with no data" {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]}) :assert {:email (fn [_ _] (is (= {} @mt/inbox)))}} "too much data" {:card (checkins-query-card {:limit 21, :aggregation nil}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [(merge test-card-result {"More results have been included" true "ID</th>" true}) csv-attachment]) (mt/summarize-multipart-email test-card-regex #"More results have been included" #"ID</th>"))))}} "with data and a CSV + XLS attachment" {:card (checkins-query-card {:breakout [!day.date]}) :pulse-card {:include_csv true, :include_xls true} :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [test-card-result png-attachment csv-attachment xls-attachment]) (mt/summarize-multipart-email test-card-regex))))}}))) (deftest alert-first-run-only-test (tests {:pulse {:alert_condition "rows", :alert_first_only true}} "first run only with data" {:card (checkins-query-card {:breakout [!day.date]}) :assert {:email (fn [{:keys [pulse-id]} _] (is (= (rasta-alert-email "Metabase alert: Test card has results" [(assoc test-card-result "stop sending you alerts" true) png-attachment]) (mt/summarize-multipart-email test-card-regex #"stop sending you alerts"))) (testing "Pulse should be deleted" (is (= false (db/exists? Pulse :id pulse-id)))))}} "first run alert with no data" {:card (checkins-query-card {:filter [:> $date "2017-10-24"] :breakout [!day.date]}) :assert {:email (fn [{:keys [pulse-id]} _] (is (= {} @mt/inbox)) (testing "Pulse should still exist" (is (= true (db/exists? Pulse :id pulse-id)))))}})) (deftest above-goal-alert-test (testing "above goal alert" (tests {:pulse {:alert_condition "goal" :alert_first_only false :alert_above_goal true}} "with data" {:card (merge (checkins-query-card {:filter [:between $date "2014-04-01" "2014-06-01"] :breakout [!day.date]}) {:display :line :visualization_settings {:graph.show_goal true :graph.goal_value 5.9}}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has reached its goal" [test-card-result, png-attachment]) (mt/summarize-multipart-email test-card-regex))))}} "no data" {:card (merge (checkins-query-card {:filter [:between $date "2014-02-01" "2014-04-01"] :breakout [!day.date]}) {:display :area :visualization_settings {:graph.show_goal true :graph.goal_value 5.9}}) :assert {:email (fn [_ _] (is (= {} @mt/inbox)))}} "with progress bar" {:card (merge (venues-query-card "max") {:display :progress :visualization_settings {:progress.goal 3}}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has reached its goal" [test-card-result]) (mt/summarize-multipart-email test-card-regex))))}}))) (deftest below-goal-alert-test (testing "Below goal alert" (tests {:card {:display :bar :visualization_settings {:graph.show_goal true :graph.goal_value 1.1}} :pulse {:alert_condition "goal" :alert_first_only false :alert_above_goal false}} "with data" {:card (checkins-query-card {:filter [:between $date "2014-02-12" "2014-02-17"] :breakout [!day.date]}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has gone below its goal" [test-card-result png-attachment]) (mt/summarize-multipart-email test-card-regex))))}} "with no satisfying data" {:card (checkins-query-card {:filter [:between $date "2014-02-10" "2014-02-12"] :breakout [!day.date]}) :assert {:email (fn [_ _] (is (= {} @mt/inbox)))}} "with progress bar" {:card (merge (venues-query-card "min") {:display :progress :visualization_settings {:progress.goal 2}}) :assert {:email (fn [_ _] (is (= (rasta-alert-email "Metabase alert: Test card has gone below its goal" [test-card-result]) (mt/summarize-multipart-email test-card-regex))))}}))) (deftest native-query-with-user-specified-axes-test (testing "Native query with user-specified x and y axis" (mt/with-temp Card [{card-id :id} {:name "PI:NAME:<NAME>END_PI card" :dataset_query {:database (mt/id) :type :native :native {:query (str "select count(*) as total_per_day, date as the_day " "from checkins " "group by date")}} :display :line :visualization_settings {:graph.show_goal true :graph.goal_value 5.9 :graph.dimensions ["the_day"] :graph.metrics ["total_per_day"]}}] (with-pulse-for-card [{pulse-id :id} {:card card-id, :pulse {:alert_condition "goal" :alert_first_only false :alert_above_goal true}}] (email-test-setup (pulse/send-pulse! (models.pulse/retrieve-notification pulse-id)) (is (= (rasta-alert-email "Metabase alert: Test card has reached its goal" [test-card-result png-attachment]) (mt/summarize-multipart-email test-card-regex)))))))) (deftest basic-slack-test-2 (testing "Basic slack test, 2 cards, 1 recipient channel" (mt/with-temp* [Card [{card-id-1 :id} (checkins-query-card {:breakout [!day.date]})] Card [{card-id-2 :id} (-> {:breakout [[:datetime-field (mt/id :checkins :date) "minute"]]} checkins-query-card (assoc :name "Test card 2"))] Pulse [{pulse-id :id} {:name "Pulse Name" :skip_if_empty false}] PulseCard [_ {:pulse_id pulse-id :card_id card-id-1 :position 0}] PulseCard [_ {:pulse_id pulse-id :card_id card-id-2 :position 1}] PulseChannel [{pc-id :id} {:pulse_id pulse-id :channel_type "slack" :details {:channel "#general"}}]] (slack-test-setup (let [[slack-data] (pulse/send-pulse! (models.pulse/retrieve-pulse pulse-id))] (is (= {:channel-id "#general", :message "Pulse: Pulse Name", :attachments [{:title card-name, :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id-1), :attachment-name "image.png", :channel-id "FOO", :fallback card-name} {:title "Test card 2", :rendered-info {:attachments false :content true} :title_link (str "https://metabase.com/testmb/question/" card-id-2), :attachment-name "image.png", :channel-id "FOO", :fallback "Test card 2"}]} (thunk->boolean slack-data))) (testing "attachments" (is (true? (every? produces-bytes? (:attachments slack-data)))))))))) (deftest create-and-upload-slack-attachments!-test (let [slack-uploader (fn [storage] (fn [_bytes attachment-name _channel-id] (swap! storage conj attachment-name) (str "http://uploaded/" attachment-name)))] (testing "Uploads files" (let [titles (atom []) attachments [{:title "a" :attachment-name "a.png" :rendered-info {:attachments nil :content [:div "hi"]} :channel-id "FOO"} {:title "b" :attachment-name "b.png" :rendered-info {:attachments nil :content [:div "hi again"]} :channel-id "FOO"}] processed (pulse/create-and-upload-slack-attachments! attachments (slack-uploader titles))] (is (= [{:title "a", :image_url "http://uploaded/a.png"} {:title "b", :image_url "http://uploaded/b.png"}] processed)) (is (= @titles ["a.png" "b.png"])))) (testing "Uses the raw text when present" (let [titles (atom []) attachments [{:title "a" :attachment-name "a.png" :rendered-info {:attachments nil :content [:div "hi"]} :channel-id "FOO"} {:title "b" :attachment-name "b.png" :rendered-info {:attachments nil :content [:div "hi again"] :render/text "hi again"} :channel-id "FOO"}] processed (pulse/create-and-upload-slack-attachments! attachments (slack-uploader titles))] (is (= [{:title "a", :image_url "http://uploaded/a.png"} {:title "b", :text "hi again"}] processed)) (is (= @titles ["a.png"])))))) (deftest multi-channel-test (testing "Test with a slack channel and an email" (mt/with-temp Card [{card-id :id} (checkins-query-card {:breakout [!day.date]})] ;; create a Pulse with an email channel (with-pulse-for-card [{pulse-id :id} {:card card-id, :pulse {:skip_if_empty false}}] ;; add additional Slack channel (mt/with-temp PulseChannel [_ {:pulse_id pulse-id :channel_type "slack" :details {:channel "#general"}}] (slack-test-setup (let [pulse-data (pulse/send-pulse! (models.pulse/retrieve-pulse pulse-id)) slack-data (m/find-first #(contains? % :channel-id) pulse-data) email-data (m/find-first #(contains? % :subject) pulse-data)] (is (= {:channel-id "#general" :message "Pulse: Pulse Name" :attachments [{:title card-name :title_link (str "https://metabase.com/testmb/question/" card-id) :rendered-info {:attachments false :content true} :attachment-name "image.png" :channel-id "FOO" :fallback card-name}]} (thunk->boolean slack-data))) (is (= [true] (map (comp some? :content :rendered-info) (:attachments slack-data)))) (is (= {:subject "Pulse: Pulse Name", :recipients ["PI:EMAIL:<EMAIL>END_PI"], :message-type :attachments} (select-keys email-data [:subject :recipients :message-type]))) (is (= 2 (count (:message email-data)))) (is (email-body? (first (:message email-data)))) (is (attachment? (second (:message email-data))))))))))) (deftest dont-run-async-test (testing "even if Card is saved as `:async?` we shouldn't run the query async" (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :venues)} :async? true}}] (is (schema= {:card (s/pred map?) :result (s/pred map?)} (pulse/execute-card {:creator_id (mt/user->id :rasta)} card)))))) (deftest pulse-permissions-test (testing "Pulses should be sent with the Permissions of the user that created them." (letfn [(send-pulse-created-by-user!* [user-kw] (mt/with-temp* [Collection [coll] Card [card {:dataset_query (mt/mbql-query checkins {:order-by [[:asc $id]] :limit 1}) :collection_id (:id coll)}]] (perms/revoke-collection-permissions! (group/all-users) coll) (send-pulse-created-by-user! user-kw card)))] (is (= [[1 "2014-04-07T00:00:00Z" 5 12]] (send-pulse-created-by-user!* :crowberto))) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"^You do not have permissions to view Card [\d,]+." (mt/suppress-output (send-pulse-created-by-user!* :rasta))) "If the current user doesn't have permissions to execute the Card for a Pulse, an Exception should be thrown."))))
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis", "end": 33, "score": 0.9998549818992615, "start": 19, "tag": "NAME", "value": "Nicola Mometto" }, { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution ter", "end": 46, "score": 0.9998427629470825, "start": 35, "tag": "NAME", "value": "Rich Hickey" } ]
src/lucid/legacy/analyzer/passes/index_vector_nodes.clj
willcohen/lucidity
3
;; Copyright (c) Nicola Mometto, Rich Hickey & contributors. ;; 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 lucid.legacy.analyzer.passes.index-vector-nodes) (defn index-vector-nodes "Adds an :idx attribute to nodes in a vector children, representing the position of the node vector." [ast] (merge ast (reduce (fn [m c] (let [v (c ast) v (if (vector? v) (mapv (fn [x i] (assoc x :idx i )) v (range)) v)] (assoc m c v))) {} (:children ast))))
79083
;; Copyright (c) <NAME>, <NAME> & contributors. ;; 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 lucid.legacy.analyzer.passes.index-vector-nodes) (defn index-vector-nodes "Adds an :idx attribute to nodes in a vector children, representing the position of the node vector." [ast] (merge ast (reduce (fn [m c] (let [v (c ast) v (if (vector? v) (mapv (fn [x i] (assoc x :idx i )) v (range)) v)] (assoc m c v))) {} (:children ast))))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors. ;; 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 lucid.legacy.analyzer.passes.index-vector-nodes) (defn index-vector-nodes "Adds an :idx attribute to nodes in a vector children, representing the position of the node vector." [ast] (merge ast (reduce (fn [m c] (let [v (c ast) v (if (vector? v) (mapv (fn [x i] (assoc x :idx i )) v (range)) v)] (assoc m c v))) {} (:children ast))))
[ { "context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998798370361328, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
test/territory_bro/db_test.clj
JessRoberts/territory_assistant
0
;; Copyright © 2015-2019 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.db-test (:require [clojure.test :refer :all] [territory-bro.db :as db] [territory-bro.fixtures :refer [db-fixture]] [territory-bro.testutil :refer [re-contains]])) (use-fixtures :once db-fixture) (deftest check-database-version-test (is (nil? (db/check-database-version 10)) "newer than expected") (is (nil? (db/check-database-version 11)) "same as expected") (is (thrown-with-msg? AssertionError (re-contains "Expected the database to be PostgreSQL 12 but it was PostgreSQL 11") (db/check-database-version 12)) "older than expected"))
120437
;; Copyright © 2015-2019 <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.db-test (:require [clojure.test :refer :all] [territory-bro.db :as db] [territory-bro.fixtures :refer [db-fixture]] [territory-bro.testutil :refer [re-contains]])) (use-fixtures :once db-fixture) (deftest check-database-version-test (is (nil? (db/check-database-version 10)) "newer than expected") (is (nil? (db/check-database-version 11)) "same as expected") (is (thrown-with-msg? AssertionError (re-contains "Expected the database to be PostgreSQL 12 but it was PostgreSQL 11") (db/check-database-version 12)) "older than expected"))
true
;; Copyright © 2015-2019 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.db-test (:require [clojure.test :refer :all] [territory-bro.db :as db] [territory-bro.fixtures :refer [db-fixture]] [territory-bro.testutil :refer [re-contains]])) (use-fixtures :once db-fixture) (deftest check-database-version-test (is (nil? (db/check-database-version 10)) "newer than expected") (is (nil? (db/check-database-version 11)) "same as expected") (is (thrown-with-msg? AssertionError (re-contains "Expected the database to be PostgreSQL 12 but it was PostgreSQL 11") (db/check-database-version 12)) "older than expected"))
[ { "context": "tcp://activemq:61616?user=eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&ma", "end": 1242, "score": 0.9994199872016907, "start": 1232, "tag": "PASSWORD", "value": "notasecret" }, { "context": "eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=6000", "end": 1261, "score": 0.804040253162384, "start": 1258, "tag": "PASSWORD", "value": "000" }, { "context": "ysql.jdbc.Driver\",\n :user \"sa\",\n :password \"notasecret\"},\n :eva.v2.storage.value-store.core/partition-", "end": 1620, "score": 0.9993746876716614, "start": 1610, "tag": "PASSWORD", "value": "notasecret" }, { "context": "tcp://activemq:61616?user=eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&ma", "end": 2483, "score": 0.9988511204719543, "start": 2473, "tag": "PASSWORD", "value": "notasecret" }, { "context": "ysql.jdbc.Driver\",\n :user \"sa\",\n :password \"notasecret\"},\n :eva.v2.storage.value-store.core/partition-", "end": 2861, "score": 0.9993286728858948, "start": 2851, "tag": "PASSWORD", "value": "notasecret" }, { "context": "ysql.jdbc.Driver\",\n :user \"sa\",\n :password \"notasecret\"},\n :eva.v2.database.core/id\n #uuid \"eaf51494", "end": 4091, "score": 0.9992839694023132, "start": 4081, "tag": "PASSWORD", "value": "notasecret" }, { "context": "tcp://activemq:61616?user=eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&ma", "end": 4585, "score": 0.9964218139648438, "start": 4575, "tag": "PASSWORD", "value": "notasecret" }, { "context": "ysql.jdbc.Driver\",\n :user \"sa\",\n :password \"notasecret\"},\n :eva.v2.database.core/id\n #uuid \"f998bc77", "end": 5332, "score": 0.9993758201599121, "start": 5322, "tag": "PASSWORD", "value": "notasecret" }, { "context": "cret\"},\n :eva.v2.database.core/id\n #uuid \"f998bc77-c090-4c3a-b86e-1b063536bcf3\",\n :eva.v2.storage.", "end": 5382, "score": 0.6361489295959473, "start": 5378, "tag": "PASSWORD", "value": "bc77" }, { "context": ",\n :eva.v2.database.core/id\n #uuid \"f998bc77-c090-4c3a-b86e-1b063536bcf3\",\n :eva.v2.storage.block", "end": 5387, "score": 0.736665666103363, "start": 5384, "tag": "PASSWORD", "value": "090" }, { "context": " :eva.v2.database.core/id\n #uuid \"f998bc77-c090-4c3a-b86e-1b063536bcf3\",\n :eva.v2.storage.block-stor", "end": 5392, "score": 0.7193824052810669, "start": 5388, "tag": "PASSWORD", "value": "4c3a" }, { "context": "e/id\n #uuid \"f998bc77-c090-4c3a-b86e-1b063536bcf3\",\n :eva.v2.storage.block-store.types/storage-ty", "end": 5410, "score": 0.5135270953178406, "start": 5409, "tag": "PASSWORD", "value": "3" }, { "context": "tcp://activemq:61616?user=eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&ma", "end": 5826, "score": 0.999162495136261, "start": 5816, "tag": "PASSWORD", "value": "notasecret" }, { "context": "eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=600", "end": 5844, "score": 0.8124830722808838, "start": 5842, "tag": "PASSWORD", "value": "00" }, { "context": " :password (env \"EVA_STORAGE_SQL_PASSWORD\" \"special-transactor-password\")}))\n\n(def eva-test-2-labels\n #{test-db-3-config", "end": 6641, "score": 0.9953535199165344, "start": 6614, "tag": "PASSWORD", "value": "special-transactor-password" } ]
server.alpha/test/eva/catalog/server/alpha/handler_test.clj
Workiva/eva-catalog
1
;; Copyright 2018-2019 Workiva Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns eva.catalog.server.alpha.handler-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [ring.mock.request :as mock] [eva.catalog.server.alpha.handler :refer :all] [eva.catalog.common.alpha.config :as config] [eva.catalog.common.alpha.catalog :as c] [eva.catalog.common.alpha.utils :refer [*env-overrides* env]])) (def test-db-1-config {::config/tenant "workiva" ::config/category "eva-test-1" ::config/label "test-db-1" :messenger-node-config/type :broker-uri, :broker-uri "tcp://activemq:61616?user=eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "notasecret"}, :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :eva.v2.database.core/id #uuid "cad72d3a-3af7-4111-9d68-03c75102486d", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.cad72d3a-3af7-4111-9d68-03c75102486d", :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.cad72d3a-3af7-4111-9d68-03c75102486d", :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.cad72d3a-3af7-4111-9d68-03c75102486d"}) (def test-db-2-config {::config/tenant "workiva" ::config/category "eva-test-1" ::config/label "test-db-2" :messenger-node-config/type :broker-uri, :broker-uri "tcp://activemq:61616?user=eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "notasecret"}, :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :eva.v2.database.core/id #uuid"b3923f98-cae5-4503-a572-f19a1f261fb0", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.b3923f98-cae5-4503-a572-f19a1f261fb0", :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.b3923f98-cae5-4503-a572-f19a1f261fb0", :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.b3923f98-cae5-4503-a572-f19a1f261fb0"}) (def test-db-3-config {::config/tenant "workiva" ::config/category "eva-test-2" ::config/label "test-db-3" :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.eaf51494-0032-4381-971a-7946b012724c", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.eaf51494-0032-4381-971a-7946b012724c", :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "notasecret"}, :eva.v2.database.core/id #uuid "eaf51494-0032-4381-971a-7946b012724c", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.eaf51494-0032-4381-971a-7946b012724c", :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :broker-uri "tcp://activemq:61616?user=eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :messenger-node-config/type :broker-uri}) (def test-db-4-config {::config/tenant "workiva" ::config/category "eva-test-2" ::config/label "test-db-4" :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "notasecret"}, :eva.v2.database.core/id #uuid "f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :broker-uri "tcp://activemq:61616?user=eva-transactor&password=notasecret&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :messenger-node-config/type :broker-uri}) (def test-transactor-storage (config/sql-storage {:subprotocol (env "EVA_STORAGE_SQL_DB_TYPE" "mysql") :subname (format "//%s:%s/%s" (env "EVA_STORAGE_SQL_HOST" "localhost") (env "EVA_STORAGE_SQL_PORT" 3306) (env "EVA_STORAGE_SQL_DBNAME" "eva")) :classname (env "EVA_STORAGE_SQL_DRIVER" "com.mysql.jdbc.Driver") :user (env "EVA_STORAGE_SQL_USER" "special-transactor-user") :password (env "EVA_STORAGE_SQL_PASSWORD" "special-transactor-password")})) (def eva-test-2-labels #{test-db-3-config test-db-4-config}) (defn test-app [catalog] (let [app (build-routes catalog)] (testing "status route" (let [response (app (mock/request :get "/status"))] (is (= (:status response) 200)) (is (= (:body response) "All systems nominal.")))) (testing "flat-peer-config route" (let [happy-response (app (-> (mock/request :get "/flat-peer-config" {:tenant "workiva" :category "eva-test-1" :label "test-db-1"}) (mock/content-type "application/edn") (mock/header :accept "application/edn"))) sad-response (app (-> (mock/request :get "/flat-peer-config" {}) (mock/content-type "application/edn")))] (is (= (:status happy-response) 200)) (is (= (dissoc (read-string (slurp (:body happy-response))) :eva.v2.system.peer-connection.core/id) test-db-1-config)) (is (= (:status sad-response) 404)))) (testing "flat-peer-configs-for-tenant-and-category route" (let [happy-response (app (-> (mock/request :get "/flat-peer-configs-for-tenant-and-category" {:tenant "workiva" :category "eva-test-2"}) (mock/content-type "application/edn") (mock/header :accept "application/edn"))) sad-response (app (-> (mock/request :get "/flat-peer-configs-for-tenant-and-category" {:tenant "NOT-workiva" :category "eva-test-2"}) (mock/content-type "application/edn")))] (is (= (:status happy-response) 200)) (is (= (into #{} (read-string (slurp (:body happy-response)))) eva-test-2-labels)) (is (= (:status sad-response) 404)))) (testing "flat-peer-configs-for-category-and-label route" (let [happy-response (app (-> (mock/request :get "/flat-peer-configs-for-category-and-label" {:category "eva-test-2" :label "test-db-4"}) (mock/content-type "application/edn") (mock/header :accept "application/edn"))) sad-response (app (-> (mock/request :get "/flat-peer-configs-for-tenant-and-category" {:tenant "NOT-workiva" :category "eva-test-2"}) (mock/content-type "application/edn")))] (is (= (:status happy-response) 200)) (is (= (into #{} (read-string (slurp (:body happy-response)))) #{test-db-4-config})) (is (= (:status sad-response) 404)))) (testing "not-found route" (let [response (app (mock/request :get "/invalid"))] (is (= (:status response) 404)))))) (deftest test-edn-file-catalog (test-app (c/load-catalog {::c/type :edn-file :path (io/resource "eva/catalog/common/alpha/mock-catalog-data.edn")})))
43866
;; Copyright 2018-2019 Workiva Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns eva.catalog.server.alpha.handler-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [ring.mock.request :as mock] [eva.catalog.server.alpha.handler :refer :all] [eva.catalog.common.alpha.config :as config] [eva.catalog.common.alpha.catalog :as c] [eva.catalog.common.alpha.utils :refer [*env-overrides* env]])) (def test-db-1-config {::config/tenant "workiva" ::config/category "eva-test-1" ::config/label "test-db-1" :messenger-node-config/type :broker-uri, :broker-uri "tcp://activemq:61616?user=eva-transactor&password=<PASSWORD>&retryInterval=1<PASSWORD>&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "<PASSWORD>"}, :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :eva.v2.database.core/id #uuid "cad72d3a-3af7-4111-9d68-03c75102486d", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.cad72d3a-3af7-4111-9d68-03c75102486d", :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.cad72d3a-3af7-4111-9d68-03c75102486d", :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.cad72d3a-3af7-4111-9d68-03c75102486d"}) (def test-db-2-config {::config/tenant "workiva" ::config/category "eva-test-1" ::config/label "test-db-2" :messenger-node-config/type :broker-uri, :broker-uri "tcp://activemq:61616?user=eva-transactor&password=<PASSWORD>&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "<PASSWORD>"}, :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :eva.v2.database.core/id #uuid"b3923f98-cae5-4503-a572-f19a1f261fb0", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.b3923f98-cae5-4503-a572-f19a1f261fb0", :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.b3923f98-cae5-4503-a572-f19a1f261fb0", :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.b3923f98-cae5-4503-a572-f19a1f261fb0"}) (def test-db-3-config {::config/tenant "workiva" ::config/category "eva-test-2" ::config/label "test-db-3" :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.eaf51494-0032-4381-971a-7946b012724c", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.eaf51494-0032-4381-971a-7946b012724c", :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "<PASSWORD>"}, :eva.v2.database.core/id #uuid "eaf51494-0032-4381-971a-7946b012724c", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.eaf51494-0032-4381-971a-7946b012724c", :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :broker-uri "tcp://activemq:61616?user=eva-transactor&password=<PASSWORD>&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :messenger-node-config/type :broker-uri}) (def test-db-4-config {::config/tenant "workiva" ::config/category "eva-test-2" ::config/label "test-db-4" :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "<PASSWORD>"}, :eva.v2.database.core/id #uuid "f998<PASSWORD>-c<PASSWORD>-<PASSWORD>-b86e-1b063536bcf<PASSWORD>", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :broker-uri "tcp://activemq:61616?user=eva-transactor&password=<PASSWORD>&retryInterval=1<PASSWORD>0&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :messenger-node-config/type :broker-uri}) (def test-transactor-storage (config/sql-storage {:subprotocol (env "EVA_STORAGE_SQL_DB_TYPE" "mysql") :subname (format "//%s:%s/%s" (env "EVA_STORAGE_SQL_HOST" "localhost") (env "EVA_STORAGE_SQL_PORT" 3306) (env "EVA_STORAGE_SQL_DBNAME" "eva")) :classname (env "EVA_STORAGE_SQL_DRIVER" "com.mysql.jdbc.Driver") :user (env "EVA_STORAGE_SQL_USER" "special-transactor-user") :password (env "EVA_STORAGE_SQL_PASSWORD" "<PASSWORD>")})) (def eva-test-2-labels #{test-db-3-config test-db-4-config}) (defn test-app [catalog] (let [app (build-routes catalog)] (testing "status route" (let [response (app (mock/request :get "/status"))] (is (= (:status response) 200)) (is (= (:body response) "All systems nominal.")))) (testing "flat-peer-config route" (let [happy-response (app (-> (mock/request :get "/flat-peer-config" {:tenant "workiva" :category "eva-test-1" :label "test-db-1"}) (mock/content-type "application/edn") (mock/header :accept "application/edn"))) sad-response (app (-> (mock/request :get "/flat-peer-config" {}) (mock/content-type "application/edn")))] (is (= (:status happy-response) 200)) (is (= (dissoc (read-string (slurp (:body happy-response))) :eva.v2.system.peer-connection.core/id) test-db-1-config)) (is (= (:status sad-response) 404)))) (testing "flat-peer-configs-for-tenant-and-category route" (let [happy-response (app (-> (mock/request :get "/flat-peer-configs-for-tenant-and-category" {:tenant "workiva" :category "eva-test-2"}) (mock/content-type "application/edn") (mock/header :accept "application/edn"))) sad-response (app (-> (mock/request :get "/flat-peer-configs-for-tenant-and-category" {:tenant "NOT-workiva" :category "eva-test-2"}) (mock/content-type "application/edn")))] (is (= (:status happy-response) 200)) (is (= (into #{} (read-string (slurp (:body happy-response)))) eva-test-2-labels)) (is (= (:status sad-response) 404)))) (testing "flat-peer-configs-for-category-and-label route" (let [happy-response (app (-> (mock/request :get "/flat-peer-configs-for-category-and-label" {:category "eva-test-2" :label "test-db-4"}) (mock/content-type "application/edn") (mock/header :accept "application/edn"))) sad-response (app (-> (mock/request :get "/flat-peer-configs-for-tenant-and-category" {:tenant "NOT-workiva" :category "eva-test-2"}) (mock/content-type "application/edn")))] (is (= (:status happy-response) 200)) (is (= (into #{} (read-string (slurp (:body happy-response)))) #{test-db-4-config})) (is (= (:status sad-response) 404)))) (testing "not-found route" (let [response (app (mock/request :get "/invalid"))] (is (= (:status response) 404)))))) (deftest test-edn-file-catalog (test-app (c/load-catalog {::c/type :edn-file :path (io/resource "eva/catalog/common/alpha/mock-catalog-data.edn")})))
true
;; Copyright 2018-2019 Workiva Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns eva.catalog.server.alpha.handler-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [ring.mock.request :as mock] [eva.catalog.server.alpha.handler :refer :all] [eva.catalog.common.alpha.config :as config] [eva.catalog.common.alpha.catalog :as c] [eva.catalog.common.alpha.utils :refer [*env-overrides* env]])) (def test-db-1-config {::config/tenant "workiva" ::config/category "eva-test-1" ::config/label "test-db-1" :messenger-node-config/type :broker-uri, :broker-uri "tcp://activemq:61616?user=eva-transactor&password=PI:PASSWORD:<PASSWORD>END_PI&retryInterval=1PI:PASSWORD:<PASSWORD>END_PI&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "PI:PASSWORD:<PASSWORD>END_PI"}, :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :eva.v2.database.core/id #uuid "cad72d3a-3af7-4111-9d68-03c75102486d", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.cad72d3a-3af7-4111-9d68-03c75102486d", :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.cad72d3a-3af7-4111-9d68-03c75102486d", :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.cad72d3a-3af7-4111-9d68-03c75102486d"}) (def test-db-2-config {::config/tenant "workiva" ::config/category "eva-test-1" ::config/label "test-db-2" :messenger-node-config/type :broker-uri, :broker-uri "tcp://activemq:61616?user=eva-transactor&password=PI:PASSWORD:<PASSWORD>END_PI&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "PI:PASSWORD:<PASSWORD>END_PI"}, :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :eva.v2.database.core/id #uuid"b3923f98-cae5-4503-a572-f19a1f261fb0", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.b3923f98-cae5-4503-a572-f19a1f261fb0", :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.b3923f98-cae5-4503-a572-f19a1f261fb0", :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.b3923f98-cae5-4503-a572-f19a1f261fb0"}) (def test-db-3-config {::config/tenant "workiva" ::config/category "eva-test-2" ::config/label "test-db-3" :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.eaf51494-0032-4381-971a-7946b012724c", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.eaf51494-0032-4381-971a-7946b012724c", :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "PI:PASSWORD:<PASSWORD>END_PI"}, :eva.v2.database.core/id #uuid "eaf51494-0032-4381-971a-7946b012724c", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.eaf51494-0032-4381-971a-7946b012724c", :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :broker-uri "tcp://activemq:61616?user=eva-transactor&password=PI:PASSWORD:<PASSWORD>END_PI&retryInterval=1000&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :messenger-node-config/type :broker-uri}) (def test-db-4-config {::config/tenant "workiva" ::config/category "eva-test-2" ::config/label "test-db-4" :eva.v2.messaging.address/transaction-publication "eva.v2.transacted.63621540-10fc-402a-b305-97f312d0f8f0.f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.messaging.address/transaction-submission "eva.v2.transact.63621540-10fc-402a-b305-97f312d0f8f0.f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.storage.block-store.impl.sql/db-spec {:subprotocol "mysql", :subname "//localhost:3306/eva", :classname "com.mysql.jdbc.Driver", :user "sa", :password "PI:PASSWORD:<PASSWORD>END_PI"}, :eva.v2.database.core/id #uuid "f998PI:PASSWORD:<PASSWORD>END_PI-cPI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI-b86e-1b063536bcfPI:PASSWORD:<PASSWORD>END_PI", :eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql, :eva.v2.messaging.address/index-updates "eva.v2.index-updates.63621540-10fc-402a-b305-97f312d0f8f0.f998bc77-c090-4c3a-b86e-1b063536bcf3", :eva.v2.storage.value-store.core/partition-id #uuid "63621540-10fc-402a-b305-97f312d0f8f0", :broker-uri "tcp://activemq:61616?user=eva-transactor&password=PI:PASSWORD:<PASSWORD>END_PI&retryInterval=1PI:PASSWORD:<PASSWORD>END_PI0&retryIntervalMultiplier=2.0&maxRetryInterval=60000&reconnectAttempts=-1", :messenger-node-config/type :broker-uri}) (def test-transactor-storage (config/sql-storage {:subprotocol (env "EVA_STORAGE_SQL_DB_TYPE" "mysql") :subname (format "//%s:%s/%s" (env "EVA_STORAGE_SQL_HOST" "localhost") (env "EVA_STORAGE_SQL_PORT" 3306) (env "EVA_STORAGE_SQL_DBNAME" "eva")) :classname (env "EVA_STORAGE_SQL_DRIVER" "com.mysql.jdbc.Driver") :user (env "EVA_STORAGE_SQL_USER" "special-transactor-user") :password (env "EVA_STORAGE_SQL_PASSWORD" "PI:PASSWORD:<PASSWORD>END_PI")})) (def eva-test-2-labels #{test-db-3-config test-db-4-config}) (defn test-app [catalog] (let [app (build-routes catalog)] (testing "status route" (let [response (app (mock/request :get "/status"))] (is (= (:status response) 200)) (is (= (:body response) "All systems nominal.")))) (testing "flat-peer-config route" (let [happy-response (app (-> (mock/request :get "/flat-peer-config" {:tenant "workiva" :category "eva-test-1" :label "test-db-1"}) (mock/content-type "application/edn") (mock/header :accept "application/edn"))) sad-response (app (-> (mock/request :get "/flat-peer-config" {}) (mock/content-type "application/edn")))] (is (= (:status happy-response) 200)) (is (= (dissoc (read-string (slurp (:body happy-response))) :eva.v2.system.peer-connection.core/id) test-db-1-config)) (is (= (:status sad-response) 404)))) (testing "flat-peer-configs-for-tenant-and-category route" (let [happy-response (app (-> (mock/request :get "/flat-peer-configs-for-tenant-and-category" {:tenant "workiva" :category "eva-test-2"}) (mock/content-type "application/edn") (mock/header :accept "application/edn"))) sad-response (app (-> (mock/request :get "/flat-peer-configs-for-tenant-and-category" {:tenant "NOT-workiva" :category "eva-test-2"}) (mock/content-type "application/edn")))] (is (= (:status happy-response) 200)) (is (= (into #{} (read-string (slurp (:body happy-response)))) eva-test-2-labels)) (is (= (:status sad-response) 404)))) (testing "flat-peer-configs-for-category-and-label route" (let [happy-response (app (-> (mock/request :get "/flat-peer-configs-for-category-and-label" {:category "eva-test-2" :label "test-db-4"}) (mock/content-type "application/edn") (mock/header :accept "application/edn"))) sad-response (app (-> (mock/request :get "/flat-peer-configs-for-tenant-and-category" {:tenant "NOT-workiva" :category "eva-test-2"}) (mock/content-type "application/edn")))] (is (= (:status happy-response) 200)) (is (= (into #{} (read-string (slurp (:body happy-response)))) #{test-db-4-config})) (is (= (:status sad-response) 404)))) (testing "not-found route" (let [response (app (mock/request :get "/invalid"))] (is (= (:status response) 404)))))) (deftest test-edn-file-catalog (test-app (c/load-catalog {::c/type :edn-file :path (io/resource "eva/catalog/common/alpha/mock-catalog-data.edn")})))
[ { "context": "EDVALUE)\n <TOKEN> = #\\\"[\\\\w\\\\.\\\\-]+\\\"\n KEY = TOKEN\n VALUE = TOKEN\n TYPE = #\\\"\\\\w+\\\"\n SUBTYP", "end": 493, "score": 0.6697898507118225, "start": 488, "tag": "KEY", "value": "TOKEN" } ]
src/cayenne/api/conneg.clj
CrossRef/cayenne
11
(ns cayenne.api.conneg (:require [instaparse.core :as insta] [clojure.string :as string] [net.cgrand.enlive-html :as enlive])) ;; a simple accept header parser (def accept-header-parser (insta/parser "ACCEPT = ENTRY+ ENTRY = MEDIARANGE PARAM* <[#\"\\s*,\\s*\"]> <MEDIARANGE> = '*' <'/'> '*' | (TYPE <'/'> '*') | (TYPE <'/'> SUBTYPE) PARAM = <#\"\\s*;\\s*\"> KEY <#\"\\s*=\\s*\"> (VALUE | QUOTEDVALUE) <TOKEN> = #\"[\\w\\.\\-]+\" KEY = TOKEN VALUE = TOKEN TYPE = #\"\\w+\" SUBTYPE = #\"[\\w\\+\\.\\-]+\" QUOTEDVALUE = <'\"'> #\"[^\\\"]+\" <'\"'>" :output-format :enlive)) (def default-accept-value "*/*") (defn make-accept [accept-value] (let [t (-> accept-value string/trim accept-header-parser)] (map #(hash-map :params (reduce (fn [m pair] (assoc m (-> (enlive/select pair [:KEY enlive/text]) first keyword) (first (concat (enlive/select pair [:VALUE enlive/text]) (enlive/select pair [:QUOTEDVALUE enlive/text]))))) {} (enlive/select % [:PARAM])) :type (first (enlive/select % [:TYPE enlive/text])) :subtype (first (enlive/select % [:SUBTYPE enlive/text]))) (enlive/select t [:ENTRY])))) (defn make-sorted-accept [accept-value] (sort-by #(Float/parseFloat (get-in % [:params :q] "1.0")) > (make-accept accept-value))) ;; a ring middleware to stick accept data structure in request object (defn wrap-accept [handler] (fn [req] (let [accept-value (get-in req [:headers "accept"])] (if-not (string/blank? accept-value) (handler (assoc req :accept (make-sorted-accept accept-value))) (handler (-> req (assoc-in [:headers "accept"] default-accept-value) (assoc :accept (make-sorted-accept default-accept-value)))))))) ;; a libertor decision function that selects a most appropriate content type, ;; if any is available (defn content-type-matches [cts] (fn [ctx] (let [client-acceptable-types (get-in ctx [:request :accept]) type (first (filter #(some #{(str (:type %) "/" (:subtype %))} cts) client-acceptable-types))] (when type {:representation {:media-type (str (:type type) "/" (:subtype type)) :parameters (:params type)}}))))
87546
(ns cayenne.api.conneg (:require [instaparse.core :as insta] [clojure.string :as string] [net.cgrand.enlive-html :as enlive])) ;; a simple accept header parser (def accept-header-parser (insta/parser "ACCEPT = ENTRY+ ENTRY = MEDIARANGE PARAM* <[#\"\\s*,\\s*\"]> <MEDIARANGE> = '*' <'/'> '*' | (TYPE <'/'> '*') | (TYPE <'/'> SUBTYPE) PARAM = <#\"\\s*;\\s*\"> KEY <#\"\\s*=\\s*\"> (VALUE | QUOTEDVALUE) <TOKEN> = #\"[\\w\\.\\-]+\" KEY = <KEY> VALUE = TOKEN TYPE = #\"\\w+\" SUBTYPE = #\"[\\w\\+\\.\\-]+\" QUOTEDVALUE = <'\"'> #\"[^\\\"]+\" <'\"'>" :output-format :enlive)) (def default-accept-value "*/*") (defn make-accept [accept-value] (let [t (-> accept-value string/trim accept-header-parser)] (map #(hash-map :params (reduce (fn [m pair] (assoc m (-> (enlive/select pair [:KEY enlive/text]) first keyword) (first (concat (enlive/select pair [:VALUE enlive/text]) (enlive/select pair [:QUOTEDVALUE enlive/text]))))) {} (enlive/select % [:PARAM])) :type (first (enlive/select % [:TYPE enlive/text])) :subtype (first (enlive/select % [:SUBTYPE enlive/text]))) (enlive/select t [:ENTRY])))) (defn make-sorted-accept [accept-value] (sort-by #(Float/parseFloat (get-in % [:params :q] "1.0")) > (make-accept accept-value))) ;; a ring middleware to stick accept data structure in request object (defn wrap-accept [handler] (fn [req] (let [accept-value (get-in req [:headers "accept"])] (if-not (string/blank? accept-value) (handler (assoc req :accept (make-sorted-accept accept-value))) (handler (-> req (assoc-in [:headers "accept"] default-accept-value) (assoc :accept (make-sorted-accept default-accept-value)))))))) ;; a libertor decision function that selects a most appropriate content type, ;; if any is available (defn content-type-matches [cts] (fn [ctx] (let [client-acceptable-types (get-in ctx [:request :accept]) type (first (filter #(some #{(str (:type %) "/" (:subtype %))} cts) client-acceptable-types))] (when type {:representation {:media-type (str (:type type) "/" (:subtype type)) :parameters (:params type)}}))))
true
(ns cayenne.api.conneg (:require [instaparse.core :as insta] [clojure.string :as string] [net.cgrand.enlive-html :as enlive])) ;; a simple accept header parser (def accept-header-parser (insta/parser "ACCEPT = ENTRY+ ENTRY = MEDIARANGE PARAM* <[#\"\\s*,\\s*\"]> <MEDIARANGE> = '*' <'/'> '*' | (TYPE <'/'> '*') | (TYPE <'/'> SUBTYPE) PARAM = <#\"\\s*;\\s*\"> KEY <#\"\\s*=\\s*\"> (VALUE | QUOTEDVALUE) <TOKEN> = #\"[\\w\\.\\-]+\" KEY = PI:KEY:<KEY>END_PI VALUE = TOKEN TYPE = #\"\\w+\" SUBTYPE = #\"[\\w\\+\\.\\-]+\" QUOTEDVALUE = <'\"'> #\"[^\\\"]+\" <'\"'>" :output-format :enlive)) (def default-accept-value "*/*") (defn make-accept [accept-value] (let [t (-> accept-value string/trim accept-header-parser)] (map #(hash-map :params (reduce (fn [m pair] (assoc m (-> (enlive/select pair [:KEY enlive/text]) first keyword) (first (concat (enlive/select pair [:VALUE enlive/text]) (enlive/select pair [:QUOTEDVALUE enlive/text]))))) {} (enlive/select % [:PARAM])) :type (first (enlive/select % [:TYPE enlive/text])) :subtype (first (enlive/select % [:SUBTYPE enlive/text]))) (enlive/select t [:ENTRY])))) (defn make-sorted-accept [accept-value] (sort-by #(Float/parseFloat (get-in % [:params :q] "1.0")) > (make-accept accept-value))) ;; a ring middleware to stick accept data structure in request object (defn wrap-accept [handler] (fn [req] (let [accept-value (get-in req [:headers "accept"])] (if-not (string/blank? accept-value) (handler (assoc req :accept (make-sorted-accept accept-value))) (handler (-> req (assoc-in [:headers "accept"] default-accept-value) (assoc :accept (make-sorted-accept default-accept-value)))))))) ;; a libertor decision function that selects a most appropriate content type, ;; if any is available (defn content-type-matches [cts] (fn [ctx] (let [client-acceptable-types (get-in ctx [:request :accept]) type (first (filter #(some #{(str (:type %) "/" (:subtype %))} cts) client-acceptable-types))] (when type {:representation {:media-type (str (:type type) "/" (:subtype type)) :parameters (:params type)}}))))
[ { "context": "l://localhost/objective8?user=objective8&password=development\"))\n\n(defproject objective8 \"0.0.1-SNAPSHOT\"\n :de", "end": 145, "score": 0.999325156211853, "start": 134, "tag": "PASSWORD", "value": "development" } ]
project.clj
d-cent/objective8
23
(def database-connection-url (or (System/getenv "DB_JDBC_URL") "jdbc:postgresql://localhost/objective8?user=objective8&password=development")) (defproject objective8 "0.0.1-SNAPSHOT" :description "Cool new project to do things and stuff" :min-lein-version "2.0.0" :test-paths ["test"] :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/core.cache "0.6.4"] [http-kit "2.1.16"] [org.clojure/tools.logging "0.3.1"] [log4j/log4j "1.2.16" :exclusions [javax.mail/mail javax.jms/jms com.sun.jdmk/jmxtools com.sun.jmx/jmxri]] [bidi "1.12.0"] [ring "1.3.2"] [ring/ring-json "0.3.1"] [ring/ring-anti-forgery "1.0.0"] [ring/ring-headers "0.1.2"] [ring/ring-ssl "0.2.1"] [com.cemerick/url "0.1.1"] [org.apache.httpcomponents/httpclient "4.3.5"] [xml-apis "1.4.01"] [com.cemerick/friend "0.2.1" :exclusions [robert/hooke xml-apis]] [de.ubercode.clostache/clostache "1.4.0"] [enlive "1.1.5"] [com.taoensso/tower "3.0.2"] [clj-oauth "1.5.2"] [cheshire "5.4.0"] [clj-time "0.9.0"] [korma "0.4.1"] [org.clojure/java.jdbc "0.3.6"] [postgresql "9.3-1102.jdbc41"] [ragtime "0.3.8"] [endophile "0.1.2"] [org.pegdown/pegdown "1.2.0"] [clojure-csv/clojure-csv "2.0.1"] [hickory "0.5.4"] [diff-match-patch-clj "1.0.0-SNAPSHOT"] [crypto-random "1.2.0"] [org.clojars.d-cent/stonecutter-oauth "0.2.0-SNAPSHOT"] [com.googlecode.owasp-java-html-sanitizer/owasp-java-html-sanitizer "r239" :exclusions [com.google.guava/guava com.google.code.findbugs/jsr305]]] :main objective8.core :plugins [[ragtime/ragtime.lein "0.3.8"] [lein-cloverage "1.0.6"]] :profiles {:dev {:source-paths ["dev"] :repl-options {:init-ns user :timeout 120000} :dependencies [[midje "1.7.0"] [ring/ring-mock "0.2.0"] [clj-webdriver "0.7.2" :exclusions [org.seleniumhq.selenium/selenium-java org.seleniumhq.selenium/selenium-server org.seleniumhq.selenium/selenium-remote-driver xml-apis]] [org.seleniumhq.selenium/selenium-server "2.45.0"] [org.seleniumhq.selenium/selenium-java "2.45.0"] [org.seleniumhq.selenium/selenium-remote-driver "2.45.0"] [org.clojure/algo.generic "0.1.2"] [javax.servlet/servlet-api "2.5"] [peridot "0.3.1"] [robert/hooke "1.3.0"]] :plugins [[lein-midje "3.1.3"] [jonase/eastwood "0.2.1"] [lein-shell "0.4.1"]] :ragtime {:migrations ragtime.sql.files/migrations :database ~database-connection-url} :aliases {"translation-template" ["run" "-m" "dev-helpers.translation/main"] "unit" ["do" "grunt," "midje" "objective8.unit.*"] "integration" ["do" "grunt," "midje" "objective8.integration.*"] "browser" ["do" "grunt," "shell" "test/run_browser_tests.sh"] "test" ["do" "grunt," "shell" "test/run_all_tests.sh"] "auto-no-browser" ["test" ":autotest" "src/" "test/objective8/unit/" "test/objective8/integration/"] "grunt" ["shell" "grunt" "build"] "start" ["shell" "./start_app_vm.sh"]} :jvm-opts ["-Dlog4j.configuration=log4j.dev"]} :load-testing {:source-paths ["load_testing"] :repl-options [:init-ns load-tests] :dependencies [[clj-gatling "0.5.4"] [org.clojure/tools.nrepl "0.2.10"]] :main load-tests} :uberjar {:source-paths ["prod"] :jvm-opts ["-Dlog4j.configuration=log4j.dev"] :ragtime {:migrations ragtime.sql.files/migrations :database ~database-connection-url} :main main :aot [main]} :heroku {:repl-options {:init-ns user :timeout 120000} :ragtime {:migrations ragtime.sql.files/migrations :database ~database-connection-url} :jvm-opts ["-Dlog4j.configuration=log4j.heroku"]}})
91771
(def database-connection-url (or (System/getenv "DB_JDBC_URL") "jdbc:postgresql://localhost/objective8?user=objective8&password=<PASSWORD>")) (defproject objective8 "0.0.1-SNAPSHOT" :description "Cool new project to do things and stuff" :min-lein-version "2.0.0" :test-paths ["test"] :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/core.cache "0.6.4"] [http-kit "2.1.16"] [org.clojure/tools.logging "0.3.1"] [log4j/log4j "1.2.16" :exclusions [javax.mail/mail javax.jms/jms com.sun.jdmk/jmxtools com.sun.jmx/jmxri]] [bidi "1.12.0"] [ring "1.3.2"] [ring/ring-json "0.3.1"] [ring/ring-anti-forgery "1.0.0"] [ring/ring-headers "0.1.2"] [ring/ring-ssl "0.2.1"] [com.cemerick/url "0.1.1"] [org.apache.httpcomponents/httpclient "4.3.5"] [xml-apis "1.4.01"] [com.cemerick/friend "0.2.1" :exclusions [robert/hooke xml-apis]] [de.ubercode.clostache/clostache "1.4.0"] [enlive "1.1.5"] [com.taoensso/tower "3.0.2"] [clj-oauth "1.5.2"] [cheshire "5.4.0"] [clj-time "0.9.0"] [korma "0.4.1"] [org.clojure/java.jdbc "0.3.6"] [postgresql "9.3-1102.jdbc41"] [ragtime "0.3.8"] [endophile "0.1.2"] [org.pegdown/pegdown "1.2.0"] [clojure-csv/clojure-csv "2.0.1"] [hickory "0.5.4"] [diff-match-patch-clj "1.0.0-SNAPSHOT"] [crypto-random "1.2.0"] [org.clojars.d-cent/stonecutter-oauth "0.2.0-SNAPSHOT"] [com.googlecode.owasp-java-html-sanitizer/owasp-java-html-sanitizer "r239" :exclusions [com.google.guava/guava com.google.code.findbugs/jsr305]]] :main objective8.core :plugins [[ragtime/ragtime.lein "0.3.8"] [lein-cloverage "1.0.6"]] :profiles {:dev {:source-paths ["dev"] :repl-options {:init-ns user :timeout 120000} :dependencies [[midje "1.7.0"] [ring/ring-mock "0.2.0"] [clj-webdriver "0.7.2" :exclusions [org.seleniumhq.selenium/selenium-java org.seleniumhq.selenium/selenium-server org.seleniumhq.selenium/selenium-remote-driver xml-apis]] [org.seleniumhq.selenium/selenium-server "2.45.0"] [org.seleniumhq.selenium/selenium-java "2.45.0"] [org.seleniumhq.selenium/selenium-remote-driver "2.45.0"] [org.clojure/algo.generic "0.1.2"] [javax.servlet/servlet-api "2.5"] [peridot "0.3.1"] [robert/hooke "1.3.0"]] :plugins [[lein-midje "3.1.3"] [jonase/eastwood "0.2.1"] [lein-shell "0.4.1"]] :ragtime {:migrations ragtime.sql.files/migrations :database ~database-connection-url} :aliases {"translation-template" ["run" "-m" "dev-helpers.translation/main"] "unit" ["do" "grunt," "midje" "objective8.unit.*"] "integration" ["do" "grunt," "midje" "objective8.integration.*"] "browser" ["do" "grunt," "shell" "test/run_browser_tests.sh"] "test" ["do" "grunt," "shell" "test/run_all_tests.sh"] "auto-no-browser" ["test" ":autotest" "src/" "test/objective8/unit/" "test/objective8/integration/"] "grunt" ["shell" "grunt" "build"] "start" ["shell" "./start_app_vm.sh"]} :jvm-opts ["-Dlog4j.configuration=log4j.dev"]} :load-testing {:source-paths ["load_testing"] :repl-options [:init-ns load-tests] :dependencies [[clj-gatling "0.5.4"] [org.clojure/tools.nrepl "0.2.10"]] :main load-tests} :uberjar {:source-paths ["prod"] :jvm-opts ["-Dlog4j.configuration=log4j.dev"] :ragtime {:migrations ragtime.sql.files/migrations :database ~database-connection-url} :main main :aot [main]} :heroku {:repl-options {:init-ns user :timeout 120000} :ragtime {:migrations ragtime.sql.files/migrations :database ~database-connection-url} :jvm-opts ["-Dlog4j.configuration=log4j.heroku"]}})
true
(def database-connection-url (or (System/getenv "DB_JDBC_URL") "jdbc:postgresql://localhost/objective8?user=objective8&password=PI:PASSWORD:<PASSWORD>END_PI")) (defproject objective8 "0.0.1-SNAPSHOT" :description "Cool new project to do things and stuff" :min-lein-version "2.0.0" :test-paths ["test"] :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/core.cache "0.6.4"] [http-kit "2.1.16"] [org.clojure/tools.logging "0.3.1"] [log4j/log4j "1.2.16" :exclusions [javax.mail/mail javax.jms/jms com.sun.jdmk/jmxtools com.sun.jmx/jmxri]] [bidi "1.12.0"] [ring "1.3.2"] [ring/ring-json "0.3.1"] [ring/ring-anti-forgery "1.0.0"] [ring/ring-headers "0.1.2"] [ring/ring-ssl "0.2.1"] [com.cemerick/url "0.1.1"] [org.apache.httpcomponents/httpclient "4.3.5"] [xml-apis "1.4.01"] [com.cemerick/friend "0.2.1" :exclusions [robert/hooke xml-apis]] [de.ubercode.clostache/clostache "1.4.0"] [enlive "1.1.5"] [com.taoensso/tower "3.0.2"] [clj-oauth "1.5.2"] [cheshire "5.4.0"] [clj-time "0.9.0"] [korma "0.4.1"] [org.clojure/java.jdbc "0.3.6"] [postgresql "9.3-1102.jdbc41"] [ragtime "0.3.8"] [endophile "0.1.2"] [org.pegdown/pegdown "1.2.0"] [clojure-csv/clojure-csv "2.0.1"] [hickory "0.5.4"] [diff-match-patch-clj "1.0.0-SNAPSHOT"] [crypto-random "1.2.0"] [org.clojars.d-cent/stonecutter-oauth "0.2.0-SNAPSHOT"] [com.googlecode.owasp-java-html-sanitizer/owasp-java-html-sanitizer "r239" :exclusions [com.google.guava/guava com.google.code.findbugs/jsr305]]] :main objective8.core :plugins [[ragtime/ragtime.lein "0.3.8"] [lein-cloverage "1.0.6"]] :profiles {:dev {:source-paths ["dev"] :repl-options {:init-ns user :timeout 120000} :dependencies [[midje "1.7.0"] [ring/ring-mock "0.2.0"] [clj-webdriver "0.7.2" :exclusions [org.seleniumhq.selenium/selenium-java org.seleniumhq.selenium/selenium-server org.seleniumhq.selenium/selenium-remote-driver xml-apis]] [org.seleniumhq.selenium/selenium-server "2.45.0"] [org.seleniumhq.selenium/selenium-java "2.45.0"] [org.seleniumhq.selenium/selenium-remote-driver "2.45.0"] [org.clojure/algo.generic "0.1.2"] [javax.servlet/servlet-api "2.5"] [peridot "0.3.1"] [robert/hooke "1.3.0"]] :plugins [[lein-midje "3.1.3"] [jonase/eastwood "0.2.1"] [lein-shell "0.4.1"]] :ragtime {:migrations ragtime.sql.files/migrations :database ~database-connection-url} :aliases {"translation-template" ["run" "-m" "dev-helpers.translation/main"] "unit" ["do" "grunt," "midje" "objective8.unit.*"] "integration" ["do" "grunt," "midje" "objective8.integration.*"] "browser" ["do" "grunt," "shell" "test/run_browser_tests.sh"] "test" ["do" "grunt," "shell" "test/run_all_tests.sh"] "auto-no-browser" ["test" ":autotest" "src/" "test/objective8/unit/" "test/objective8/integration/"] "grunt" ["shell" "grunt" "build"] "start" ["shell" "./start_app_vm.sh"]} :jvm-opts ["-Dlog4j.configuration=log4j.dev"]} :load-testing {:source-paths ["load_testing"] :repl-options [:init-ns load-tests] :dependencies [[clj-gatling "0.5.4"] [org.clojure/tools.nrepl "0.2.10"]] :main load-tests} :uberjar {:source-paths ["prod"] :jvm-opts ["-Dlog4j.configuration=log4j.dev"] :ragtime {:migrations ragtime.sql.files/migrations :database ~database-connection-url} :main main :aot [main]} :heroku {:repl-options {:init-ns user :timeout 120000} :ragtime {:migrations ragtime.sql.files/migrations :database ~database-connection-url} :jvm-opts ["-Dlog4j.configuration=log4j.heroku"]}})
[ { "context": "e another Dockerfile.\"\n :url \"https://github.com/into-docker/into-docker\"\n :license {:name \"MIT\"\n ", "end": 121, "score": 0.9939672946929932, "start": 110, "tag": "USERNAME", "value": "into-docker" }, { "context": "ses/mit\"\n :year 2020\n :key \"mit\"\n :comment \"MIT License\"}\n :dependenc", "end": 262, "score": 0.7139384150505066, "start": 259, "tag": "KEY", "value": "mit" }, { "context": ".check \"1.1.0\"]\n [com.gfredericks/test.chuck \"0.2.10\"]]\n :global-vars ", "end": 1332, "score": 0.9690830707550049, "start": 1321, "tag": "USERNAME", "value": "gfredericks" } ]
project.clj
into-docker/into-docker
83
(defproject into "1.1.3-SNAPSHOT" :description "Never write another Dockerfile." :url "https://github.com/into-docker/into-docker" :license {:name "MIT" :url "https://choosealicense.com/licenses/mit" :year 2020 :key "mit" :comment "MIT License"} :dependencies [[org.clojure/clojure "1.10.3"] [org.clojure/tools.cli "1.0.206"] [org.clojure/tools.logging "1.1.0"] ;; components [lispyclouds/clj-docker-client "1.0.3"] [unixsocket-http "1.0.10"] [com.squareup.okhttp3/okhttp "4.9.1"] [com.squareup.okhttp3/okhttp-tls "4.9.1"] ;; utilities [org.apache.commons/commons-compress "1.20"] [commons-lang "2.6"] [potemkin "0.4.5"] ;; logging [jansi-clj "0.1.1"] [ch.qos.logback/logback-classic "1.2.3"] ;; cleanup dependency chain [riddley "0.2.0"] [org.jetbrains.kotlin/kotlin-stdlib-common "1.4.32"]] :exclusions [org.clojure/clojure] :java-source-paths ["src"] :profiles {:dev {:dependencies [[org.clojure/test.check "1.1.0"] [com.gfredericks/test.chuck "0.2.10"]] :global-vars {*warn-on-reflection* true}} :kaocha {:dependencies [[lambdaisland/kaocha "1.0.829" :exclusions [org.clojure/spec.alpha]] [lambdaisland/kaocha-cloverage "1.0.75"] [org.clojure/java.classpath "1.0.0"]]} :uberjar {:global-vars {*assert* false} :jvm-opts ["-Dclojure.compiler.direct-linking=true" "-Dclojure.spec.skip-macros=true"] :main into.main :aot :all}} :cljfmt {:indents {prop/for-all [[:block 1]] defcomponent [[:block 2] [:inner 1]]}} :aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"]} :pedantic? :abort)
45611
(defproject into "1.1.3-SNAPSHOT" :description "Never write another Dockerfile." :url "https://github.com/into-docker/into-docker" :license {:name "MIT" :url "https://choosealicense.com/licenses/mit" :year 2020 :key "<KEY>" :comment "MIT License"} :dependencies [[org.clojure/clojure "1.10.3"] [org.clojure/tools.cli "1.0.206"] [org.clojure/tools.logging "1.1.0"] ;; components [lispyclouds/clj-docker-client "1.0.3"] [unixsocket-http "1.0.10"] [com.squareup.okhttp3/okhttp "4.9.1"] [com.squareup.okhttp3/okhttp-tls "4.9.1"] ;; utilities [org.apache.commons/commons-compress "1.20"] [commons-lang "2.6"] [potemkin "0.4.5"] ;; logging [jansi-clj "0.1.1"] [ch.qos.logback/logback-classic "1.2.3"] ;; cleanup dependency chain [riddley "0.2.0"] [org.jetbrains.kotlin/kotlin-stdlib-common "1.4.32"]] :exclusions [org.clojure/clojure] :java-source-paths ["src"] :profiles {:dev {:dependencies [[org.clojure/test.check "1.1.0"] [com.gfredericks/test.chuck "0.2.10"]] :global-vars {*warn-on-reflection* true}} :kaocha {:dependencies [[lambdaisland/kaocha "1.0.829" :exclusions [org.clojure/spec.alpha]] [lambdaisland/kaocha-cloverage "1.0.75"] [org.clojure/java.classpath "1.0.0"]]} :uberjar {:global-vars {*assert* false} :jvm-opts ["-Dclojure.compiler.direct-linking=true" "-Dclojure.spec.skip-macros=true"] :main into.main :aot :all}} :cljfmt {:indents {prop/for-all [[:block 1]] defcomponent [[:block 2] [:inner 1]]}} :aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"]} :pedantic? :abort)
true
(defproject into "1.1.3-SNAPSHOT" :description "Never write another Dockerfile." :url "https://github.com/into-docker/into-docker" :license {:name "MIT" :url "https://choosealicense.com/licenses/mit" :year 2020 :key "PI:KEY:<KEY>END_PI" :comment "MIT License"} :dependencies [[org.clojure/clojure "1.10.3"] [org.clojure/tools.cli "1.0.206"] [org.clojure/tools.logging "1.1.0"] ;; components [lispyclouds/clj-docker-client "1.0.3"] [unixsocket-http "1.0.10"] [com.squareup.okhttp3/okhttp "4.9.1"] [com.squareup.okhttp3/okhttp-tls "4.9.1"] ;; utilities [org.apache.commons/commons-compress "1.20"] [commons-lang "2.6"] [potemkin "0.4.5"] ;; logging [jansi-clj "0.1.1"] [ch.qos.logback/logback-classic "1.2.3"] ;; cleanup dependency chain [riddley "0.2.0"] [org.jetbrains.kotlin/kotlin-stdlib-common "1.4.32"]] :exclusions [org.clojure/clojure] :java-source-paths ["src"] :profiles {:dev {:dependencies [[org.clojure/test.check "1.1.0"] [com.gfredericks/test.chuck "0.2.10"]] :global-vars {*warn-on-reflection* true}} :kaocha {:dependencies [[lambdaisland/kaocha "1.0.829" :exclusions [org.clojure/spec.alpha]] [lambdaisland/kaocha-cloverage "1.0.75"] [org.clojure/java.classpath "1.0.0"]]} :uberjar {:global-vars {*assert* false} :jvm-opts ["-Dclojure.compiler.direct-linking=true" "-Dclojure.spec.skip-macros=true"] :main into.main :aot :all}} :cljfmt {:indents {prop/for-all [[:block 1]] defcomponent [[:block 2] [:inner 1]]}} :aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"]} :pedantic? :abort)
[ { "context": "the publisher of recipe\n(def user (u/->User 2345 \"joesimpson\" \"Joe\"\n \"Simpson\" \"+9199704562", "end": 2214, "score": 0.9993590712547302, "start": 2204, "tag": "USERNAME", "value": "joesimpson" }, { "context": " of recipe\n(def user (u/->User 2345 \"joesimpson\" \"Joe\"\n \"Simpson\" \"+919970456243\" \"j", "end": 2220, "score": 0.9987246990203857, "start": 2217, "tag": "NAME", "value": "Joe" }, { "context": "User 2345 \"joesimpson\" \"Joe\"\n \"Simpson\" \"+919970456243\" \"jsms345@treemail.com\"\n ", "end": 2250, "score": 0.9993048906326294, "start": 2243, "tag": "NAME", "value": "Simpson" }, { "context": "e\"\n \"Simpson\" \"+919970456243\" \"jsms345@treemail.com\"\n \"23/11/1985\" \"11/02/2014\"))\n", "end": 2289, "score": 0.9999275207519531, "start": 2269, "tag": "EMAIL", "value": "jsms345@treemail.com" } ]
src/com/mshiray/recipebcp/spec_test.clj
mshiray/recipebcp
0
(ns com.mshiray.recipebcp.spec_test (:require [clojure.spec.alpha :as s] ;;Note: [org.clojure/test.check "0.9.0"] need to be added to ;;project.clj dependencies for spec.gen.alpha [clojure.spec.gen.alpha :as gen] [clojure.repl :as crpl] ;;This is needed so that all required dependencies are loaded at boot time. ;;require all needed spec modules with respective prefixes. ;;Leaf spec ns name need to match with that of the respective file name. [com.mshiray.recipebcp.spec [recipe_specs :as rs] [ingredient_specs :as is] [user_specs :as us]] ;;require all needed user type namespace modules ;; (defrecords, deftypes, interfaces etc.) [com.mshiray.recipebcp.domain.type [user :as u] [recipe :as r] [ingredient :as i]]);;require end );;ns end ;; ###### Lets do some Simple type validation with spec ########## ;;simple data type validations based on defined regexs & type constraints (s/valid? ::rs/r_estTime "02:23") ;; => true ;;validation against defined coll of keywords (s/valid? ::rs/r_diet ::rs/Keto) ;; => true ;;validate & explain any validation errors.. ;;this spec validates against the locale regex pattern defined in common_specs.clj (s/explain ::us/u_langPref "zh_CN") ;; => nil (s/valid? ::us/u_langPref "en_US") ;;generate sample data from spec defs (gen/generate (s/gen pos-int?)) ;; => 54 ;; => 52589684 (gen/generate (s/gen ::rs/r_cuisine)) ;; => :com.mshiray.recipebcp.domain.type.recipe/African ;;generate sample test data for specified spec def ;;(gen/sample (s/gen ::rs/r_diet 3)) ;; => (:com.mshiray.recipebcp.domain.type.recipe/Vegiterian ;; :com.mshiray.recipebcp.domain.type.recipe/Vegan ;; ....) ;;prints documentation of the specified spec (crpl/doc ::is/Ingredient) ;;check if specified keyword belongs to the sequence. (def tests #{:a :b :c}) (some tests #{:b}) ;; => :b ;;validate inline sequence key-val pair data (s/valid? ::is/Ingredient {:in_name "toast" :in_category ::i/bakery}) ;; => true ;####### Define required record type instances for our recipe spec validations ########### ;;define instance of user defrecord as the publisher of recipe (def user (u/->User 2345 "joesimpson" "Joe" "Simpson" "+919970456243" "jsms345@treemail.com" "23/11/1985" "11/02/2014")) ;;create new user record by adding optional lang pref property ;;to existing user record (def user_with_lang_pref (assoc user ::us/u_langPref "en_US")) (-> user_with_lang_pref ::us/u_langPref) ;; => "en_US" ;;validate user against user spec (s/valid? ::us/User user_with_lang_pref) ;; => true (def flour (i/->Ingredient "Wheat flour" ::i/bakery)) ;;Note: 'Ingredient.' when record type is imported (s/valid? ::is/Ingredient flour) ;; => true (s/valid? ::is/Ingredient {::is/in_name (-> flour :in_name) ::is/in_category (-> flour :in_category)}) ;; => true ;;get keys of defrecord type (keys flour) ;; => (:in_name :in_category) ;;return no. of keys defined in defrecord (count flour) ;; => 2 ;;access defrecord instance named properties (-> flour :in_name) ;; => "Wheat flour" (-> flour :in_category) ;; => :com.mshiray.recipebcp.domain.type.ingredient/bakery ;;validate defrecord instancd against defined Ingredient spec.. (s/valid? ::is/Ingredient flour) ;; => true ;;create ingredient data from hash map instead of defreocrd type (def eggs (hash-map :in_name "eggs" :in_category ::i/poultry)) ;;vlaidate created hashmap data against the defined Ingredient spec... (s/valid? ::is/Ingredient eggs) ;; => true ;;append optional properties key-vals to existing entity map (def eggs_with_specs (assoc eggs ;;IngredientFormFactor props :in_form ::i/whole :in_process_type ::i/fresh :in_form_details ::i/large :in_special_instrns ::i/organic :alergy_warning false :in_description "organic farm fresh chicken eggs")) ;;access properties of compbined eggs entity map (-> eggs_with_specs :in_name) ;; => "eggs" ;; => "eggs" (eggs_with_specs :in_description) ;; => "organic farm fresh chicken eggs" ;;validate appended entity map against the Ingredient specs (s/valid? ::is/Ingredient eggs_with_specs) ;; => true ;;lets fetch two eggs for our omlette recipe prep (def eggs_qty (i/->In_Measure 2 ::i/no)) ;;append measures record isntance to flour ingredient for our bread recipe (def two_eggs (assoc eggs_with_specs ::in_measure eggs_qty ::in_measure_type ::i/Exact ::in_decription "dont carry all of them in one basket!")) (s/valid? ::is/Ingredient two_eggs) ;; => true ;;TODO ;;ref: https://clojuredocs.org/clojure.core/defrecord ;; This is particularly useful for mapping parsed CSV files to records ;;(map #(apply t/Ingredient %) parsed-csv-file) ;;lets add flour ingredient measures required for our recipes (def flour_msr_qty (i/->In_Measure 2 ::i/C)) ;;append measures record isntance to flour ingredient for our bread recipe (def two_cup_flour (assoc flour ::in_measure flour_msr_qty ::in_measure_type ::i/Lightly_Packed ::in_decription "whole wheat flour one cup")) (s/valid? ::is/Ingredient two_cup_flour) ;; => true ;lets see internal data structure of the created flour ingredient (-> two_cup_flour) ;; => {:in_name "Wheat flour", ;; :in_category ;; :com.mshiray.recipebcp.domain.type.ingredient/bakery, ;; :com.mshiray.recipebcp.spec_test/in_measure ;; {:in_measure_no 2, ;; :in_measure_units ;; :com.mshiray.recipebcp.domain.type.ingredient/C}, ;; :com.mshiray.recipebcp.spec_test/in_measure_type ;; :com.mshiray.recipebcp.domain.type.ingredient/Lightly_Packed, ;; :com.mshiray.recipebcp.spec_test/in_decription ;; "whole wheat flour one cup"} ;;access nested cup measures quantity amount & units for flour ingredient (-> two_cup_flour ::in_measure :in_measure_no) ;; => 2 (-> two_cup_flour ::in_measure :in_measure_units) ;; => :com.mshiray.recipebcp.domain.type.ingredient/C ;;create new ingredient record instance for salt (def salt (i/->Ingredient "salt" ::i/additive)) ;;append measures properties to salt ingredient ;;lets add flour ingredient measures required for our recipes (def salt_msr_qty (i/->In_Measure 0.25 ::i/tsp)) ;;append measures record isntance to flour ingredient for our bread recipe (def qtr_tsp_salt (assoc salt ::in_measure salt_msr_qty ::in_measure_type ::Lightly_Packed ::in_decription "quarter tea spoon of sea salt")) ;;access nested recipe composite properties (-> qtr_tsp_salt ::in_measure :in_measure_no) ;; => 0.25 (-> qtr_tsp_salt ::in_measure :in_measure_units) ;; => :com.mshiray.recipebcp.domain.type.ingredient/tsp (s/valid? ::is/Ingredient qtr_tsp_salt) ;; => true ;;lets create distinct set of ingredients for our bread (def bread_ingredients #{two_cup_flour qtr_tsp_salt}) (s/valid? ::rs/r_ingredients bread_ingredients) ;; => true ;;create bread recipe record instance (def bread_recipe (r/->Recipe 135 "bread" user_with_lang_pref "brown bread" "01:00" 4 ::r/Vegiterian ::r/Western ::r/Bakery ::r/Other ::r/T3 bread_ingredients)) ;;print spec documentation on console (crpl/doc ::rs/Recipe) ;;explain msg to debug any validation errors (s/explain ::rs/Recipe bread_recipe) ;;validate our bread recipe for any data mismatch (s/valid? ::rs/Recipe bread_recipe) ;; => true ;;define recipe defrecord with optional companion recipe added. (def omlette_recipe (r/->Recipe 134 "omlette" user_with_lang_pref "masala omlette" "00:20" 1 ::r/NonVeg ::r/Indian ::r/Breakfast ::r/Spicy ::r/T4 #{two_eggs qtr_tsp_salt})) (s/valid? ::rs/Recipe omlette_recipe) ;; => true ;;append optional companion recipe property to existing recipe defrecord to recommend having a bread with our omlette (def bread_omlette (assoc omlette_recipe ::rs/companions [bread_recipe])) ;;validate final recipe defrecord instance with companion recipe added to it (s/valid? ::rs/Recipe bread_omlette) ;; => true
80029
(ns com.mshiray.recipebcp.spec_test (:require [clojure.spec.alpha :as s] ;;Note: [org.clojure/test.check "0.9.0"] need to be added to ;;project.clj dependencies for spec.gen.alpha [clojure.spec.gen.alpha :as gen] [clojure.repl :as crpl] ;;This is needed so that all required dependencies are loaded at boot time. ;;require all needed spec modules with respective prefixes. ;;Leaf spec ns name need to match with that of the respective file name. [com.mshiray.recipebcp.spec [recipe_specs :as rs] [ingredient_specs :as is] [user_specs :as us]] ;;require all needed user type namespace modules ;; (defrecords, deftypes, interfaces etc.) [com.mshiray.recipebcp.domain.type [user :as u] [recipe :as r] [ingredient :as i]]);;require end );;ns end ;; ###### Lets do some Simple type validation with spec ########## ;;simple data type validations based on defined regexs & type constraints (s/valid? ::rs/r_estTime "02:23") ;; => true ;;validation against defined coll of keywords (s/valid? ::rs/r_diet ::rs/Keto) ;; => true ;;validate & explain any validation errors.. ;;this spec validates against the locale regex pattern defined in common_specs.clj (s/explain ::us/u_langPref "zh_CN") ;; => nil (s/valid? ::us/u_langPref "en_US") ;;generate sample data from spec defs (gen/generate (s/gen pos-int?)) ;; => 54 ;; => 52589684 (gen/generate (s/gen ::rs/r_cuisine)) ;; => :com.mshiray.recipebcp.domain.type.recipe/African ;;generate sample test data for specified spec def ;;(gen/sample (s/gen ::rs/r_diet 3)) ;; => (:com.mshiray.recipebcp.domain.type.recipe/Vegiterian ;; :com.mshiray.recipebcp.domain.type.recipe/Vegan ;; ....) ;;prints documentation of the specified spec (crpl/doc ::is/Ingredient) ;;check if specified keyword belongs to the sequence. (def tests #{:a :b :c}) (some tests #{:b}) ;; => :b ;;validate inline sequence key-val pair data (s/valid? ::is/Ingredient {:in_name "toast" :in_category ::i/bakery}) ;; => true ;####### Define required record type instances for our recipe spec validations ########### ;;define instance of user defrecord as the publisher of recipe (def user (u/->User 2345 "joesimpson" "<NAME>" "<NAME>" "+919970456243" "<EMAIL>" "23/11/1985" "11/02/2014")) ;;create new user record by adding optional lang pref property ;;to existing user record (def user_with_lang_pref (assoc user ::us/u_langPref "en_US")) (-> user_with_lang_pref ::us/u_langPref) ;; => "en_US" ;;validate user against user spec (s/valid? ::us/User user_with_lang_pref) ;; => true (def flour (i/->Ingredient "Wheat flour" ::i/bakery)) ;;Note: 'Ingredient.' when record type is imported (s/valid? ::is/Ingredient flour) ;; => true (s/valid? ::is/Ingredient {::is/in_name (-> flour :in_name) ::is/in_category (-> flour :in_category)}) ;; => true ;;get keys of defrecord type (keys flour) ;; => (:in_name :in_category) ;;return no. of keys defined in defrecord (count flour) ;; => 2 ;;access defrecord instance named properties (-> flour :in_name) ;; => "Wheat flour" (-> flour :in_category) ;; => :com.mshiray.recipebcp.domain.type.ingredient/bakery ;;validate defrecord instancd against defined Ingredient spec.. (s/valid? ::is/Ingredient flour) ;; => true ;;create ingredient data from hash map instead of defreocrd type (def eggs (hash-map :in_name "eggs" :in_category ::i/poultry)) ;;vlaidate created hashmap data against the defined Ingredient spec... (s/valid? ::is/Ingredient eggs) ;; => true ;;append optional properties key-vals to existing entity map (def eggs_with_specs (assoc eggs ;;IngredientFormFactor props :in_form ::i/whole :in_process_type ::i/fresh :in_form_details ::i/large :in_special_instrns ::i/organic :alergy_warning false :in_description "organic farm fresh chicken eggs")) ;;access properties of compbined eggs entity map (-> eggs_with_specs :in_name) ;; => "eggs" ;; => "eggs" (eggs_with_specs :in_description) ;; => "organic farm fresh chicken eggs" ;;validate appended entity map against the Ingredient specs (s/valid? ::is/Ingredient eggs_with_specs) ;; => true ;;lets fetch two eggs for our omlette recipe prep (def eggs_qty (i/->In_Measure 2 ::i/no)) ;;append measures record isntance to flour ingredient for our bread recipe (def two_eggs (assoc eggs_with_specs ::in_measure eggs_qty ::in_measure_type ::i/Exact ::in_decription "dont carry all of them in one basket!")) (s/valid? ::is/Ingredient two_eggs) ;; => true ;;TODO ;;ref: https://clojuredocs.org/clojure.core/defrecord ;; This is particularly useful for mapping parsed CSV files to records ;;(map #(apply t/Ingredient %) parsed-csv-file) ;;lets add flour ingredient measures required for our recipes (def flour_msr_qty (i/->In_Measure 2 ::i/C)) ;;append measures record isntance to flour ingredient for our bread recipe (def two_cup_flour (assoc flour ::in_measure flour_msr_qty ::in_measure_type ::i/Lightly_Packed ::in_decription "whole wheat flour one cup")) (s/valid? ::is/Ingredient two_cup_flour) ;; => true ;lets see internal data structure of the created flour ingredient (-> two_cup_flour) ;; => {:in_name "Wheat flour", ;; :in_category ;; :com.mshiray.recipebcp.domain.type.ingredient/bakery, ;; :com.mshiray.recipebcp.spec_test/in_measure ;; {:in_measure_no 2, ;; :in_measure_units ;; :com.mshiray.recipebcp.domain.type.ingredient/C}, ;; :com.mshiray.recipebcp.spec_test/in_measure_type ;; :com.mshiray.recipebcp.domain.type.ingredient/Lightly_Packed, ;; :com.mshiray.recipebcp.spec_test/in_decription ;; "whole wheat flour one cup"} ;;access nested cup measures quantity amount & units for flour ingredient (-> two_cup_flour ::in_measure :in_measure_no) ;; => 2 (-> two_cup_flour ::in_measure :in_measure_units) ;; => :com.mshiray.recipebcp.domain.type.ingredient/C ;;create new ingredient record instance for salt (def salt (i/->Ingredient "salt" ::i/additive)) ;;append measures properties to salt ingredient ;;lets add flour ingredient measures required for our recipes (def salt_msr_qty (i/->In_Measure 0.25 ::i/tsp)) ;;append measures record isntance to flour ingredient for our bread recipe (def qtr_tsp_salt (assoc salt ::in_measure salt_msr_qty ::in_measure_type ::Lightly_Packed ::in_decription "quarter tea spoon of sea salt")) ;;access nested recipe composite properties (-> qtr_tsp_salt ::in_measure :in_measure_no) ;; => 0.25 (-> qtr_tsp_salt ::in_measure :in_measure_units) ;; => :com.mshiray.recipebcp.domain.type.ingredient/tsp (s/valid? ::is/Ingredient qtr_tsp_salt) ;; => true ;;lets create distinct set of ingredients for our bread (def bread_ingredients #{two_cup_flour qtr_tsp_salt}) (s/valid? ::rs/r_ingredients bread_ingredients) ;; => true ;;create bread recipe record instance (def bread_recipe (r/->Recipe 135 "bread" user_with_lang_pref "brown bread" "01:00" 4 ::r/Vegiterian ::r/Western ::r/Bakery ::r/Other ::r/T3 bread_ingredients)) ;;print spec documentation on console (crpl/doc ::rs/Recipe) ;;explain msg to debug any validation errors (s/explain ::rs/Recipe bread_recipe) ;;validate our bread recipe for any data mismatch (s/valid? ::rs/Recipe bread_recipe) ;; => true ;;define recipe defrecord with optional companion recipe added. (def omlette_recipe (r/->Recipe 134 "omlette" user_with_lang_pref "masala omlette" "00:20" 1 ::r/NonVeg ::r/Indian ::r/Breakfast ::r/Spicy ::r/T4 #{two_eggs qtr_tsp_salt})) (s/valid? ::rs/Recipe omlette_recipe) ;; => true ;;append optional companion recipe property to existing recipe defrecord to recommend having a bread with our omlette (def bread_omlette (assoc omlette_recipe ::rs/companions [bread_recipe])) ;;validate final recipe defrecord instance with companion recipe added to it (s/valid? ::rs/Recipe bread_omlette) ;; => true
true
(ns com.mshiray.recipebcp.spec_test (:require [clojure.spec.alpha :as s] ;;Note: [org.clojure/test.check "0.9.0"] need to be added to ;;project.clj dependencies for spec.gen.alpha [clojure.spec.gen.alpha :as gen] [clojure.repl :as crpl] ;;This is needed so that all required dependencies are loaded at boot time. ;;require all needed spec modules with respective prefixes. ;;Leaf spec ns name need to match with that of the respective file name. [com.mshiray.recipebcp.spec [recipe_specs :as rs] [ingredient_specs :as is] [user_specs :as us]] ;;require all needed user type namespace modules ;; (defrecords, deftypes, interfaces etc.) [com.mshiray.recipebcp.domain.type [user :as u] [recipe :as r] [ingredient :as i]]);;require end );;ns end ;; ###### Lets do some Simple type validation with spec ########## ;;simple data type validations based on defined regexs & type constraints (s/valid? ::rs/r_estTime "02:23") ;; => true ;;validation against defined coll of keywords (s/valid? ::rs/r_diet ::rs/Keto) ;; => true ;;validate & explain any validation errors.. ;;this spec validates against the locale regex pattern defined in common_specs.clj (s/explain ::us/u_langPref "zh_CN") ;; => nil (s/valid? ::us/u_langPref "en_US") ;;generate sample data from spec defs (gen/generate (s/gen pos-int?)) ;; => 54 ;; => 52589684 (gen/generate (s/gen ::rs/r_cuisine)) ;; => :com.mshiray.recipebcp.domain.type.recipe/African ;;generate sample test data for specified spec def ;;(gen/sample (s/gen ::rs/r_diet 3)) ;; => (:com.mshiray.recipebcp.domain.type.recipe/Vegiterian ;; :com.mshiray.recipebcp.domain.type.recipe/Vegan ;; ....) ;;prints documentation of the specified spec (crpl/doc ::is/Ingredient) ;;check if specified keyword belongs to the sequence. (def tests #{:a :b :c}) (some tests #{:b}) ;; => :b ;;validate inline sequence key-val pair data (s/valid? ::is/Ingredient {:in_name "toast" :in_category ::i/bakery}) ;; => true ;####### Define required record type instances for our recipe spec validations ########### ;;define instance of user defrecord as the publisher of recipe (def user (u/->User 2345 "joesimpson" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "+919970456243" "PI:EMAIL:<EMAIL>END_PI" "23/11/1985" "11/02/2014")) ;;create new user record by adding optional lang pref property ;;to existing user record (def user_with_lang_pref (assoc user ::us/u_langPref "en_US")) (-> user_with_lang_pref ::us/u_langPref) ;; => "en_US" ;;validate user against user spec (s/valid? ::us/User user_with_lang_pref) ;; => true (def flour (i/->Ingredient "Wheat flour" ::i/bakery)) ;;Note: 'Ingredient.' when record type is imported (s/valid? ::is/Ingredient flour) ;; => true (s/valid? ::is/Ingredient {::is/in_name (-> flour :in_name) ::is/in_category (-> flour :in_category)}) ;; => true ;;get keys of defrecord type (keys flour) ;; => (:in_name :in_category) ;;return no. of keys defined in defrecord (count flour) ;; => 2 ;;access defrecord instance named properties (-> flour :in_name) ;; => "Wheat flour" (-> flour :in_category) ;; => :com.mshiray.recipebcp.domain.type.ingredient/bakery ;;validate defrecord instancd against defined Ingredient spec.. (s/valid? ::is/Ingredient flour) ;; => true ;;create ingredient data from hash map instead of defreocrd type (def eggs (hash-map :in_name "eggs" :in_category ::i/poultry)) ;;vlaidate created hashmap data against the defined Ingredient spec... (s/valid? ::is/Ingredient eggs) ;; => true ;;append optional properties key-vals to existing entity map (def eggs_with_specs (assoc eggs ;;IngredientFormFactor props :in_form ::i/whole :in_process_type ::i/fresh :in_form_details ::i/large :in_special_instrns ::i/organic :alergy_warning false :in_description "organic farm fresh chicken eggs")) ;;access properties of compbined eggs entity map (-> eggs_with_specs :in_name) ;; => "eggs" ;; => "eggs" (eggs_with_specs :in_description) ;; => "organic farm fresh chicken eggs" ;;validate appended entity map against the Ingredient specs (s/valid? ::is/Ingredient eggs_with_specs) ;; => true ;;lets fetch two eggs for our omlette recipe prep (def eggs_qty (i/->In_Measure 2 ::i/no)) ;;append measures record isntance to flour ingredient for our bread recipe (def two_eggs (assoc eggs_with_specs ::in_measure eggs_qty ::in_measure_type ::i/Exact ::in_decription "dont carry all of them in one basket!")) (s/valid? ::is/Ingredient two_eggs) ;; => true ;;TODO ;;ref: https://clojuredocs.org/clojure.core/defrecord ;; This is particularly useful for mapping parsed CSV files to records ;;(map #(apply t/Ingredient %) parsed-csv-file) ;;lets add flour ingredient measures required for our recipes (def flour_msr_qty (i/->In_Measure 2 ::i/C)) ;;append measures record isntance to flour ingredient for our bread recipe (def two_cup_flour (assoc flour ::in_measure flour_msr_qty ::in_measure_type ::i/Lightly_Packed ::in_decription "whole wheat flour one cup")) (s/valid? ::is/Ingredient two_cup_flour) ;; => true ;lets see internal data structure of the created flour ingredient (-> two_cup_flour) ;; => {:in_name "Wheat flour", ;; :in_category ;; :com.mshiray.recipebcp.domain.type.ingredient/bakery, ;; :com.mshiray.recipebcp.spec_test/in_measure ;; {:in_measure_no 2, ;; :in_measure_units ;; :com.mshiray.recipebcp.domain.type.ingredient/C}, ;; :com.mshiray.recipebcp.spec_test/in_measure_type ;; :com.mshiray.recipebcp.domain.type.ingredient/Lightly_Packed, ;; :com.mshiray.recipebcp.spec_test/in_decription ;; "whole wheat flour one cup"} ;;access nested cup measures quantity amount & units for flour ingredient (-> two_cup_flour ::in_measure :in_measure_no) ;; => 2 (-> two_cup_flour ::in_measure :in_measure_units) ;; => :com.mshiray.recipebcp.domain.type.ingredient/C ;;create new ingredient record instance for salt (def salt (i/->Ingredient "salt" ::i/additive)) ;;append measures properties to salt ingredient ;;lets add flour ingredient measures required for our recipes (def salt_msr_qty (i/->In_Measure 0.25 ::i/tsp)) ;;append measures record isntance to flour ingredient for our bread recipe (def qtr_tsp_salt (assoc salt ::in_measure salt_msr_qty ::in_measure_type ::Lightly_Packed ::in_decription "quarter tea spoon of sea salt")) ;;access nested recipe composite properties (-> qtr_tsp_salt ::in_measure :in_measure_no) ;; => 0.25 (-> qtr_tsp_salt ::in_measure :in_measure_units) ;; => :com.mshiray.recipebcp.domain.type.ingredient/tsp (s/valid? ::is/Ingredient qtr_tsp_salt) ;; => true ;;lets create distinct set of ingredients for our bread (def bread_ingredients #{two_cup_flour qtr_tsp_salt}) (s/valid? ::rs/r_ingredients bread_ingredients) ;; => true ;;create bread recipe record instance (def bread_recipe (r/->Recipe 135 "bread" user_with_lang_pref "brown bread" "01:00" 4 ::r/Vegiterian ::r/Western ::r/Bakery ::r/Other ::r/T3 bread_ingredients)) ;;print spec documentation on console (crpl/doc ::rs/Recipe) ;;explain msg to debug any validation errors (s/explain ::rs/Recipe bread_recipe) ;;validate our bread recipe for any data mismatch (s/valid? ::rs/Recipe bread_recipe) ;; => true ;;define recipe defrecord with optional companion recipe added. (def omlette_recipe (r/->Recipe 134 "omlette" user_with_lang_pref "masala omlette" "00:20" 1 ::r/NonVeg ::r/Indian ::r/Breakfast ::r/Spicy ::r/T4 #{two_eggs qtr_tsp_salt})) (s/valid? ::rs/Recipe omlette_recipe) ;; => true ;;append optional companion recipe property to existing recipe defrecord to recommend having a bread with our omlette (def bread_omlette (assoc omlette_recipe ::rs/companions [bread_recipe])) ;;validate final recipe defrecord instance with companion recipe added to it (s/valid? ::rs/Recipe bread_omlette) ;; => true
[ { "context": ";; Copyright (c) Michael Glaesemann\n;; Heavily inspired by congitect.http-client, Cop", "end": 35, "score": 0.9998552203178406, "start": 17, "tag": "NAME", "value": "Michael Glaesemann" } ]
src/com/grzm/aws/http_client.cljc
borkdude/yaaws-api
1
;; Copyright (c) Michael Glaesemann ;; Heavily inspired by congitect.http-client, Copyright (c) Cognitect, Inc. ;; All rights reserved. (ns com.grzm.aws.http-client (:require [clojure.core.async :refer [put!] :as a] [com.grzm.aws.http-client.client :as client] [com.grzm.aws.http-client.specs]) (:import (clojure.lang ExceptionInfo) (java.net URI) (java.net.http HttpClient HttpClient$Redirect HttpHeaders HttpRequest HttpRequest$Builder HttpRequest$BodyPublishers HttpResponse HttpResponse$BodyHandlers) (java.nio ByteBuffer) (java.time Duration) (java.util.function Function))) #?(:bb (do (require 'spartan.spec) (alias 's 'clojure.spec.alpha)) :clj (require '[clojure.spec.alpha :as s])) (set! *warn-on-reflection* true) (defn submit "Submit an http request, channel will be filled with response. Returns ch. Request map: :server-name string :server-port integer :uri string :query-string string, optional :request-method :get/:post/:put/:head :scheme :http or :https :headers map from downcased string to string :body ByteBuffer, optional :cognitect.http-client/timeout-msec opt, total request send/receive timeout :cognitect.http-client/meta opt, data to be added to the response map content-type must be specified in the headers map content-length is derived from the ByteBuffer passed to body Response map: :status integer HTTP status code :body ByteBuffer, optional :header map from downcased string to string :cognitect.http-client/meta opt, data from the request On error, response map is per cognitect.anomalies" ([client request] (submit client request (a/chan 1))) ([client request ch] (s/assert ::submit-request request) (client/submit client request ch))) (def method-string {:get "GET" :post "POST" :put "PUT" :head "HEAD" :delete "DELETE" :path "PATCH"}) (defn byte-buffer->byte-array [^ByteBuffer bbuf] (.rewind bbuf) (let [arr (byte-array (.remaining bbuf))] (.get bbuf arr) arr)) (defn flatten-headers [headers] (->> headers (mapcat (fn [[nom val]] (if (coll? val) (map (fn [v] [(name nom) v]) val) [[(name nom) val]]))))) (defn add-headers [^HttpRequest$Builder builder headers] (doseq [[nom val] (flatten-headers headers)] (.header builder nom val)) builder) (defn map->http-request [{:keys [scheme server-name server-port uri query-string request-method headers body] :or {scheme "https"} :as m}] (let [uri (URI. (str (name scheme) "://" server-name (some->> server-port (str ":")) uri (some->> query-string (str "?")))) method (method-string request-method) bp (if body (HttpRequest$BodyPublishers/ofByteArray (byte-buffer->byte-array body)) (HttpRequest$BodyPublishers/noBody)) builder (-> (HttpRequest/newBuilder uri) (.method method bp))] (.build (cond-> builder (seq headers) (add-headers headers) (::timeout-msec m) (.timeout (Duration/ofMillis (::timeout-msec m))))))) (defn error->anomaly [^Throwable t] {:cognitect.anomalies/category :cognitect.anomalies/fault :cognitect.anomalies/message (.getMessage t) ::throwable t}) (defn header-map [^HttpHeaders headers] (->> headers (.map) (map (fn [[k v]] [k (if (< 1 (count v)) (into [] v) (first v))])) (into {}))) (defn response-map [^HttpResponse http-response] (let [body (.body http-response)] (cond-> {:status (.statusCode http-response) :headers (header-map (.headers http-response))} body (assoc :body (ByteBuffer/wrap body))))) (defrecord Client [^HttpClient http-client pending-ops pending-ops-limit] client/Client (-submit [_ request ch] (if (< pending-ops-limit (swap! pending-ops inc)) (do (put! ch (merge {:cognitect.anomalies/category :cognitect.anomalies/busy :cognitect.anomalies/message (str "Ops limit reached: " pending-ops-limit) :pending-ops-limit pending-ops-limit} (select-keys request [::meta]))) (swap! pending-ops dec)) (try (let [http-request (map->http-request request)] (-> (.sendAsync http-client http-request (HttpResponse$BodyHandlers/ofByteArray)) (.thenApply (reify Function (apply [_ http-response] (put! ch (merge (response-map http-response) (select-keys request [::meta])))))) (.exceptionally (reify Function (apply [_ e] (let [cause (.getCause ^Exception e)] (if (instance? ExceptionInfo cause) (throw cause) (throw e)))))))) (catch Throwable t (put! ch (merge (error->anomaly t) (select-keys request [::meta]))) (swap! pending-ops dec)))) ch)) (defn create [{:keys [connect-timeout-msecs pending-ops-limit] :or {pending-ops-limit 64 connect-timeout-msecs 5000} :as _config}] (System/setProperty "jdk.httpclient.allowRestrictedHeaders" "host") (let [http-client (.build (-> (HttpClient/newBuilder) (.connectTimeout (Duration/ofMillis connect-timeout-msecs)) (.followRedirects HttpClient$Redirect/NORMAL)))] (->Client http-client (atom 0) pending-ops-limit))) (defn stop "no-op. Implemented for compatibility" [^Client _client])
116659
;; Copyright (c) <NAME> ;; Heavily inspired by congitect.http-client, Copyright (c) Cognitect, Inc. ;; All rights reserved. (ns com.grzm.aws.http-client (:require [clojure.core.async :refer [put!] :as a] [com.grzm.aws.http-client.client :as client] [com.grzm.aws.http-client.specs]) (:import (clojure.lang ExceptionInfo) (java.net URI) (java.net.http HttpClient HttpClient$Redirect HttpHeaders HttpRequest HttpRequest$Builder HttpRequest$BodyPublishers HttpResponse HttpResponse$BodyHandlers) (java.nio ByteBuffer) (java.time Duration) (java.util.function Function))) #?(:bb (do (require 'spartan.spec) (alias 's 'clojure.spec.alpha)) :clj (require '[clojure.spec.alpha :as s])) (set! *warn-on-reflection* true) (defn submit "Submit an http request, channel will be filled with response. Returns ch. Request map: :server-name string :server-port integer :uri string :query-string string, optional :request-method :get/:post/:put/:head :scheme :http or :https :headers map from downcased string to string :body ByteBuffer, optional :cognitect.http-client/timeout-msec opt, total request send/receive timeout :cognitect.http-client/meta opt, data to be added to the response map content-type must be specified in the headers map content-length is derived from the ByteBuffer passed to body Response map: :status integer HTTP status code :body ByteBuffer, optional :header map from downcased string to string :cognitect.http-client/meta opt, data from the request On error, response map is per cognitect.anomalies" ([client request] (submit client request (a/chan 1))) ([client request ch] (s/assert ::submit-request request) (client/submit client request ch))) (def method-string {:get "GET" :post "POST" :put "PUT" :head "HEAD" :delete "DELETE" :path "PATCH"}) (defn byte-buffer->byte-array [^ByteBuffer bbuf] (.rewind bbuf) (let [arr (byte-array (.remaining bbuf))] (.get bbuf arr) arr)) (defn flatten-headers [headers] (->> headers (mapcat (fn [[nom val]] (if (coll? val) (map (fn [v] [(name nom) v]) val) [[(name nom) val]]))))) (defn add-headers [^HttpRequest$Builder builder headers] (doseq [[nom val] (flatten-headers headers)] (.header builder nom val)) builder) (defn map->http-request [{:keys [scheme server-name server-port uri query-string request-method headers body] :or {scheme "https"} :as m}] (let [uri (URI. (str (name scheme) "://" server-name (some->> server-port (str ":")) uri (some->> query-string (str "?")))) method (method-string request-method) bp (if body (HttpRequest$BodyPublishers/ofByteArray (byte-buffer->byte-array body)) (HttpRequest$BodyPublishers/noBody)) builder (-> (HttpRequest/newBuilder uri) (.method method bp))] (.build (cond-> builder (seq headers) (add-headers headers) (::timeout-msec m) (.timeout (Duration/ofMillis (::timeout-msec m))))))) (defn error->anomaly [^Throwable t] {:cognitect.anomalies/category :cognitect.anomalies/fault :cognitect.anomalies/message (.getMessage t) ::throwable t}) (defn header-map [^HttpHeaders headers] (->> headers (.map) (map (fn [[k v]] [k (if (< 1 (count v)) (into [] v) (first v))])) (into {}))) (defn response-map [^HttpResponse http-response] (let [body (.body http-response)] (cond-> {:status (.statusCode http-response) :headers (header-map (.headers http-response))} body (assoc :body (ByteBuffer/wrap body))))) (defrecord Client [^HttpClient http-client pending-ops pending-ops-limit] client/Client (-submit [_ request ch] (if (< pending-ops-limit (swap! pending-ops inc)) (do (put! ch (merge {:cognitect.anomalies/category :cognitect.anomalies/busy :cognitect.anomalies/message (str "Ops limit reached: " pending-ops-limit) :pending-ops-limit pending-ops-limit} (select-keys request [::meta]))) (swap! pending-ops dec)) (try (let [http-request (map->http-request request)] (-> (.sendAsync http-client http-request (HttpResponse$BodyHandlers/ofByteArray)) (.thenApply (reify Function (apply [_ http-response] (put! ch (merge (response-map http-response) (select-keys request [::meta])))))) (.exceptionally (reify Function (apply [_ e] (let [cause (.getCause ^Exception e)] (if (instance? ExceptionInfo cause) (throw cause) (throw e)))))))) (catch Throwable t (put! ch (merge (error->anomaly t) (select-keys request [::meta]))) (swap! pending-ops dec)))) ch)) (defn create [{:keys [connect-timeout-msecs pending-ops-limit] :or {pending-ops-limit 64 connect-timeout-msecs 5000} :as _config}] (System/setProperty "jdk.httpclient.allowRestrictedHeaders" "host") (let [http-client (.build (-> (HttpClient/newBuilder) (.connectTimeout (Duration/ofMillis connect-timeout-msecs)) (.followRedirects HttpClient$Redirect/NORMAL)))] (->Client http-client (atom 0) pending-ops-limit))) (defn stop "no-op. Implemented for compatibility" [^Client _client])
true
;; Copyright (c) PI:NAME:<NAME>END_PI ;; Heavily inspired by congitect.http-client, Copyright (c) Cognitect, Inc. ;; All rights reserved. (ns com.grzm.aws.http-client (:require [clojure.core.async :refer [put!] :as a] [com.grzm.aws.http-client.client :as client] [com.grzm.aws.http-client.specs]) (:import (clojure.lang ExceptionInfo) (java.net URI) (java.net.http HttpClient HttpClient$Redirect HttpHeaders HttpRequest HttpRequest$Builder HttpRequest$BodyPublishers HttpResponse HttpResponse$BodyHandlers) (java.nio ByteBuffer) (java.time Duration) (java.util.function Function))) #?(:bb (do (require 'spartan.spec) (alias 's 'clojure.spec.alpha)) :clj (require '[clojure.spec.alpha :as s])) (set! *warn-on-reflection* true) (defn submit "Submit an http request, channel will be filled with response. Returns ch. Request map: :server-name string :server-port integer :uri string :query-string string, optional :request-method :get/:post/:put/:head :scheme :http or :https :headers map from downcased string to string :body ByteBuffer, optional :cognitect.http-client/timeout-msec opt, total request send/receive timeout :cognitect.http-client/meta opt, data to be added to the response map content-type must be specified in the headers map content-length is derived from the ByteBuffer passed to body Response map: :status integer HTTP status code :body ByteBuffer, optional :header map from downcased string to string :cognitect.http-client/meta opt, data from the request On error, response map is per cognitect.anomalies" ([client request] (submit client request (a/chan 1))) ([client request ch] (s/assert ::submit-request request) (client/submit client request ch))) (def method-string {:get "GET" :post "POST" :put "PUT" :head "HEAD" :delete "DELETE" :path "PATCH"}) (defn byte-buffer->byte-array [^ByteBuffer bbuf] (.rewind bbuf) (let [arr (byte-array (.remaining bbuf))] (.get bbuf arr) arr)) (defn flatten-headers [headers] (->> headers (mapcat (fn [[nom val]] (if (coll? val) (map (fn [v] [(name nom) v]) val) [[(name nom) val]]))))) (defn add-headers [^HttpRequest$Builder builder headers] (doseq [[nom val] (flatten-headers headers)] (.header builder nom val)) builder) (defn map->http-request [{:keys [scheme server-name server-port uri query-string request-method headers body] :or {scheme "https"} :as m}] (let [uri (URI. (str (name scheme) "://" server-name (some->> server-port (str ":")) uri (some->> query-string (str "?")))) method (method-string request-method) bp (if body (HttpRequest$BodyPublishers/ofByteArray (byte-buffer->byte-array body)) (HttpRequest$BodyPublishers/noBody)) builder (-> (HttpRequest/newBuilder uri) (.method method bp))] (.build (cond-> builder (seq headers) (add-headers headers) (::timeout-msec m) (.timeout (Duration/ofMillis (::timeout-msec m))))))) (defn error->anomaly [^Throwable t] {:cognitect.anomalies/category :cognitect.anomalies/fault :cognitect.anomalies/message (.getMessage t) ::throwable t}) (defn header-map [^HttpHeaders headers] (->> headers (.map) (map (fn [[k v]] [k (if (< 1 (count v)) (into [] v) (first v))])) (into {}))) (defn response-map [^HttpResponse http-response] (let [body (.body http-response)] (cond-> {:status (.statusCode http-response) :headers (header-map (.headers http-response))} body (assoc :body (ByteBuffer/wrap body))))) (defrecord Client [^HttpClient http-client pending-ops pending-ops-limit] client/Client (-submit [_ request ch] (if (< pending-ops-limit (swap! pending-ops inc)) (do (put! ch (merge {:cognitect.anomalies/category :cognitect.anomalies/busy :cognitect.anomalies/message (str "Ops limit reached: " pending-ops-limit) :pending-ops-limit pending-ops-limit} (select-keys request [::meta]))) (swap! pending-ops dec)) (try (let [http-request (map->http-request request)] (-> (.sendAsync http-client http-request (HttpResponse$BodyHandlers/ofByteArray)) (.thenApply (reify Function (apply [_ http-response] (put! ch (merge (response-map http-response) (select-keys request [::meta])))))) (.exceptionally (reify Function (apply [_ e] (let [cause (.getCause ^Exception e)] (if (instance? ExceptionInfo cause) (throw cause) (throw e)))))))) (catch Throwable t (put! ch (merge (error->anomaly t) (select-keys request [::meta]))) (swap! pending-ops dec)))) ch)) (defn create [{:keys [connect-timeout-msecs pending-ops-limit] :or {pending-ops-limit 64 connect-timeout-msecs 5000} :as _config}] (System/setProperty "jdk.httpclient.allowRestrictedHeaders" "host") (let [http-client (.build (-> (HttpClient/newBuilder) (.connectTimeout (Duration/ofMillis connect-timeout-msecs)) (.followRedirects HttpClient$Redirect/NORMAL)))] (->Client http-client (atom 0) pending-ops-limit))) (defn stop "no-op. Implemented for compatibility" [^Client _client])
[ { "context": "r mocking/expectation framework for Clojure\n\n;; by Matt Clark\n\n;; Copyright (c) Matt Clark, 2009. All rights re", "end": 106, "score": 0.9998635053634644, "start": 96, "tag": "NAME", "value": "Matt Clark" }, { "context": "rk for Clojure\n\n;; by Matt Clark\n\n;; Copyright (c) Matt Clark, 2009. All rights reserved. The use\n;; and distr", "end": 135, "score": 0.9998670816421509, "start": 125, "tag": "NAME", "value": "Matt Clark" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/mock/test_adapter.clj
allertonm/Couverjure
3
;;; test_adapter.clj: clojure.test adapter for mocking/expectation framework for Clojure ;; by Matt Clark ;; Copyright (c) Matt Clark, 2009. 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. You must not ;; remove this notice, or any other, from this software. (ns clojure.contrib.mock.test-adapter (:require [clojure.contrib.mock :as mock]) (:use clojure.test clojure.contrib.ns-utils)) (immigrate 'clojure.contrib.mock) (defn report-problem "This function is designed to be used in a binding macro to override the report-problem function in clojure.contrib.mock. Instead of printing the error to the console, the error is logged via clojure.test." {:dynamic true} [fn-name expected actual msg] (report {:type :fail, :message (str msg " Function name: " fn-name), :expected expected, :actual actual})) (defmacro expect [& body] "Use this macro instead of the standard c.c.mock expect macro to have failures reported through clojure.test." `(binding [mock/report-problem report-problem] (mock/expect ~@body)))
78703
;;; test_adapter.clj: clojure.test adapter for mocking/expectation framework for Clojure ;; by <NAME> ;; Copyright (c) <NAME>, 2009. 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. You must not ;; remove this notice, or any other, from this software. (ns clojure.contrib.mock.test-adapter (:require [clojure.contrib.mock :as mock]) (:use clojure.test clojure.contrib.ns-utils)) (immigrate 'clojure.contrib.mock) (defn report-problem "This function is designed to be used in a binding macro to override the report-problem function in clojure.contrib.mock. Instead of printing the error to the console, the error is logged via clojure.test." {:dynamic true} [fn-name expected actual msg] (report {:type :fail, :message (str msg " Function name: " fn-name), :expected expected, :actual actual})) (defmacro expect [& body] "Use this macro instead of the standard c.c.mock expect macro to have failures reported through clojure.test." `(binding [mock/report-problem report-problem] (mock/expect ~@body)))
true
;;; test_adapter.clj: clojure.test adapter for mocking/expectation framework for Clojure ;; by PI:NAME:<NAME>END_PI ;; Copyright (c) PI:NAME:<NAME>END_PI, 2009. 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. You must not ;; remove this notice, or any other, from this software. (ns clojure.contrib.mock.test-adapter (:require [clojure.contrib.mock :as mock]) (:use clojure.test clojure.contrib.ns-utils)) (immigrate 'clojure.contrib.mock) (defn report-problem "This function is designed to be used in a binding macro to override the report-problem function in clojure.contrib.mock. Instead of printing the error to the console, the error is logged via clojure.test." {:dynamic true} [fn-name expected actual msg] (report {:type :fail, :message (str msg " Function name: " fn-name), :expected expected, :actual actual})) (defmacro expect [& body] "Use this macro instead of the standard c.c.mock expect macro to have failures reported through clojure.test." `(binding [mock/report-problem report-problem] (mock/expect ~@body)))
[ { "context": "(t/is (sut/valid-password?\n {:password \"abcde\", :letter \\a, :fst 1, :snd 3}))))\n\n(t/deftest inv", "end": 292, "score": 0.9994314908981323, "start": 287, "tag": "PASSWORD", "value": "abcde" }, { "context": " (sut/valid-password?\n {:password \"cdefg\", :letter \\b, :fst 1, :snd 3})))))\n\n(t/deftest co", "end": 468, "score": 0.9994256496429443, "start": 463, "tag": "PASSWORD", "value": "cdefg" } ]
test/aoc_2020/day_2/problem_1_test.clj
Camsbury/aoc-2020
2
(ns aoc-2020.day-2.problem-1-test (:require [aoc-2020.day-2.problem-1 :as sut] [aoc-2020.day-2.utils :as day-utils] [clojure.test :as t])) (t/deftest valid-password-test (t/testing "validates a password" (t/is (sut/valid-password? {:password "abcde", :letter \a, :fst 1, :snd 3})))) (t/deftest invalid-password-test (t/testing "invalidates a password" (t/is (not (sut/valid-password? {:password "cdefg", :letter \b, :fst 1, :snd 3}))))) (t/deftest count-valid-passwords-test (t/testing "counts valid passwords" (t/is (= 2 (->> ["1-3 a: abcde" "1-3 b: cdefg" "2-9 c: ccccccccc"] (map day-utils/process-entry) sut/count-valid-passwords)))))
73106
(ns aoc-2020.day-2.problem-1-test (:require [aoc-2020.day-2.problem-1 :as sut] [aoc-2020.day-2.utils :as day-utils] [clojure.test :as t])) (t/deftest valid-password-test (t/testing "validates a password" (t/is (sut/valid-password? {:password "<PASSWORD>", :letter \a, :fst 1, :snd 3})))) (t/deftest invalid-password-test (t/testing "invalidates a password" (t/is (not (sut/valid-password? {:password "<PASSWORD>", :letter \b, :fst 1, :snd 3}))))) (t/deftest count-valid-passwords-test (t/testing "counts valid passwords" (t/is (= 2 (->> ["1-3 a: abcde" "1-3 b: cdefg" "2-9 c: ccccccccc"] (map day-utils/process-entry) sut/count-valid-passwords)))))
true
(ns aoc-2020.day-2.problem-1-test (:require [aoc-2020.day-2.problem-1 :as sut] [aoc-2020.day-2.utils :as day-utils] [clojure.test :as t])) (t/deftest valid-password-test (t/testing "validates a password" (t/is (sut/valid-password? {:password "PI:PASSWORD:<PASSWORD>END_PI", :letter \a, :fst 1, :snd 3})))) (t/deftest invalid-password-test (t/testing "invalidates a password" (t/is (not (sut/valid-password? {:password "PI:PASSWORD:<PASSWORD>END_PI", :letter \b, :fst 1, :snd 3}))))) (t/deftest count-valid-passwords-test (t/testing "counts valid passwords" (t/is (= 2 (->> ["1-3 a: abcde" "1-3 b: cdefg" "2-9 c: ccccccccc"] (map day-utils/process-entry) sut/count-valid-passwords)))))
[ { "context": "T\")\n; \"/testendpoint\")\n; :user \"testusr\"\n; :password \"testpwd\"\n; }\n; (if-let [", "end": 1029, "score": 0.9976038932800293, "start": 1022, "tag": "USERNAME", "value": "testusr" }, { "context": "endpoint\")\n; :user \"testusr\"\n; :password \"testpwd\"\n; }\n; (if-let [host (System/getenv \"MYSQL", "end": 1055, "score": 0.9994418621063232, "start": 1048, "tag": "PASSWORD", "value": "testpwd" }, { "context": "; \"/testendpoint\")\n; :user \"testusr\"\n; :password \"testpwd\"\n; }\n; {:s", "end": 1353, "score": 0.9943719506263733, "start": 1346, "tag": "USERNAME", "value": "testusr" }, { "context": "oint\")\n; :user \"testusr\"\n; :password \"testpwd\"\n; }\n; {:subprotocol \"mysql\"\n; :", "end": 1381, "score": 0.9994384050369263, "start": 1374, "tag": "PASSWORD", "value": "testpwd" }, { "context": "me \"//localhost:3306/testendpoint\"\n; :user \"testusr\"\n; :password \"testpwd\"\n; }\n; )))", "end": 1493, "score": 0.9972643852233887, "start": 1486, "tag": "USERNAME", "value": "testusr" }, { "context": "point\"\n; :user \"testusr\"\n; :password \"testpwd\"\n; }\n; )))\n\n; NEW Postgres spec for Cr", "end": 1521, "score": 0.9994708299636841, "start": 1514, "tag": "PASSWORD", "value": "testpwd" }, { "context": "getenv \"PGUSER\")\n :password (System/getenv \"PGPASSWORD\")\n :ssl true\n :sslmode \"require\"\n }\n ", "end": 1943, "score": 0.5353912115097046, "start": 1935, "tag": "PASSWORD", "value": "PASSWORD" }, { "context": "bname \"//localhost:3306/testendpoint\"\n :user \"testusr\"\n :password \"testpwd\"\n }\n ))\n\n;;;\n;;; ", "end": 2083, "score": 0.8196712732315063, "start": 2076, "tag": "USERNAME", "value": "testusr" }, { "context": "estendpoint\"\n :user \"testusr\"\n :password \"testpwd\"\n }\n ))\n\n;;;\n;;; MongoDB of sailing tracks", "end": 2108, "score": 0.9994996190071106, "start": 2101, "tag": "PASSWORD", "value": "testpwd" }, { "context": "ONGODB_26_RHEL7_SERVICE_PORT\"))\n; uname \"testusr\"\n; dbname \"tracks\"\n; pwd-raw \"t", "end": 2427, "score": 0.9857660531997681, "start": 2420, "tag": "USERNAME", "value": "testusr" }, { "context": "r\"\n; dbname \"tracks\"\n; pwd-raw \"testpwd\"\n; pwd (.toCharArray pwd-raw)\n; ", "end": 2483, "score": 0.9993953704833984, "start": 2476, "tag": "PASSWORD", "value": "testpwd" }, { "context": " \"MONGODB_SERVICE_PORT\"))\n; uname \"testusr\"\n; dbname \"tracks\"\n; pwd-ra", "end": 2826, "score": 0.9887744188308716, "start": 2819, "tag": "USERNAME", "value": "testusr" }, { "context": " dbname \"tracks\"\n; pwd-raw \"testpwd\"\n; pwd (.toCharArray pwd-raw)\n; ", "end": 2886, "score": 0.999335765838623, "start": 2879, "tag": "PASSWORD", "value": "testpwd" }, { "context": "s-username \":\"\n atlas-password \"@\"\n atlas-host \"/\"\n ", "end": 3777, "score": 0.9436505436897278, "start": 3777, "tag": "PASSWORD", "value": "" } ]
src/rhoda_test_clojure/handler.clj
mpiech/rhoda-test-clojure
0
(ns rhoda-test-clojure.handler (:require [nrepl.server :as nrepl] [compojure.core :as cpj] [compojure.route :as cpjroute] [ring.middleware.defaults :as ring] [net.cgrand.enlive-html :as enlive] [clj-time.core :as time] [clj-time.format :as ftime] [clj-time.coerce :as ctime] [clojure.java.jdbc :as jdbc] [clojure.data.json :as json] [clojure.java.io :as io] [monger.core :as mg] [monger.credentials :as mcr] [monger.collection :as mc] [monger.operators :refer :all] )) ;;; ;;; Static parameters ;;; (def timezone "America/Los_Angeles") (def gmaps-key (System/getenv "GMAPS_KEY")) ;;; ;;; SQL database of reservations ;;; ; OLD MySQL database specs for OpenShift or local ; ;(def dbspec ; (if-let [host (System/getenv "MYSQL_55_RHEL7_SERVICE_HOST")] ; {:subprotocol "mysql" ; :subname (str ; "//" ; host ; ":" ; (System/getenv "MYSQL_55_RHEL7_SERVICE_PORT") ; "/testendpoint") ; :user "testusr" ; :password "testpwd" ; } ; (if-let [host (System/getenv "MYSQL_SERVICE_HOST")] ; {:subprotocol "mysql" ; :subname (str ; "//" ; host ; ":" ; (System/getenv "MYSQL_SERVICE_PORT") ; "/testendpoint") ; :user "testusr" ; :password "testpwd" ; } ; {:subprotocol "mysql" ; :subname "//localhost:3306/testendpoint" ; :user "testusr" ; :password "testpwd" ; } ; ))) ; NEW Postgres spec for Crunchy Bridge on OpenShift or local ; ; TODO: get RHODA bindings from injected Service Bindings (def dbspec (if-let [host (System/getenv "PGHOST")] {:dbtype "postgresql" :dbname (System/getenv "PGDB") :host (System/getenv "PGHOST") ; host :user (System/getenv "PGUSER") :password (System/getenv "PGPASSWORD") :ssl true :sslmode "require" } {:subprotocol "mysql" :subname "//localhost:3306/testendpoint" :user "testusr" :password "testpwd" } )) ;;; ;;; MongoDB of sailing tracks ;;; ; OLD: connection to in-cluster MongoDB ;(def mgconn ; (if-let [host (System/getenv "MONGODB_26_RHEL7_SERVICE_HOST")] ; (let [port (Integer/parseInt ; (System/getenv ; "MONGODB_26_RHEL7_SERVICE_PORT")) ; uname "testusr" ; dbname "tracks" ; pwd-raw "testpwd" ; pwd (.toCharArray pwd-raw) ; creds (mcr/create uname dbname pwd)] ; (mg/connect-with-credentials host port creds)) ; (if-let [host (System/getenv "MONGODB_SERVICE_HOST")] ; (let [port (Integer/parseInt ; (System/getenv ; "MONGODB_SERVICE_PORT")) ; uname "testusr" ; dbname "tracks" ; pwd-raw "testpwd" ; pwd (.toCharArray pwd-raw) ; creds (mcr/create uname dbname pwd)] ; (mg/connect-with-credentials host port creds)) ; (mg/connect) ; ))) ; ;(def mgdb (mg/get-db mgconn "mystrk")) ; TODO: get creds from OpenShift Service Binding ;(def atlas-cred-dir "/bindings/cpjdb1-d-cluster0-26b73026be-dbsc") ;(def atlas-username (slurp (str atlas-cred-dir "/username"))) ;(def atlas-password (slurp (str atlas-cred-dir "/password"))) ;(def atlas-host (slurp (str atlas-cred-dir "/host"))) ;(def atlas-db "mystrk") (def atlas-username (System/getenv "ATLAS_USERNAME")) (def atlas-password (System/getenv "ATLAS_PASSWORD")) (def atlas-host (System/getenv "ATLAS_HOST")) (def atlas-db (System/getenv "ATLAS_DB")) (def mgdb (:db (mg/connect-via-uri (str "mongodb+srv://" atlas-username ":" atlas-password "@" atlas-host "/" atlas-db)))) ;;; ;;; Date/Time utilities ;;; (defn sqldtobj-to-dtobj [sqldtobj] (time/to-time-zone (ctime/from-sql-time sqldtobj) (time/time-zone-for-id timezone))) ;;; ;;; Database read functions ;;; ; reservations and other 'events' from SQL database ; Postgres needs TIMESTAMP cast to make this work, unlike MySQL (defn db-read-dtobjs [table start-dtstr end-dtstr] (let [qstr (str "SELECT DISTINCT res_date " "FROM " table " WHERE CAST (res_date AS TIMESTAMP) >= " "CAST ('" start-dtstr "' AS TIMESTAMP) " "AND CAST (res_date AS TIMESTAMP) <= " "CAST ('" end-dtstr "' AS TIMESTAMP)" )] (map (fn [x] (sqldtobj-to-dtobj (:res_date x))) (try (jdbc/query dbspec [qstr]) (catch org.postgresql.util.PSQLException e (println qstr (ex-message e))))) )) ; sailing tracks from MongoDB ; fix to filter date >= datestr; currently returns all tracks ever (defn trdb-read-dtobjs [coll start-dtstr end-dtstr] (map (fn [x] (:date x)) (mc/find-maps mgdb coll)) ) ;;; ;;; Enlive - Clojure HTML templating ;;; ;;; for index, simply show index.html with vars replaced (enlive/deftemplate index "rhoda_test_clojure/index.html" [] [:#gmap] (enlive/replace-vars {:gmapskey gmaps-key}) ) ;;; ;;; Handlers for Compojure - Clojure web app routing ;;; ;;; main calendar page - enlive displays index.html SPA (defn handler-get-index [] (index) ) (defn handler-get-track [params] (let [trdate (get params "date") rawTrack (mc/find-one-as-map mgdb "tracks" {:date trdate}) ] (if rawTrack (json/write-str (:points rawTrack)) (json/write-str '[])) ) ) ;;; REST API for AJAX call to get dates as JSON ;;; returns array of e.g. {:title "Mys Rsvd" :start "2021-12-10"} (defn handler-get-events [params] (let [start (subs (get params "start" "2021-12-01") 0 10) end (subs (get params "end" "2021-12-31") 0 10)] (json/write-str (concat (map (fn [x] {:title "Boat Reserved", :start (ftime/unparse (ftime/formatters :date) x) }) (db-read-dtobjs "reservations" start end)) ; example of other types of events currently not being captured ; (map (fn [x] ; {:title "Bareboat", ; :start (ftime/unparse ; (ftime/formatters ; :date) ; x) ; }) ; (db-read-dtobjs "bareboat" start end)) (map (fn [x] {:title "Track", :start x }) (trdb-read-dtobjs "tracks" start end)))) )) ;;; ;;; Compojure Routing ;;; (cpj/defroutes app-routes (cpj/HEAD "/" [] "") (cpj/GET "/" [] (handler-get-index)) (cpj/GET "/track" {params :query-params} (handler-get-track params)) (cpj/GET "/events" {params :query-params} (handler-get-events params)) (cpjroute/files "/") (cpjroute/resources "/") (cpjroute/not-found "Not found.") ) ;; start nREPL server (defonce server (nrepl/start-server :port 7888)) ;; generated by 'lein ring new' (def app (ring/wrap-defaults app-routes ring/site-defaults) ) ;;; EOF
36346
(ns rhoda-test-clojure.handler (:require [nrepl.server :as nrepl] [compojure.core :as cpj] [compojure.route :as cpjroute] [ring.middleware.defaults :as ring] [net.cgrand.enlive-html :as enlive] [clj-time.core :as time] [clj-time.format :as ftime] [clj-time.coerce :as ctime] [clojure.java.jdbc :as jdbc] [clojure.data.json :as json] [clojure.java.io :as io] [monger.core :as mg] [monger.credentials :as mcr] [monger.collection :as mc] [monger.operators :refer :all] )) ;;; ;;; Static parameters ;;; (def timezone "America/Los_Angeles") (def gmaps-key (System/getenv "GMAPS_KEY")) ;;; ;;; SQL database of reservations ;;; ; OLD MySQL database specs for OpenShift or local ; ;(def dbspec ; (if-let [host (System/getenv "MYSQL_55_RHEL7_SERVICE_HOST")] ; {:subprotocol "mysql" ; :subname (str ; "//" ; host ; ":" ; (System/getenv "MYSQL_55_RHEL7_SERVICE_PORT") ; "/testendpoint") ; :user "testusr" ; :password "<PASSWORD>" ; } ; (if-let [host (System/getenv "MYSQL_SERVICE_HOST")] ; {:subprotocol "mysql" ; :subname (str ; "//" ; host ; ":" ; (System/getenv "MYSQL_SERVICE_PORT") ; "/testendpoint") ; :user "testusr" ; :password "<PASSWORD>" ; } ; {:subprotocol "mysql" ; :subname "//localhost:3306/testendpoint" ; :user "testusr" ; :password "<PASSWORD>" ; } ; ))) ; NEW Postgres spec for Crunchy Bridge on OpenShift or local ; ; TODO: get RHODA bindings from injected Service Bindings (def dbspec (if-let [host (System/getenv "PGHOST")] {:dbtype "postgresql" :dbname (System/getenv "PGDB") :host (System/getenv "PGHOST") ; host :user (System/getenv "PGUSER") :password (System/getenv "PG<PASSWORD>") :ssl true :sslmode "require" } {:subprotocol "mysql" :subname "//localhost:3306/testendpoint" :user "testusr" :password "<PASSWORD>" } )) ;;; ;;; MongoDB of sailing tracks ;;; ; OLD: connection to in-cluster MongoDB ;(def mgconn ; (if-let [host (System/getenv "MONGODB_26_RHEL7_SERVICE_HOST")] ; (let [port (Integer/parseInt ; (System/getenv ; "MONGODB_26_RHEL7_SERVICE_PORT")) ; uname "testusr" ; dbname "tracks" ; pwd-raw "<PASSWORD>" ; pwd (.toCharArray pwd-raw) ; creds (mcr/create uname dbname pwd)] ; (mg/connect-with-credentials host port creds)) ; (if-let [host (System/getenv "MONGODB_SERVICE_HOST")] ; (let [port (Integer/parseInt ; (System/getenv ; "MONGODB_SERVICE_PORT")) ; uname "testusr" ; dbname "tracks" ; pwd-raw "<PASSWORD>" ; pwd (.toCharArray pwd-raw) ; creds (mcr/create uname dbname pwd)] ; (mg/connect-with-credentials host port creds)) ; (mg/connect) ; ))) ; ;(def mgdb (mg/get-db mgconn "mystrk")) ; TODO: get creds from OpenShift Service Binding ;(def atlas-cred-dir "/bindings/cpjdb1-d-cluster0-26b73026be-dbsc") ;(def atlas-username (slurp (str atlas-cred-dir "/username"))) ;(def atlas-password (slurp (str atlas-cred-dir "/password"))) ;(def atlas-host (slurp (str atlas-cred-dir "/host"))) ;(def atlas-db "mystrk") (def atlas-username (System/getenv "ATLAS_USERNAME")) (def atlas-password (System/getenv "ATLAS_PASSWORD")) (def atlas-host (System/getenv "ATLAS_HOST")) (def atlas-db (System/getenv "ATLAS_DB")) (def mgdb (:db (mg/connect-via-uri (str "mongodb+srv://" atlas-username ":" atlas-password<PASSWORD> "@" atlas-host "/" atlas-db)))) ;;; ;;; Date/Time utilities ;;; (defn sqldtobj-to-dtobj [sqldtobj] (time/to-time-zone (ctime/from-sql-time sqldtobj) (time/time-zone-for-id timezone))) ;;; ;;; Database read functions ;;; ; reservations and other 'events' from SQL database ; Postgres needs TIMESTAMP cast to make this work, unlike MySQL (defn db-read-dtobjs [table start-dtstr end-dtstr] (let [qstr (str "SELECT DISTINCT res_date " "FROM " table " WHERE CAST (res_date AS TIMESTAMP) >= " "CAST ('" start-dtstr "' AS TIMESTAMP) " "AND CAST (res_date AS TIMESTAMP) <= " "CAST ('" end-dtstr "' AS TIMESTAMP)" )] (map (fn [x] (sqldtobj-to-dtobj (:res_date x))) (try (jdbc/query dbspec [qstr]) (catch org.postgresql.util.PSQLException e (println qstr (ex-message e))))) )) ; sailing tracks from MongoDB ; fix to filter date >= datestr; currently returns all tracks ever (defn trdb-read-dtobjs [coll start-dtstr end-dtstr] (map (fn [x] (:date x)) (mc/find-maps mgdb coll)) ) ;;; ;;; Enlive - Clojure HTML templating ;;; ;;; for index, simply show index.html with vars replaced (enlive/deftemplate index "rhoda_test_clojure/index.html" [] [:#gmap] (enlive/replace-vars {:gmapskey gmaps-key}) ) ;;; ;;; Handlers for Compojure - Clojure web app routing ;;; ;;; main calendar page - enlive displays index.html SPA (defn handler-get-index [] (index) ) (defn handler-get-track [params] (let [trdate (get params "date") rawTrack (mc/find-one-as-map mgdb "tracks" {:date trdate}) ] (if rawTrack (json/write-str (:points rawTrack)) (json/write-str '[])) ) ) ;;; REST API for AJAX call to get dates as JSON ;;; returns array of e.g. {:title "Mys Rsvd" :start "2021-12-10"} (defn handler-get-events [params] (let [start (subs (get params "start" "2021-12-01") 0 10) end (subs (get params "end" "2021-12-31") 0 10)] (json/write-str (concat (map (fn [x] {:title "Boat Reserved", :start (ftime/unparse (ftime/formatters :date) x) }) (db-read-dtobjs "reservations" start end)) ; example of other types of events currently not being captured ; (map (fn [x] ; {:title "Bareboat", ; :start (ftime/unparse ; (ftime/formatters ; :date) ; x) ; }) ; (db-read-dtobjs "bareboat" start end)) (map (fn [x] {:title "Track", :start x }) (trdb-read-dtobjs "tracks" start end)))) )) ;;; ;;; Compojure Routing ;;; (cpj/defroutes app-routes (cpj/HEAD "/" [] "") (cpj/GET "/" [] (handler-get-index)) (cpj/GET "/track" {params :query-params} (handler-get-track params)) (cpj/GET "/events" {params :query-params} (handler-get-events params)) (cpjroute/files "/") (cpjroute/resources "/") (cpjroute/not-found "Not found.") ) ;; start nREPL server (defonce server (nrepl/start-server :port 7888)) ;; generated by 'lein ring new' (def app (ring/wrap-defaults app-routes ring/site-defaults) ) ;;; EOF
true
(ns rhoda-test-clojure.handler (:require [nrepl.server :as nrepl] [compojure.core :as cpj] [compojure.route :as cpjroute] [ring.middleware.defaults :as ring] [net.cgrand.enlive-html :as enlive] [clj-time.core :as time] [clj-time.format :as ftime] [clj-time.coerce :as ctime] [clojure.java.jdbc :as jdbc] [clojure.data.json :as json] [clojure.java.io :as io] [monger.core :as mg] [monger.credentials :as mcr] [monger.collection :as mc] [monger.operators :refer :all] )) ;;; ;;; Static parameters ;;; (def timezone "America/Los_Angeles") (def gmaps-key (System/getenv "GMAPS_KEY")) ;;; ;;; SQL database of reservations ;;; ; OLD MySQL database specs for OpenShift or local ; ;(def dbspec ; (if-let [host (System/getenv "MYSQL_55_RHEL7_SERVICE_HOST")] ; {:subprotocol "mysql" ; :subname (str ; "//" ; host ; ":" ; (System/getenv "MYSQL_55_RHEL7_SERVICE_PORT") ; "/testendpoint") ; :user "testusr" ; :password "PI:PASSWORD:<PASSWORD>END_PI" ; } ; (if-let [host (System/getenv "MYSQL_SERVICE_HOST")] ; {:subprotocol "mysql" ; :subname (str ; "//" ; host ; ":" ; (System/getenv "MYSQL_SERVICE_PORT") ; "/testendpoint") ; :user "testusr" ; :password "PI:PASSWORD:<PASSWORD>END_PI" ; } ; {:subprotocol "mysql" ; :subname "//localhost:3306/testendpoint" ; :user "testusr" ; :password "PI:PASSWORD:<PASSWORD>END_PI" ; } ; ))) ; NEW Postgres spec for Crunchy Bridge on OpenShift or local ; ; TODO: get RHODA bindings from injected Service Bindings (def dbspec (if-let [host (System/getenv "PGHOST")] {:dbtype "postgresql" :dbname (System/getenv "PGDB") :host (System/getenv "PGHOST") ; host :user (System/getenv "PGUSER") :password (System/getenv "PGPI:PASSWORD:<PASSWORD>END_PI") :ssl true :sslmode "require" } {:subprotocol "mysql" :subname "//localhost:3306/testendpoint" :user "testusr" :password "PI:PASSWORD:<PASSWORD>END_PI" } )) ;;; ;;; MongoDB of sailing tracks ;;; ; OLD: connection to in-cluster MongoDB ;(def mgconn ; (if-let [host (System/getenv "MONGODB_26_RHEL7_SERVICE_HOST")] ; (let [port (Integer/parseInt ; (System/getenv ; "MONGODB_26_RHEL7_SERVICE_PORT")) ; uname "testusr" ; dbname "tracks" ; pwd-raw "PI:PASSWORD:<PASSWORD>END_PI" ; pwd (.toCharArray pwd-raw) ; creds (mcr/create uname dbname pwd)] ; (mg/connect-with-credentials host port creds)) ; (if-let [host (System/getenv "MONGODB_SERVICE_HOST")] ; (let [port (Integer/parseInt ; (System/getenv ; "MONGODB_SERVICE_PORT")) ; uname "testusr" ; dbname "tracks" ; pwd-raw "PI:PASSWORD:<PASSWORD>END_PI" ; pwd (.toCharArray pwd-raw) ; creds (mcr/create uname dbname pwd)] ; (mg/connect-with-credentials host port creds)) ; (mg/connect) ; ))) ; ;(def mgdb (mg/get-db mgconn "mystrk")) ; TODO: get creds from OpenShift Service Binding ;(def atlas-cred-dir "/bindings/cpjdb1-d-cluster0-26b73026be-dbsc") ;(def atlas-username (slurp (str atlas-cred-dir "/username"))) ;(def atlas-password (slurp (str atlas-cred-dir "/password"))) ;(def atlas-host (slurp (str atlas-cred-dir "/host"))) ;(def atlas-db "mystrk") (def atlas-username (System/getenv "ATLAS_USERNAME")) (def atlas-password (System/getenv "ATLAS_PASSWORD")) (def atlas-host (System/getenv "ATLAS_HOST")) (def atlas-db (System/getenv "ATLAS_DB")) (def mgdb (:db (mg/connect-via-uri (str "mongodb+srv://" atlas-username ":" atlas-passwordPI:PASSWORD:<PASSWORD>END_PI "@" atlas-host "/" atlas-db)))) ;;; ;;; Date/Time utilities ;;; (defn sqldtobj-to-dtobj [sqldtobj] (time/to-time-zone (ctime/from-sql-time sqldtobj) (time/time-zone-for-id timezone))) ;;; ;;; Database read functions ;;; ; reservations and other 'events' from SQL database ; Postgres needs TIMESTAMP cast to make this work, unlike MySQL (defn db-read-dtobjs [table start-dtstr end-dtstr] (let [qstr (str "SELECT DISTINCT res_date " "FROM " table " WHERE CAST (res_date AS TIMESTAMP) >= " "CAST ('" start-dtstr "' AS TIMESTAMP) " "AND CAST (res_date AS TIMESTAMP) <= " "CAST ('" end-dtstr "' AS TIMESTAMP)" )] (map (fn [x] (sqldtobj-to-dtobj (:res_date x))) (try (jdbc/query dbspec [qstr]) (catch org.postgresql.util.PSQLException e (println qstr (ex-message e))))) )) ; sailing tracks from MongoDB ; fix to filter date >= datestr; currently returns all tracks ever (defn trdb-read-dtobjs [coll start-dtstr end-dtstr] (map (fn [x] (:date x)) (mc/find-maps mgdb coll)) ) ;;; ;;; Enlive - Clojure HTML templating ;;; ;;; for index, simply show index.html with vars replaced (enlive/deftemplate index "rhoda_test_clojure/index.html" [] [:#gmap] (enlive/replace-vars {:gmapskey gmaps-key}) ) ;;; ;;; Handlers for Compojure - Clojure web app routing ;;; ;;; main calendar page - enlive displays index.html SPA (defn handler-get-index [] (index) ) (defn handler-get-track [params] (let [trdate (get params "date") rawTrack (mc/find-one-as-map mgdb "tracks" {:date trdate}) ] (if rawTrack (json/write-str (:points rawTrack)) (json/write-str '[])) ) ) ;;; REST API for AJAX call to get dates as JSON ;;; returns array of e.g. {:title "Mys Rsvd" :start "2021-12-10"} (defn handler-get-events [params] (let [start (subs (get params "start" "2021-12-01") 0 10) end (subs (get params "end" "2021-12-31") 0 10)] (json/write-str (concat (map (fn [x] {:title "Boat Reserved", :start (ftime/unparse (ftime/formatters :date) x) }) (db-read-dtobjs "reservations" start end)) ; example of other types of events currently not being captured ; (map (fn [x] ; {:title "Bareboat", ; :start (ftime/unparse ; (ftime/formatters ; :date) ; x) ; }) ; (db-read-dtobjs "bareboat" start end)) (map (fn [x] {:title "Track", :start x }) (trdb-read-dtobjs "tracks" start end)))) )) ;;; ;;; Compojure Routing ;;; (cpj/defroutes app-routes (cpj/HEAD "/" [] "") (cpj/GET "/" [] (handler-get-index)) (cpj/GET "/track" {params :query-params} (handler-get-track params)) (cpj/GET "/events" {params :query-params} (handler-get-events params)) (cpjroute/files "/") (cpjroute/resources "/") (cpjroute/not-found "Not found.") ) ;; start nREPL server (defonce server (nrepl/start-server :port 7888)) ;; generated by 'lein ring new' (def app (ring/wrap-defaults app-routes ring/site-defaults) ) ;;; EOF
[ { "context": "; Copyright (c) Gunnar Völkel. All rights reserved.\n; The use and distribution ", "end": 29, "score": 0.9998405575752258, "start": 16, "tag": "NAME", "value": "Gunnar Völkel" } ]
data/test/clojure/e3dc52d8f4cab21d94c5cc87de6b692d75979e59stream_freezer.clj
harshp8l/deep-learning-lang-detection
84
; Copyright (c) Gunnar Völkel. 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-v1.0.txt 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 frost.stream-freezer (:require [clojure.java.io :as io] [clojure.options :refer [defn+opts, defn+opts-, ->option-map]] [frost.util :refer [conditional-wrap]] [frost.version :as v] [frost.kryo :as kryo] [frost.compression :as compress]) (:import (java.io Closeable EOFException OutputStream InputStream DataOutputStream DataInputStream) (com.esotericsoftware.kryo Kryo KryoException) (com.esotericsoftware.kryo.io Output Input))) (defprotocol IFreeze (freeze [this, obj] "Serialize a given object.")) (defprotocol IDefrost (defrost [this] "Deserialize the next object.")) (deftype StreamFreezer [^Kryo kryo, ^Output out, locking?] Closeable (close [this] (conditional-wrap locking? (locking this %) (.flush out) (.close out))) IFreeze (freeze [this, obj] (conditional-wrap locking? (locking this %) (.writeClassAndObject kryo, out, obj) (.flush out)))) (defn+opts ^StreamFreezer create-freezer "Creates a stream freezer to serialize data into the given output stream. The stream freezer can use compression. The stream freezer can be created in a thread-safe or non-thread-safe mode. <compressed>Specifies whether compression of the data is used.</> <locking>Determines whether locking should be use to make the stream freezer thread-safe.</> " [^OutputStream output-stream | {compressed false, locking true} :as options] ; create kryo configured by given parameters (let [kryo (kryo/create-specified-kryo options), output-stream (cond-> output-stream ; activate compression if specified compressed (compress/wrap-compression options))] (StreamFreezer. kryo, (Output. ^OutputStream output-stream), locking))) (deftype StreamDefroster [^Kryo kryo, ^Input in, locking?] Closeable (close [this] (conditional-wrap locking? (locking this %) (.close in))) IDefrost (defrost [this] (conditional-wrap locking? (locking this %) (.readClassAndObject kryo, in)))) (defn+opts ^StreamDefroster create-defroster "Creates a stream defroster to read data from the given stream. The stream defroster can be created in a thread-safe or non-thread-safe mode. <compressed>Specifies whether compression of the data is used.</> <locking>Determines whether locking should be use to make the stream freezer thread-safe.</>" [^InputStream input-stream | {compressed false, locking true} :as options] ; create kryo configured by given parameters (let [kryo (kryo/create-specified-kryo options), input-stream (cond-> input-stream ; activate compression if specified compressed (compress/wrap-compression options))] (StreamDefroster. kryo, (Input. ^InputStream input-stream), locking)))
33328
; 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-v1.0.txt 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 frost.stream-freezer (:require [clojure.java.io :as io] [clojure.options :refer [defn+opts, defn+opts-, ->option-map]] [frost.util :refer [conditional-wrap]] [frost.version :as v] [frost.kryo :as kryo] [frost.compression :as compress]) (:import (java.io Closeable EOFException OutputStream InputStream DataOutputStream DataInputStream) (com.esotericsoftware.kryo Kryo KryoException) (com.esotericsoftware.kryo.io Output Input))) (defprotocol IFreeze (freeze [this, obj] "Serialize a given object.")) (defprotocol IDefrost (defrost [this] "Deserialize the next object.")) (deftype StreamFreezer [^Kryo kryo, ^Output out, locking?] Closeable (close [this] (conditional-wrap locking? (locking this %) (.flush out) (.close out))) IFreeze (freeze [this, obj] (conditional-wrap locking? (locking this %) (.writeClassAndObject kryo, out, obj) (.flush out)))) (defn+opts ^StreamFreezer create-freezer "Creates a stream freezer to serialize data into the given output stream. The stream freezer can use compression. The stream freezer can be created in a thread-safe or non-thread-safe mode. <compressed>Specifies whether compression of the data is used.</> <locking>Determines whether locking should be use to make the stream freezer thread-safe.</> " [^OutputStream output-stream | {compressed false, locking true} :as options] ; create kryo configured by given parameters (let [kryo (kryo/create-specified-kryo options), output-stream (cond-> output-stream ; activate compression if specified compressed (compress/wrap-compression options))] (StreamFreezer. kryo, (Output. ^OutputStream output-stream), locking))) (deftype StreamDefroster [^Kryo kryo, ^Input in, locking?] Closeable (close [this] (conditional-wrap locking? (locking this %) (.close in))) IDefrost (defrost [this] (conditional-wrap locking? (locking this %) (.readClassAndObject kryo, in)))) (defn+opts ^StreamDefroster create-defroster "Creates a stream defroster to read data from the given stream. The stream defroster can be created in a thread-safe or non-thread-safe mode. <compressed>Specifies whether compression of the data is used.</> <locking>Determines whether locking should be use to make the stream freezer thread-safe.</>" [^InputStream input-stream | {compressed false, locking true} :as options] ; create kryo configured by given parameters (let [kryo (kryo/create-specified-kryo options), input-stream (cond-> input-stream ; activate compression if specified compressed (compress/wrap-compression options))] (StreamDefroster. kryo, (Input. ^InputStream input-stream), locking)))
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-v1.0.txt 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 frost.stream-freezer (:require [clojure.java.io :as io] [clojure.options :refer [defn+opts, defn+opts-, ->option-map]] [frost.util :refer [conditional-wrap]] [frost.version :as v] [frost.kryo :as kryo] [frost.compression :as compress]) (:import (java.io Closeable EOFException OutputStream InputStream DataOutputStream DataInputStream) (com.esotericsoftware.kryo Kryo KryoException) (com.esotericsoftware.kryo.io Output Input))) (defprotocol IFreeze (freeze [this, obj] "Serialize a given object.")) (defprotocol IDefrost (defrost [this] "Deserialize the next object.")) (deftype StreamFreezer [^Kryo kryo, ^Output out, locking?] Closeable (close [this] (conditional-wrap locking? (locking this %) (.flush out) (.close out))) IFreeze (freeze [this, obj] (conditional-wrap locking? (locking this %) (.writeClassAndObject kryo, out, obj) (.flush out)))) (defn+opts ^StreamFreezer create-freezer "Creates a stream freezer to serialize data into the given output stream. The stream freezer can use compression. The stream freezer can be created in a thread-safe or non-thread-safe mode. <compressed>Specifies whether compression of the data is used.</> <locking>Determines whether locking should be use to make the stream freezer thread-safe.</> " [^OutputStream output-stream | {compressed false, locking true} :as options] ; create kryo configured by given parameters (let [kryo (kryo/create-specified-kryo options), output-stream (cond-> output-stream ; activate compression if specified compressed (compress/wrap-compression options))] (StreamFreezer. kryo, (Output. ^OutputStream output-stream), locking))) (deftype StreamDefroster [^Kryo kryo, ^Input in, locking?] Closeable (close [this] (conditional-wrap locking? (locking this %) (.close in))) IDefrost (defrost [this] (conditional-wrap locking? (locking this %) (.readClassAndObject kryo, in)))) (defn+opts ^StreamDefroster create-defroster "Creates a stream defroster to read data from the given stream. The stream defroster can be created in a thread-safe or non-thread-safe mode. <compressed>Specifies whether compression of the data is used.</> <locking>Determines whether locking should be use to make the stream freezer thread-safe.</>" [^InputStream input-stream | {compressed false, locking true} :as options] ; create kryo configured by given parameters (let [kryo (kryo/create-specified-kryo options), input-stream (cond-> input-stream ; activate compression if specified compressed (compress/wrap-compression options))] (StreamDefroster. kryo, (Input. ^InputStream input-stream), locking)))
[ { "context": "p library for Clojure\"\n :url \"https://github.com/t6/from-scala\"\n :license {:name \"MIT License\"\n ", "end": 125, "score": 0.8109715580940247, "start": 123, "tag": "USERNAME", "value": "t6" }, { "context": " for Clojure\"\n :author \"Tobias Kortkamp\"\n :email \"tobias.kortk", "end": 991, "score": 0.9998913407325745, "start": 976, "tag": "NAME", "value": "Tobias Kortkamp" }, { "context": "ias Kortkamp\"\n :email \"tobias.kortkamp@gmail.com\"}}}\n :dependencies [[funcool/cats \"1.2.1\"\n ", "end": 1054, "score": 0.9999206066131592, "start": 1029, "tag": "EMAIL", "value": "tobias.kortkamp@gmail.com" } ]
project.clj
t6/from-scala
66
(defproject t6/from-scala "0.3.1-SNAPSHOT" :description "A Scala interop library for Clojure" :url "https://github.com/t6/from-scala" :license {:name "MIT License" :url "http://www.opensource.org/licenses/mit-license.php"} :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]] :profiles {:scala2.10 {:dependencies [[org.scala-lang/scala-library "2.10.4"]]} :dev {:dependencies [[org.clojure/clojure "1.8.0"] [org.scala-lang/scala-library "2.11.6"] [midje "1.6.3"]] :plugins [[lein-midje-doc "0.0.24"] [lein-midje "3.1.3"]]}} :documentation {:files {"doc/index" {:input "test/t6/from_scala/guide.clj" :title "from-scala" :sub-title "A Scala interop library for Clojure" :author "Tobias Kortkamp" :email "tobias.kortkamp@gmail.com"}}} :dependencies [[funcool/cats "1.2.1" :exclusions [com.keminglabs/cljx org.clojure/clojurescript]] [potemkin "0.4.3"]] :aliases {"test-all" ["do" "midje," "with-profile" "+scala2.10" "midje"]})
33942
(defproject t6/from-scala "0.3.1-SNAPSHOT" :description "A Scala interop library for Clojure" :url "https://github.com/t6/from-scala" :license {:name "MIT License" :url "http://www.opensource.org/licenses/mit-license.php"} :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]] :profiles {:scala2.10 {:dependencies [[org.scala-lang/scala-library "2.10.4"]]} :dev {:dependencies [[org.clojure/clojure "1.8.0"] [org.scala-lang/scala-library "2.11.6"] [midje "1.6.3"]] :plugins [[lein-midje-doc "0.0.24"] [lein-midje "3.1.3"]]}} :documentation {:files {"doc/index" {:input "test/t6/from_scala/guide.clj" :title "from-scala" :sub-title "A Scala interop library for Clojure" :author "<NAME>" :email "<EMAIL>"}}} :dependencies [[funcool/cats "1.2.1" :exclusions [com.keminglabs/cljx org.clojure/clojurescript]] [potemkin "0.4.3"]] :aliases {"test-all" ["do" "midje," "with-profile" "+scala2.10" "midje"]})
true
(defproject t6/from-scala "0.3.1-SNAPSHOT" :description "A Scala interop library for Clojure" :url "https://github.com/t6/from-scala" :license {:name "MIT License" :url "http://www.opensource.org/licenses/mit-license.php"} :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]] :profiles {:scala2.10 {:dependencies [[org.scala-lang/scala-library "2.10.4"]]} :dev {:dependencies [[org.clojure/clojure "1.8.0"] [org.scala-lang/scala-library "2.11.6"] [midje "1.6.3"]] :plugins [[lein-midje-doc "0.0.24"] [lein-midje "3.1.3"]]}} :documentation {:files {"doc/index" {:input "test/t6/from_scala/guide.clj" :title "from-scala" :sub-title "A Scala interop library for Clojure" :author "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}}} :dependencies [[funcool/cats "1.2.1" :exclusions [com.keminglabs/cljx org.clojure/clojurescript]] [potemkin "0.4.3"]] :aliases {"test-all" ["do" "midje," "with-profile" "+scala2.10" "midje"]})
[ { "context": "sitional Logic, tests\n\n; Copyright (c) 2014 - 2017 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 95, "score": 0.9998683929443359, "start": 81, "tag": "NAME", "value": "Burkhardt Renz" } ]
test/lwb/prop/sat_test.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Propositional Logic, tests ; Copyright (c) 2014 - 2017 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.prop.sat-test (:require [clojure.test :refer :all] [lwb.prop :refer :all] [lwb.prop.sat :refer :all] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as stest])) (stest/instrument) ; dimacs -------------------------------------------------------------- (deftest cl->dimacs-test (is (= #{1 2} (#'lwb.prop.sat/cl->dimacs '(or P Q) '{P 1 Q 2}))) (is (= #{-1 2} (#'lwb.prop.sat/cl->dimacs '(or (not P) Q) '{P 1 Q 2}))) (is (= #{-1 -2} (#'lwb.prop.sat/cl->dimacs '(or (not P) (not Q)) '{P 1 Q 2}))) ) (deftest cnf->dimacs-test (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R)))))) (is (= {:formula '(and (or P Q) (or (not Q) R)), :num-atoms 3, :int-atoms '{1 P, 2 Q, 3 R}, :num-cl 2, :cl-set #{#{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R))))) (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)))))) (is (= {:formula '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)), :num-atoms 5, :int-atoms '{1 P, 2 Q, 3 R, 4 S, 5 T}, :num-cl 3, :cl-set #{#{4 -3 -5} #{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S))))) ) ; sat4j --------------------------------------------------------------- (deftest sat4j-solve-test (is (= true (s/valid? :lwb.prop/model (sat4j-solve (cnf->dimacs '(and (or P Q) (or (not Q) R))))))) (is (= true (s/valid? nil? (sat4j-solve (cnf->dimacs '(and (or P) (or (not P)))))))) ) ; tseitin ------------------------------------------------------------- (deftest tseitin-test (is (= (tseitin '(impl (and P Q) T)) '(and (or ts-1) (or T (not ts-2) (not ts-1)) (or ts-2 ts-1) (or ts-1 (not T)) (or P (not ts-2)) (or Q (not ts-2)) (or ts-2 (not Q) (not P))))) (is (= (tseitin '(or P1 (and P2 (impl P3 P4)))) '(and (or ts-1) (or ts-2 P1 (not ts-1)) (or ts-1 (not P1)) (or ts-1 (not ts-2)) (or P2 (not ts-2)) (or ts-3 (not ts-2)) (or ts-2 (not ts-3) (not P2)) (or P4 (not ts-3) (not P3)) (or ts-3 P3) (or ts-3 (not P4))))) ) ; sat ----------------------------------------------------------------- (deftest sat-test (is (= (sat '(and P Q)) '{P true Q true})) (is (= (sat '(and P Q R S)) '{P true Q true R true S true})) (is (= (sat '(or P1 (and P2 (impl P3 P4)))) '{P1 false P2 true P3 false P4 false})) ) ; sat? ---------------------------------------------------------------- (deftest sat?-test (is (= true (sat? '(and P Q)))) (is (= true (sat? '(or P Q)))) (is (= true (sat? '(impl P Q)))) (is (= true (sat? '(equiv P Q)))) (is (= true (sat? '(xor P Q)))) (is (= true (sat? '(ite P Q R)))) (is (= true (sat? '(or (ite P Q R) (impl P Q) (and R S))))) (is (= false (sat? '(and P Q (not P))))) ) ; valid? -------------------------------------------------------------- (deftest valid?-test (is (= true (valid? '(or P (not P))))) (is (= false (valid? '(or P Q)))) ) (run-tests)
87764
; lwb Logic WorkBench -- Propositional Logic, tests ; Copyright (c) 2014 - 2017 <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.prop.sat-test (:require [clojure.test :refer :all] [lwb.prop :refer :all] [lwb.prop.sat :refer :all] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as stest])) (stest/instrument) ; dimacs -------------------------------------------------------------- (deftest cl->dimacs-test (is (= #{1 2} (#'lwb.prop.sat/cl->dimacs '(or P Q) '{P 1 Q 2}))) (is (= #{-1 2} (#'lwb.prop.sat/cl->dimacs '(or (not P) Q) '{P 1 Q 2}))) (is (= #{-1 -2} (#'lwb.prop.sat/cl->dimacs '(or (not P) (not Q)) '{P 1 Q 2}))) ) (deftest cnf->dimacs-test (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R)))))) (is (= {:formula '(and (or P Q) (or (not Q) R)), :num-atoms 3, :int-atoms '{1 P, 2 Q, 3 R}, :num-cl 2, :cl-set #{#{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R))))) (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)))))) (is (= {:formula '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)), :num-atoms 5, :int-atoms '{1 P, 2 Q, 3 R, 4 S, 5 T}, :num-cl 3, :cl-set #{#{4 -3 -5} #{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S))))) ) ; sat4j --------------------------------------------------------------- (deftest sat4j-solve-test (is (= true (s/valid? :lwb.prop/model (sat4j-solve (cnf->dimacs '(and (or P Q) (or (not Q) R))))))) (is (= true (s/valid? nil? (sat4j-solve (cnf->dimacs '(and (or P) (or (not P)))))))) ) ; tseitin ------------------------------------------------------------- (deftest tseitin-test (is (= (tseitin '(impl (and P Q) T)) '(and (or ts-1) (or T (not ts-2) (not ts-1)) (or ts-2 ts-1) (or ts-1 (not T)) (or P (not ts-2)) (or Q (not ts-2)) (or ts-2 (not Q) (not P))))) (is (= (tseitin '(or P1 (and P2 (impl P3 P4)))) '(and (or ts-1) (or ts-2 P1 (not ts-1)) (or ts-1 (not P1)) (or ts-1 (not ts-2)) (or P2 (not ts-2)) (or ts-3 (not ts-2)) (or ts-2 (not ts-3) (not P2)) (or P4 (not ts-3) (not P3)) (or ts-3 P3) (or ts-3 (not P4))))) ) ; sat ----------------------------------------------------------------- (deftest sat-test (is (= (sat '(and P Q)) '{P true Q true})) (is (= (sat '(and P Q R S)) '{P true Q true R true S true})) (is (= (sat '(or P1 (and P2 (impl P3 P4)))) '{P1 false P2 true P3 false P4 false})) ) ; sat? ---------------------------------------------------------------- (deftest sat?-test (is (= true (sat? '(and P Q)))) (is (= true (sat? '(or P Q)))) (is (= true (sat? '(impl P Q)))) (is (= true (sat? '(equiv P Q)))) (is (= true (sat? '(xor P Q)))) (is (= true (sat? '(ite P Q R)))) (is (= true (sat? '(or (ite P Q R) (impl P Q) (and R S))))) (is (= false (sat? '(and P Q (not P))))) ) ; valid? -------------------------------------------------------------- (deftest valid?-test (is (= true (valid? '(or P (not P))))) (is (= false (valid? '(or P Q)))) ) (run-tests)
true
; lwb Logic WorkBench -- Propositional Logic, tests ; Copyright (c) 2014 - 2017 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.prop.sat-test (:require [clojure.test :refer :all] [lwb.prop :refer :all] [lwb.prop.sat :refer :all] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as stest])) (stest/instrument) ; dimacs -------------------------------------------------------------- (deftest cl->dimacs-test (is (= #{1 2} (#'lwb.prop.sat/cl->dimacs '(or P Q) '{P 1 Q 2}))) (is (= #{-1 2} (#'lwb.prop.sat/cl->dimacs '(or (not P) Q) '{P 1 Q 2}))) (is (= #{-1 -2} (#'lwb.prop.sat/cl->dimacs '(or (not P) (not Q)) '{P 1 Q 2}))) ) (deftest cnf->dimacs-test (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R)))))) (is (= {:formula '(and (or P Q) (or (not Q) R)), :num-atoms 3, :int-atoms '{1 P, 2 Q, 3 R}, :num-cl 2, :cl-set #{#{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R))))) (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)))))) (is (= {:formula '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)), :num-atoms 5, :int-atoms '{1 P, 2 Q, 3 R, 4 S, 5 T}, :num-cl 3, :cl-set #{#{4 -3 -5} #{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S))))) ) ; sat4j --------------------------------------------------------------- (deftest sat4j-solve-test (is (= true (s/valid? :lwb.prop/model (sat4j-solve (cnf->dimacs '(and (or P Q) (or (not Q) R))))))) (is (= true (s/valid? nil? (sat4j-solve (cnf->dimacs '(and (or P) (or (not P)))))))) ) ; tseitin ------------------------------------------------------------- (deftest tseitin-test (is (= (tseitin '(impl (and P Q) T)) '(and (or ts-1) (or T (not ts-2) (not ts-1)) (or ts-2 ts-1) (or ts-1 (not T)) (or P (not ts-2)) (or Q (not ts-2)) (or ts-2 (not Q) (not P))))) (is (= (tseitin '(or P1 (and P2 (impl P3 P4)))) '(and (or ts-1) (or ts-2 P1 (not ts-1)) (or ts-1 (not P1)) (or ts-1 (not ts-2)) (or P2 (not ts-2)) (or ts-3 (not ts-2)) (or ts-2 (not ts-3) (not P2)) (or P4 (not ts-3) (not P3)) (or ts-3 P3) (or ts-3 (not P4))))) ) ; sat ----------------------------------------------------------------- (deftest sat-test (is (= (sat '(and P Q)) '{P true Q true})) (is (= (sat '(and P Q R S)) '{P true Q true R true S true})) (is (= (sat '(or P1 (and P2 (impl P3 P4)))) '{P1 false P2 true P3 false P4 false})) ) ; sat? ---------------------------------------------------------------- (deftest sat?-test (is (= true (sat? '(and P Q)))) (is (= true (sat? '(or P Q)))) (is (= true (sat? '(impl P Q)))) (is (= true (sat? '(equiv P Q)))) (is (= true (sat? '(xor P Q)))) (is (= true (sat? '(ite P Q R)))) (is (= true (sat? '(or (ite P Q R) (impl P Q) (and R S))))) (is (= false (sat? '(and P Q (not P))))) ) ; valid? -------------------------------------------------------------- (deftest valid?-test (is (= true (valid? '(or P (not P))))) (is (= false (valid? '(or P Q)))) ) (run-tests)
[ { "context": " rando (new Random))\n(def ^{:private true} idkey \"nextid\")\n(def ^{:private true} epochStart 1387263000)\n\n(", "end": 522, "score": 0.8843504786491394, "start": 516, "tag": "KEY", "value": "nextid" } ]
src/nooz/crypto.clj
codeslinger/nooz
1
(ns nooz.crypto (:require [ring.util.codec :as codec] [clojure.string :as s] [redis.core :as redis] [nooz.time :as nt] [nooz.db :as db]) (:import org.mindrot.jbcrypt.BCrypt java.security.SecureRandom java.security.MessageDigest java.math.BigInteger java.util.Random java.nio.ByteBuffer)) (def ^{:private true} seed-algorithm "SHA1PRNG") (def ^{:private true} rando (new Random)) (def ^{:private true} idkey "nextid") (def ^{:private true} epochStart 1387263000) (defn gen-salt "Generate a salt for BCrypt's hashing routines." ([] (BCrypt/gensalt)) ([rounds] (BCrypt/gensalt rounds))) (defn gen-hash "Hash the given string with a generated or supplied salt. Uses BCrypt hashing algorithm. The given salt (if supplied) needs to be in a format acceptable by BCrypt. Its recommended one use `gen-salt` for generating salts." ([raw] (gen-hash (gen-salt) raw)) ([salt raw] (BCrypt/hashpw raw salt))) (defn compare-hashes "Compare a raw string with an already hashed string." [raw hashed] (BCrypt/checkpw raw hashed)) (defn gen-random-hash "Returns a random byte array of the specified size." [size] (let [seed (byte-array size)] (.nextBytes (SecureRandom/getInstance seed-algorithm) seed) seed)) (defn wrap-web-safe [raw] (s/replace (s/replace (s/replace raw "+" "-") "/" "_") "=" "")) (defn unwrap-web-safe [wrapped] (let [unwrapped (s/replace (s/replace wrapped "_" "/") "-" "+") eqs (seq (repeat (- 4 (rem (.length unwrapped) 4)) "="))] (s/join (flatten [unwrapped eqs])))) (defn md5 [input] (let [alg (doto (MessageDigest/getInstance "MD5") (.reset) (.update (.getBytes input)))] (.toString (new BigInteger 1 (.digest alg)) 16))) (defn gen-confirmation-token [] (let [hashbytes (gen-random-hash 16)] (wrap-web-safe (codec/base64-encode hashbytes)))) (defn long-to-web-safe [val] (let [b (. ByteBuffer allocate 8)] (.putLong b val) (wrap-web-safe (codec/base64-encode (.array b))))) (defn gen-id "Generate a random unique ID." ([] (let [ms (- (nt/long-now) epochStart) r (.nextLong rando) id (mod (redis/with-server db/prod-redis (redis/incr idkey)) 1024)] (long-to-web-safe (bit-or (bit-or (bit-shift-left (bit-and ms 0x000001FFFFFFFFFF) 23) (bit-shift-left (bit-and r 0x0000000000001FFF) 10)) (bit-and id 0x00000000000003FF))))))
49262
(ns nooz.crypto (:require [ring.util.codec :as codec] [clojure.string :as s] [redis.core :as redis] [nooz.time :as nt] [nooz.db :as db]) (:import org.mindrot.jbcrypt.BCrypt java.security.SecureRandom java.security.MessageDigest java.math.BigInteger java.util.Random java.nio.ByteBuffer)) (def ^{:private true} seed-algorithm "SHA1PRNG") (def ^{:private true} rando (new Random)) (def ^{:private true} idkey "<KEY>") (def ^{:private true} epochStart 1387263000) (defn gen-salt "Generate a salt for BCrypt's hashing routines." ([] (BCrypt/gensalt)) ([rounds] (BCrypt/gensalt rounds))) (defn gen-hash "Hash the given string with a generated or supplied salt. Uses BCrypt hashing algorithm. The given salt (if supplied) needs to be in a format acceptable by BCrypt. Its recommended one use `gen-salt` for generating salts." ([raw] (gen-hash (gen-salt) raw)) ([salt raw] (BCrypt/hashpw raw salt))) (defn compare-hashes "Compare a raw string with an already hashed string." [raw hashed] (BCrypt/checkpw raw hashed)) (defn gen-random-hash "Returns a random byte array of the specified size." [size] (let [seed (byte-array size)] (.nextBytes (SecureRandom/getInstance seed-algorithm) seed) seed)) (defn wrap-web-safe [raw] (s/replace (s/replace (s/replace raw "+" "-") "/" "_") "=" "")) (defn unwrap-web-safe [wrapped] (let [unwrapped (s/replace (s/replace wrapped "_" "/") "-" "+") eqs (seq (repeat (- 4 (rem (.length unwrapped) 4)) "="))] (s/join (flatten [unwrapped eqs])))) (defn md5 [input] (let [alg (doto (MessageDigest/getInstance "MD5") (.reset) (.update (.getBytes input)))] (.toString (new BigInteger 1 (.digest alg)) 16))) (defn gen-confirmation-token [] (let [hashbytes (gen-random-hash 16)] (wrap-web-safe (codec/base64-encode hashbytes)))) (defn long-to-web-safe [val] (let [b (. ByteBuffer allocate 8)] (.putLong b val) (wrap-web-safe (codec/base64-encode (.array b))))) (defn gen-id "Generate a random unique ID." ([] (let [ms (- (nt/long-now) epochStart) r (.nextLong rando) id (mod (redis/with-server db/prod-redis (redis/incr idkey)) 1024)] (long-to-web-safe (bit-or (bit-or (bit-shift-left (bit-and ms 0x000001FFFFFFFFFF) 23) (bit-shift-left (bit-and r 0x0000000000001FFF) 10)) (bit-and id 0x00000000000003FF))))))
true
(ns nooz.crypto (:require [ring.util.codec :as codec] [clojure.string :as s] [redis.core :as redis] [nooz.time :as nt] [nooz.db :as db]) (:import org.mindrot.jbcrypt.BCrypt java.security.SecureRandom java.security.MessageDigest java.math.BigInteger java.util.Random java.nio.ByteBuffer)) (def ^{:private true} seed-algorithm "SHA1PRNG") (def ^{:private true} rando (new Random)) (def ^{:private true} idkey "PI:KEY:<KEY>END_PI") (def ^{:private true} epochStart 1387263000) (defn gen-salt "Generate a salt for BCrypt's hashing routines." ([] (BCrypt/gensalt)) ([rounds] (BCrypt/gensalt rounds))) (defn gen-hash "Hash the given string with a generated or supplied salt. Uses BCrypt hashing algorithm. The given salt (if supplied) needs to be in a format acceptable by BCrypt. Its recommended one use `gen-salt` for generating salts." ([raw] (gen-hash (gen-salt) raw)) ([salt raw] (BCrypt/hashpw raw salt))) (defn compare-hashes "Compare a raw string with an already hashed string." [raw hashed] (BCrypt/checkpw raw hashed)) (defn gen-random-hash "Returns a random byte array of the specified size." [size] (let [seed (byte-array size)] (.nextBytes (SecureRandom/getInstance seed-algorithm) seed) seed)) (defn wrap-web-safe [raw] (s/replace (s/replace (s/replace raw "+" "-") "/" "_") "=" "")) (defn unwrap-web-safe [wrapped] (let [unwrapped (s/replace (s/replace wrapped "_" "/") "-" "+") eqs (seq (repeat (- 4 (rem (.length unwrapped) 4)) "="))] (s/join (flatten [unwrapped eqs])))) (defn md5 [input] (let [alg (doto (MessageDigest/getInstance "MD5") (.reset) (.update (.getBytes input)))] (.toString (new BigInteger 1 (.digest alg)) 16))) (defn gen-confirmation-token [] (let [hashbytes (gen-random-hash 16)] (wrap-web-safe (codec/base64-encode hashbytes)))) (defn long-to-web-safe [val] (let [b (. ByteBuffer allocate 8)] (.putLong b val) (wrap-web-safe (codec/base64-encode (.array b))))) (defn gen-id "Generate a random unique ID." ([] (let [ms (- (nt/long-now) epochStart) r (.nextLong rando) id (mod (redis/with-server db/prod-redis (redis/incr idkey)) 1024)] (long-to-web-safe (bit-or (bit-or (bit-shift-left (bit-and ms 0x000001FFFFFFFFFF) 23) (bit-shift-left (bit-and r 0x0000000000001FFF) 10)) (bit-and id 0x00000000000003FF))))))
[ { "context": "error-field\"\n recover-pass-ids [\"reset-password\"]\n query (:qu", "end": 3231, "score": 0.7934198379516602, "start": 3226, "tag": "PASSWORD", "value": "reset" }, { "context": " :username (get query \"username\")\n :activatio", "end": 3484, "score": 0.9986584186553955, "start": 3476, "tag": "USERNAME", "value": "username" } ]
src/cljs/clojurecademy/controller/auth.cljs
harunpehlivan/clojurecademy
651
(ns clojurecademy.controller.auth (:require [clojurecademy.validation :as validation] [clojurecademy.util :as util] [cemerick.url :as url])) (defn- signup-validations [data] [[(validation/email? (:email data)) "Email is invalid."] [(validation/username? (:username data)) "Username is invalid."] [(validation/password? (:password data)) "Password is invalid."]]) (defn signup [_] (let [signup-error-field-id "signup-error-field" signup-field-ids ["signup-username" "signup-password" "signup-email"] data (util/create-field-val-map signup-field-ids)] (when (util/valid-input? signup-error-field-id (signup-validations data)) (util/ajax :post "/signup" :data data :success #(util/change-url "/courses") :error (fn [{:keys [status response]}] (util/set-innerText! signup-error-field-id (:error response))))))) (defn- login-validations [data] [[((util/any-pred validation/username? validation/email?) (:username-or-email data)) "Username or email is invalid."] [(validation/password? (:password data)) "Password is invalid."]]) (defn login [_] (let [login-error-field-id "login-error-field" login-field-ids ["login-username-or-email" "login-password"] data (util/create-field-val-map login-field-ids)] (when (util/valid-input? login-error-field-id (login-validations data)) (util/ajax :put "/login" :data data :success #(util/change-url "/courses/learn") :error (fn [{:keys [status response]}] (util/show-error-text login-error-field-id (:error response)) (util/scroll-to-top)))))) (defn logout [_] (util/ajax :put "/logout" :success #(util/change-url "/") :error (fn [{:keys [status response]}] (util/show-error-text "user-update-error-field" (:error response)) (util/scroll-to-top)))) (defn- forgotpass-validations [data] [[(validation/email? (:forgot-pass-email data)) "Email is invalid."]]) (defn send-reset-pass-email [_] (let [forgot-pass-error-field "forgot-pass-error-field" forgot-pass-ids ["forgot-pass-email"] data (util/create-field-val-map forgot-pass-ids)] (when (util/valid-input? forgot-pass-error-field (forgotpass-validations data)) (util/ajax :put "/send-reset-password-activation" :data data :success #(do (util/show-success-text forgot-pass-error-field "Successfully sent recovery email.") (util/clear-input-fields ["forgot-pass-email"])) :error (fn [{:keys [status response]}] (util/show-error-text forgot-pass-error-field (:error response))))))) (defn- reset-password-validations [data] [[(validation/password? (:reset-password data)) "Password is invalid."]]) (defn reset-password [_] (let [reset-password-error-field "reset-password-error-field" recover-pass-ids ["reset-password"] query (:query (url/url (-> js/window .-location .-href))) data (assoc (util/create-field-val-map recover-pass-ids) :username (get query "username") :activation-key (get query "activation-key"))] (when (util/valid-input? reset-password-error-field (reset-password-validations data)) (util/ajax :put "/resetpassword" :data data :success (fn [_] (util/show-success-text reset-password-error-field "Password successfully updated.You will be redirected to login...") (js/setTimeout #(util/redirect! "/login") 2500)) :error (fn [{:keys [status response]}] (util/show-error-text reset-password-error-field (:error response)))))))
114295
(ns clojurecademy.controller.auth (:require [clojurecademy.validation :as validation] [clojurecademy.util :as util] [cemerick.url :as url])) (defn- signup-validations [data] [[(validation/email? (:email data)) "Email is invalid."] [(validation/username? (:username data)) "Username is invalid."] [(validation/password? (:password data)) "Password is invalid."]]) (defn signup [_] (let [signup-error-field-id "signup-error-field" signup-field-ids ["signup-username" "signup-password" "signup-email"] data (util/create-field-val-map signup-field-ids)] (when (util/valid-input? signup-error-field-id (signup-validations data)) (util/ajax :post "/signup" :data data :success #(util/change-url "/courses") :error (fn [{:keys [status response]}] (util/set-innerText! signup-error-field-id (:error response))))))) (defn- login-validations [data] [[((util/any-pred validation/username? validation/email?) (:username-or-email data)) "Username or email is invalid."] [(validation/password? (:password data)) "Password is invalid."]]) (defn login [_] (let [login-error-field-id "login-error-field" login-field-ids ["login-username-or-email" "login-password"] data (util/create-field-val-map login-field-ids)] (when (util/valid-input? login-error-field-id (login-validations data)) (util/ajax :put "/login" :data data :success #(util/change-url "/courses/learn") :error (fn [{:keys [status response]}] (util/show-error-text login-error-field-id (:error response)) (util/scroll-to-top)))))) (defn logout [_] (util/ajax :put "/logout" :success #(util/change-url "/") :error (fn [{:keys [status response]}] (util/show-error-text "user-update-error-field" (:error response)) (util/scroll-to-top)))) (defn- forgotpass-validations [data] [[(validation/email? (:forgot-pass-email data)) "Email is invalid."]]) (defn send-reset-pass-email [_] (let [forgot-pass-error-field "forgot-pass-error-field" forgot-pass-ids ["forgot-pass-email"] data (util/create-field-val-map forgot-pass-ids)] (when (util/valid-input? forgot-pass-error-field (forgotpass-validations data)) (util/ajax :put "/send-reset-password-activation" :data data :success #(do (util/show-success-text forgot-pass-error-field "Successfully sent recovery email.") (util/clear-input-fields ["forgot-pass-email"])) :error (fn [{:keys [status response]}] (util/show-error-text forgot-pass-error-field (:error response))))))) (defn- reset-password-validations [data] [[(validation/password? (:reset-password data)) "Password is invalid."]]) (defn reset-password [_] (let [reset-password-error-field "reset-password-error-field" recover-pass-ids ["<PASSWORD>-password"] query (:query (url/url (-> js/window .-location .-href))) data (assoc (util/create-field-val-map recover-pass-ids) :username (get query "username") :activation-key (get query "activation-key"))] (when (util/valid-input? reset-password-error-field (reset-password-validations data)) (util/ajax :put "/resetpassword" :data data :success (fn [_] (util/show-success-text reset-password-error-field "Password successfully updated.You will be redirected to login...") (js/setTimeout #(util/redirect! "/login") 2500)) :error (fn [{:keys [status response]}] (util/show-error-text reset-password-error-field (:error response)))))))
true
(ns clojurecademy.controller.auth (:require [clojurecademy.validation :as validation] [clojurecademy.util :as util] [cemerick.url :as url])) (defn- signup-validations [data] [[(validation/email? (:email data)) "Email is invalid."] [(validation/username? (:username data)) "Username is invalid."] [(validation/password? (:password data)) "Password is invalid."]]) (defn signup [_] (let [signup-error-field-id "signup-error-field" signup-field-ids ["signup-username" "signup-password" "signup-email"] data (util/create-field-val-map signup-field-ids)] (when (util/valid-input? signup-error-field-id (signup-validations data)) (util/ajax :post "/signup" :data data :success #(util/change-url "/courses") :error (fn [{:keys [status response]}] (util/set-innerText! signup-error-field-id (:error response))))))) (defn- login-validations [data] [[((util/any-pred validation/username? validation/email?) (:username-or-email data)) "Username or email is invalid."] [(validation/password? (:password data)) "Password is invalid."]]) (defn login [_] (let [login-error-field-id "login-error-field" login-field-ids ["login-username-or-email" "login-password"] data (util/create-field-val-map login-field-ids)] (when (util/valid-input? login-error-field-id (login-validations data)) (util/ajax :put "/login" :data data :success #(util/change-url "/courses/learn") :error (fn [{:keys [status response]}] (util/show-error-text login-error-field-id (:error response)) (util/scroll-to-top)))))) (defn logout [_] (util/ajax :put "/logout" :success #(util/change-url "/") :error (fn [{:keys [status response]}] (util/show-error-text "user-update-error-field" (:error response)) (util/scroll-to-top)))) (defn- forgotpass-validations [data] [[(validation/email? (:forgot-pass-email data)) "Email is invalid."]]) (defn send-reset-pass-email [_] (let [forgot-pass-error-field "forgot-pass-error-field" forgot-pass-ids ["forgot-pass-email"] data (util/create-field-val-map forgot-pass-ids)] (when (util/valid-input? forgot-pass-error-field (forgotpass-validations data)) (util/ajax :put "/send-reset-password-activation" :data data :success #(do (util/show-success-text forgot-pass-error-field "Successfully sent recovery email.") (util/clear-input-fields ["forgot-pass-email"])) :error (fn [{:keys [status response]}] (util/show-error-text forgot-pass-error-field (:error response))))))) (defn- reset-password-validations [data] [[(validation/password? (:reset-password data)) "Password is invalid."]]) (defn reset-password [_] (let [reset-password-error-field "reset-password-error-field" recover-pass-ids ["PI:PASSWORD:<PASSWORD>END_PI-password"] query (:query (url/url (-> js/window .-location .-href))) data (assoc (util/create-field-val-map recover-pass-ids) :username (get query "username") :activation-key (get query "activation-key"))] (when (util/valid-input? reset-password-error-field (reset-password-validations data)) (util/ajax :put "/resetpassword" :data data :success (fn [_] (util/show-success-text reset-password-error-field "Password successfully updated.You will be redirected to login...") (js/setTimeout #(util/redirect! "/login") 2500)) :error (fn [{:keys [status response]}] (util/show-error-text reset-password-error-field (:error response)))))))
[ { "context": " :joined 1\n :players (\\\"John\\\")\n :deck [\\\"♠A\\\" \\\"♥9\\\" \\\"♦6\\\" \\", "end": 191, "score": 0.9988102912902832, "start": 187, "tag": "NAME", "value": "John" } ]
src/cardgame/network/core.clj
ykarikos/cardgame
0
(ns cardgame.network.core "The network protocol format: {:command \"state\" :msg \"Joined.\"} :params {:game {:playercount 2 :joined 1 :players (\"John\") :deck [\"♠A\" \"♥9\" \"♦6\" \"♣K\"]}} " (:require [manifold.stream :as s] [cardgame.state :as state] [aleph.http :as http] [clojure.data.json :as json])) (def port 9876) (defn parse-json [s] (try (json/read-str s :key-fn keyword) (catch Exception e {}))) (defn get-consumer [executor] (fn [data] ; (println "received" data) (let [json-data (parse-json data)] (state/print-msg (:msg json-data)) (executor json-data)))) (defn send-message [connection data] (s/put! connection (json/write-str data)))
3720
(ns cardgame.network.core "The network protocol format: {:command \"state\" :msg \"Joined.\"} :params {:game {:playercount 2 :joined 1 :players (\"<NAME>\") :deck [\"♠A\" \"♥9\" \"♦6\" \"♣K\"]}} " (:require [manifold.stream :as s] [cardgame.state :as state] [aleph.http :as http] [clojure.data.json :as json])) (def port 9876) (defn parse-json [s] (try (json/read-str s :key-fn keyword) (catch Exception e {}))) (defn get-consumer [executor] (fn [data] ; (println "received" data) (let [json-data (parse-json data)] (state/print-msg (:msg json-data)) (executor json-data)))) (defn send-message [connection data] (s/put! connection (json/write-str data)))
true
(ns cardgame.network.core "The network protocol format: {:command \"state\" :msg \"Joined.\"} :params {:game {:playercount 2 :joined 1 :players (\"PI:NAME:<NAME>END_PI\") :deck [\"♠A\" \"♥9\" \"♦6\" \"♣K\"]}} " (:require [manifold.stream :as s] [cardgame.state :as state] [aleph.http :as http] [clojure.data.json :as json])) (def port 9876) (defn parse-json [s] (try (json/read-str s :key-fn keyword) (catch Exception e {}))) (defn get-consumer [executor] (fn [data] ; (println "received" data) (let [json-data (parse-json data)] (state/print-msg (:msg json-data)) (executor json-data)))) (defn send-message [connection data] (s/put! connection (json/write-str data)))
[ { "context": ";; The MIT License (MIT)\n\n;; Copyright (c) 2016 Stuart Sierra\n\n;; Permission is hereby granted, free of charge,", "end": 61, "score": 0.9998409748077393, "start": 48, "tag": "NAME", "value": "Stuart Sierra" } ]
src/com/stuartsierra/mapgraph.cljc
vimsical/mapgraph
69
;; The MIT License (MIT) ;; Copyright (c) 2016 Stuart Sierra ;; 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 com.stuartsierra.mapgraph "An in-memory graph data store consisting of maps with links. ## Introduction This is a very basic database that stores entities. An *entity* is a Clojure map from *attributes* to values. An *attribute* is a keyword, usually namespace-qualified. An entity has exactly one *unique identity* attribute whose value acts as a globally-unique identifier for that entity. An entity may not have more than one unique identity attribute; if it does, the behavior is undefined. A *lookup ref* is a vector pair of a unique identity attribute and a value, such as `[:user/id 1234]`. The combination of a unique identity attribute and its value uniquely identifies a single entity in the database. ## Usage Create a new database with `new-db`. The schema of the database is the set of all unique identity attributes. `add-id-attr` extends the schema with a new unique identity attribute. `add` inserts entities in the database. Entities already in the database are updated as by `clojure.core/merge`. (To replace an entity without merging, `dissoc` it first.) All entites added to a database are automatically *normalized*: all nested entities are replaced with lookup refs to other entities in the database. Entity normalization recognizes the following forms: - any non-entity value, including collections - a single entity - a collection (list, vector, set) of entities - a map where keys are any type, vals are single entities Collection values may not mix entities and non-entities. Collections are searched only one layer deep: `add` will not recursively walk arbitrary data structures to search for entities to normalize. Databases can be manipulated with primitive map operations such as `get` and `dissoc`. Keep in mind that there are no indexes: If you `dissoc` an entity from the database you may leave behind broken links to that entity. To get nested maps back out, use `pull`, which follows a pull pattern to recursively expand entity lookup refs.") (defn- seek [pred s] (some #(when (pred %) %) s)) (defn- possible-entity-map? "True if x is a non-sorted map. This check prevents errors from trying to compare keywords with incompatible keys in sorted maps." [x] (and (map? x) (not (sorted? x)))) (defn- find-id-key "Returns the first identifier key found in map, or nil if it is not a valid entity map." [map id-attrs] (when (possible-entity-map? map) (seek #(contains? map %) id-attrs))) (defn- get-ref "Returns a lookup ref for the map, given a collection of identifier keys, or nil if the map does not have an identifier key." [map id-attrs] (when-let [k (find-id-key map id-attrs)] [k (get map k)])) (defn- keept "Like clojure.core/keep but preserves the types of vectors and sets, including sorted sets. If coll is a map, applies f to each value in the map and returns a map of the same (sorted) type." [f coll] (cond (vector? coll) (into [] (keep f) coll) (set? coll) (into (empty coll) (keep f) coll) (map? coll) (reduce-kv (fn [m k v] (if-let [vv (f v)] (assoc m k vv) m)) (empty coll) coll) :else (keep f coll))) (defn- like "Returns a collection of the same type as type-coll (vector, set, sequence) containing elements of sequence s." [type-coll s] (cond (vector? type-coll) (vec s) (set? type-coll) (into (empty type-coll) s) ; handles sorted-set :else s)) (defn- into! "Transient version of clojure.core/into" [to from] (reduce conj! to from)) (defn- update! "Transient version of clojure.core/update" [m k f x] (assoc! m k (f (get m k) x))) (defn- normalize-entities "Returns a sequence of normalized entities starting with map m." [m id-attrs] (lazy-seq (loop [sub-entities (transient []) normalized (transient {}) kvs (seq m)] (if-let [[k v] (first kvs)] (if (map? v) (if-let [r (get-ref v id-attrs)] ;; v is a single entity (recur (conj! sub-entities v) (assoc! normalized k r) (rest kvs)) ;; v is a map, not an entity (let [values (vals v)] (if-let [refs (seq (keep #(get-ref % id-attrs) values))] ;; v is a map whose values are entities (do (when-not (= (count refs) (count v)) (throw (ex-info "Map values may not mix entities and non-entities" {:reason ::mixed-map-vals ::attribute k ::value v}))) (recur (into! sub-entities values) (assoc! normalized k (into (empty v) ; preserve type (map vector (keys v) refs))) (rest kvs))) ;; v is a plain map (recur sub-entities (assoc! normalized k v) (rest kvs))))) ;; v is not a map (if (coll? v) (if-let [refs (seq (keep #(get-ref % id-attrs) v))] ;; v is a collection of entities (do (when-not (= (count refs) (count v)) (throw (ex-info "Collection values may not mix entities and non-entities" {:reason ::mixed-collection ::attribute k ::value v}))) (recur (into! sub-entities v) (assoc! normalized k (like v refs)) (rest kvs))) ;; v is a collection of non-entities (recur sub-entities (assoc! normalized k v) (rest kvs))) ;; v is a single non-entity (recur sub-entities (assoc! normalized k v) (rest kvs)))) (cons (persistent! normalized) (mapcat #(normalize-entities % id-attrs) (persistent! sub-entities))))))) (defn new-db "Returns a new, empty database value." [] {::id-attrs #{}}) (defn db? "Returns true if x is a mapgraph database." [x] (and (map? x) (set? (::id-attrs x)) (every? keyword? (::id-attrs x)))) (defn add-id-attr "Adds unique identity attributes to the db schema. Returns updated db." [db & id-keys] (update db ::id-attrs into id-keys)) (defn add "Returns updated db with normalized entities merged in." [db & entities] (let [id-attrs (::id-attrs db)] (persistent! (reduce (fn [db e] (let [ref (get-ref e id-attrs)] (update! db ref merge e))) (transient db) (mapcat #(normalize-entities % id-attrs) entities))))) (defn entity? "Returns true if map is an entity according to the db schema. An entity is a map from keywords to values with exactly one identifier key." [db map] (and (map? map) (every? keyword? (keys map)) (= 1 (count (filter #(contains? map %) (::id-attrs db)))))) (defn ref-to "Returns a lookup ref for the entity using the schema in db, or nil if not found. The db does not need to contain the entity." [db entity] (get-ref entity (::id-attrs db))) (defn ref? "Returns true if ref is a lookup ref according to the db schema." [db ref] (and (vector? ref) (= 2 (count ref)) (contains? (::id-attrs db) (first ref)))) (declare pull) (defn- pull-join "Executes a pull map expression on entity." [db result pull-map entity] (reduce-kv (fn [result k join-expr] (if-let [val (get entity k)] (if (ref? db val) (assoc result k (pull db join-expr val)) (do (when-not (coll? val) (throw (ex-info "pull map pattern must be to a lookup ref or a collection of lookup refs." {:reason ::pull-join-not-ref ::pull-map-pattern pull-map ::entity entity ::attribute k ::value val}))) (assoc result k (keept #(pull db join-expr %) val)))) ;; no value for key result)) result pull-map)) (defn pull "Returns a map representation of the entity found at lookup ref in db. Builds nested maps following a pull pattern. A pull pattern is a vector containing any of the following forms: :key If the entity contains :key, includes it in the result. '* (literal symbol asterisk) Includes all keys from the entity in the result. { :key sub-pattern } The entity's value for key is a lookup ref or collection of lookup refs. Expands each lookup ref to the entity it refers to, then applies pull to each of those entities using the sub-pattern." [db pattern lookup-ref] (when-let [entity (get db lookup-ref)] (reduce (fn [result expr] (cond (keyword? expr) (if-let [[_ val] (find entity expr)] (assoc result expr val) result) (map? expr) (pull-join db result expr entity) (= '* expr) ; don't re-merge things we already joined (merge result (apply dissoc entity (keys result))) :else (throw (ex-info "Invalid form in pull pattern" {:reason ::invalid-pull-form ::form expr ::pattern pattern ::lookup-ref lookup-ref})))) {} pattern)))
103902
;; The MIT License (MIT) ;; Copyright (c) 2016 <NAME> ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns com.stuartsierra.mapgraph "An in-memory graph data store consisting of maps with links. ## Introduction This is a very basic database that stores entities. An *entity* is a Clojure map from *attributes* to values. An *attribute* is a keyword, usually namespace-qualified. An entity has exactly one *unique identity* attribute whose value acts as a globally-unique identifier for that entity. An entity may not have more than one unique identity attribute; if it does, the behavior is undefined. A *lookup ref* is a vector pair of a unique identity attribute and a value, such as `[:user/id 1234]`. The combination of a unique identity attribute and its value uniquely identifies a single entity in the database. ## Usage Create a new database with `new-db`. The schema of the database is the set of all unique identity attributes. `add-id-attr` extends the schema with a new unique identity attribute. `add` inserts entities in the database. Entities already in the database are updated as by `clojure.core/merge`. (To replace an entity without merging, `dissoc` it first.) All entites added to a database are automatically *normalized*: all nested entities are replaced with lookup refs to other entities in the database. Entity normalization recognizes the following forms: - any non-entity value, including collections - a single entity - a collection (list, vector, set) of entities - a map where keys are any type, vals are single entities Collection values may not mix entities and non-entities. Collections are searched only one layer deep: `add` will not recursively walk arbitrary data structures to search for entities to normalize. Databases can be manipulated with primitive map operations such as `get` and `dissoc`. Keep in mind that there are no indexes: If you `dissoc` an entity from the database you may leave behind broken links to that entity. To get nested maps back out, use `pull`, which follows a pull pattern to recursively expand entity lookup refs.") (defn- seek [pred s] (some #(when (pred %) %) s)) (defn- possible-entity-map? "True if x is a non-sorted map. This check prevents errors from trying to compare keywords with incompatible keys in sorted maps." [x] (and (map? x) (not (sorted? x)))) (defn- find-id-key "Returns the first identifier key found in map, or nil if it is not a valid entity map." [map id-attrs] (when (possible-entity-map? map) (seek #(contains? map %) id-attrs))) (defn- get-ref "Returns a lookup ref for the map, given a collection of identifier keys, or nil if the map does not have an identifier key." [map id-attrs] (when-let [k (find-id-key map id-attrs)] [k (get map k)])) (defn- keept "Like clojure.core/keep but preserves the types of vectors and sets, including sorted sets. If coll is a map, applies f to each value in the map and returns a map of the same (sorted) type." [f coll] (cond (vector? coll) (into [] (keep f) coll) (set? coll) (into (empty coll) (keep f) coll) (map? coll) (reduce-kv (fn [m k v] (if-let [vv (f v)] (assoc m k vv) m)) (empty coll) coll) :else (keep f coll))) (defn- like "Returns a collection of the same type as type-coll (vector, set, sequence) containing elements of sequence s." [type-coll s] (cond (vector? type-coll) (vec s) (set? type-coll) (into (empty type-coll) s) ; handles sorted-set :else s)) (defn- into! "Transient version of clojure.core/into" [to from] (reduce conj! to from)) (defn- update! "Transient version of clojure.core/update" [m k f x] (assoc! m k (f (get m k) x))) (defn- normalize-entities "Returns a sequence of normalized entities starting with map m." [m id-attrs] (lazy-seq (loop [sub-entities (transient []) normalized (transient {}) kvs (seq m)] (if-let [[k v] (first kvs)] (if (map? v) (if-let [r (get-ref v id-attrs)] ;; v is a single entity (recur (conj! sub-entities v) (assoc! normalized k r) (rest kvs)) ;; v is a map, not an entity (let [values (vals v)] (if-let [refs (seq (keep #(get-ref % id-attrs) values))] ;; v is a map whose values are entities (do (when-not (= (count refs) (count v)) (throw (ex-info "Map values may not mix entities and non-entities" {:reason ::mixed-map-vals ::attribute k ::value v}))) (recur (into! sub-entities values) (assoc! normalized k (into (empty v) ; preserve type (map vector (keys v) refs))) (rest kvs))) ;; v is a plain map (recur sub-entities (assoc! normalized k v) (rest kvs))))) ;; v is not a map (if (coll? v) (if-let [refs (seq (keep #(get-ref % id-attrs) v))] ;; v is a collection of entities (do (when-not (= (count refs) (count v)) (throw (ex-info "Collection values may not mix entities and non-entities" {:reason ::mixed-collection ::attribute k ::value v}))) (recur (into! sub-entities v) (assoc! normalized k (like v refs)) (rest kvs))) ;; v is a collection of non-entities (recur sub-entities (assoc! normalized k v) (rest kvs))) ;; v is a single non-entity (recur sub-entities (assoc! normalized k v) (rest kvs)))) (cons (persistent! normalized) (mapcat #(normalize-entities % id-attrs) (persistent! sub-entities))))))) (defn new-db "Returns a new, empty database value." [] {::id-attrs #{}}) (defn db? "Returns true if x is a mapgraph database." [x] (and (map? x) (set? (::id-attrs x)) (every? keyword? (::id-attrs x)))) (defn add-id-attr "Adds unique identity attributes to the db schema. Returns updated db." [db & id-keys] (update db ::id-attrs into id-keys)) (defn add "Returns updated db with normalized entities merged in." [db & entities] (let [id-attrs (::id-attrs db)] (persistent! (reduce (fn [db e] (let [ref (get-ref e id-attrs)] (update! db ref merge e))) (transient db) (mapcat #(normalize-entities % id-attrs) entities))))) (defn entity? "Returns true if map is an entity according to the db schema. An entity is a map from keywords to values with exactly one identifier key." [db map] (and (map? map) (every? keyword? (keys map)) (= 1 (count (filter #(contains? map %) (::id-attrs db)))))) (defn ref-to "Returns a lookup ref for the entity using the schema in db, or nil if not found. The db does not need to contain the entity." [db entity] (get-ref entity (::id-attrs db))) (defn ref? "Returns true if ref is a lookup ref according to the db schema." [db ref] (and (vector? ref) (= 2 (count ref)) (contains? (::id-attrs db) (first ref)))) (declare pull) (defn- pull-join "Executes a pull map expression on entity." [db result pull-map entity] (reduce-kv (fn [result k join-expr] (if-let [val (get entity k)] (if (ref? db val) (assoc result k (pull db join-expr val)) (do (when-not (coll? val) (throw (ex-info "pull map pattern must be to a lookup ref or a collection of lookup refs." {:reason ::pull-join-not-ref ::pull-map-pattern pull-map ::entity entity ::attribute k ::value val}))) (assoc result k (keept #(pull db join-expr %) val)))) ;; no value for key result)) result pull-map)) (defn pull "Returns a map representation of the entity found at lookup ref in db. Builds nested maps following a pull pattern. A pull pattern is a vector containing any of the following forms: :key If the entity contains :key, includes it in the result. '* (literal symbol asterisk) Includes all keys from the entity in the result. { :key sub-pattern } The entity's value for key is a lookup ref or collection of lookup refs. Expands each lookup ref to the entity it refers to, then applies pull to each of those entities using the sub-pattern." [db pattern lookup-ref] (when-let [entity (get db lookup-ref)] (reduce (fn [result expr] (cond (keyword? expr) (if-let [[_ val] (find entity expr)] (assoc result expr val) result) (map? expr) (pull-join db result expr entity) (= '* expr) ; don't re-merge things we already joined (merge result (apply dissoc entity (keys result))) :else (throw (ex-info "Invalid form in pull pattern" {:reason ::invalid-pull-form ::form expr ::pattern pattern ::lookup-ref lookup-ref})))) {} pattern)))
true
;; The MIT License (MIT) ;; Copyright (c) 2016 PI:NAME:<NAME>END_PI ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns com.stuartsierra.mapgraph "An in-memory graph data store consisting of maps with links. ## Introduction This is a very basic database that stores entities. An *entity* is a Clojure map from *attributes* to values. An *attribute* is a keyword, usually namespace-qualified. An entity has exactly one *unique identity* attribute whose value acts as a globally-unique identifier for that entity. An entity may not have more than one unique identity attribute; if it does, the behavior is undefined. A *lookup ref* is a vector pair of a unique identity attribute and a value, such as `[:user/id 1234]`. The combination of a unique identity attribute and its value uniquely identifies a single entity in the database. ## Usage Create a new database with `new-db`. The schema of the database is the set of all unique identity attributes. `add-id-attr` extends the schema with a new unique identity attribute. `add` inserts entities in the database. Entities already in the database are updated as by `clojure.core/merge`. (To replace an entity without merging, `dissoc` it first.) All entites added to a database are automatically *normalized*: all nested entities are replaced with lookup refs to other entities in the database. Entity normalization recognizes the following forms: - any non-entity value, including collections - a single entity - a collection (list, vector, set) of entities - a map where keys are any type, vals are single entities Collection values may not mix entities and non-entities. Collections are searched only one layer deep: `add` will not recursively walk arbitrary data structures to search for entities to normalize. Databases can be manipulated with primitive map operations such as `get` and `dissoc`. Keep in mind that there are no indexes: If you `dissoc` an entity from the database you may leave behind broken links to that entity. To get nested maps back out, use `pull`, which follows a pull pattern to recursively expand entity lookup refs.") (defn- seek [pred s] (some #(when (pred %) %) s)) (defn- possible-entity-map? "True if x is a non-sorted map. This check prevents errors from trying to compare keywords with incompatible keys in sorted maps." [x] (and (map? x) (not (sorted? x)))) (defn- find-id-key "Returns the first identifier key found in map, or nil if it is not a valid entity map." [map id-attrs] (when (possible-entity-map? map) (seek #(contains? map %) id-attrs))) (defn- get-ref "Returns a lookup ref for the map, given a collection of identifier keys, or nil if the map does not have an identifier key." [map id-attrs] (when-let [k (find-id-key map id-attrs)] [k (get map k)])) (defn- keept "Like clojure.core/keep but preserves the types of vectors and sets, including sorted sets. If coll is a map, applies f to each value in the map and returns a map of the same (sorted) type." [f coll] (cond (vector? coll) (into [] (keep f) coll) (set? coll) (into (empty coll) (keep f) coll) (map? coll) (reduce-kv (fn [m k v] (if-let [vv (f v)] (assoc m k vv) m)) (empty coll) coll) :else (keep f coll))) (defn- like "Returns a collection of the same type as type-coll (vector, set, sequence) containing elements of sequence s." [type-coll s] (cond (vector? type-coll) (vec s) (set? type-coll) (into (empty type-coll) s) ; handles sorted-set :else s)) (defn- into! "Transient version of clojure.core/into" [to from] (reduce conj! to from)) (defn- update! "Transient version of clojure.core/update" [m k f x] (assoc! m k (f (get m k) x))) (defn- normalize-entities "Returns a sequence of normalized entities starting with map m." [m id-attrs] (lazy-seq (loop [sub-entities (transient []) normalized (transient {}) kvs (seq m)] (if-let [[k v] (first kvs)] (if (map? v) (if-let [r (get-ref v id-attrs)] ;; v is a single entity (recur (conj! sub-entities v) (assoc! normalized k r) (rest kvs)) ;; v is a map, not an entity (let [values (vals v)] (if-let [refs (seq (keep #(get-ref % id-attrs) values))] ;; v is a map whose values are entities (do (when-not (= (count refs) (count v)) (throw (ex-info "Map values may not mix entities and non-entities" {:reason ::mixed-map-vals ::attribute k ::value v}))) (recur (into! sub-entities values) (assoc! normalized k (into (empty v) ; preserve type (map vector (keys v) refs))) (rest kvs))) ;; v is a plain map (recur sub-entities (assoc! normalized k v) (rest kvs))))) ;; v is not a map (if (coll? v) (if-let [refs (seq (keep #(get-ref % id-attrs) v))] ;; v is a collection of entities (do (when-not (= (count refs) (count v)) (throw (ex-info "Collection values may not mix entities and non-entities" {:reason ::mixed-collection ::attribute k ::value v}))) (recur (into! sub-entities v) (assoc! normalized k (like v refs)) (rest kvs))) ;; v is a collection of non-entities (recur sub-entities (assoc! normalized k v) (rest kvs))) ;; v is a single non-entity (recur sub-entities (assoc! normalized k v) (rest kvs)))) (cons (persistent! normalized) (mapcat #(normalize-entities % id-attrs) (persistent! sub-entities))))))) (defn new-db "Returns a new, empty database value." [] {::id-attrs #{}}) (defn db? "Returns true if x is a mapgraph database." [x] (and (map? x) (set? (::id-attrs x)) (every? keyword? (::id-attrs x)))) (defn add-id-attr "Adds unique identity attributes to the db schema. Returns updated db." [db & id-keys] (update db ::id-attrs into id-keys)) (defn add "Returns updated db with normalized entities merged in." [db & entities] (let [id-attrs (::id-attrs db)] (persistent! (reduce (fn [db e] (let [ref (get-ref e id-attrs)] (update! db ref merge e))) (transient db) (mapcat #(normalize-entities % id-attrs) entities))))) (defn entity? "Returns true if map is an entity according to the db schema. An entity is a map from keywords to values with exactly one identifier key." [db map] (and (map? map) (every? keyword? (keys map)) (= 1 (count (filter #(contains? map %) (::id-attrs db)))))) (defn ref-to "Returns a lookup ref for the entity using the schema in db, or nil if not found. The db does not need to contain the entity." [db entity] (get-ref entity (::id-attrs db))) (defn ref? "Returns true if ref is a lookup ref according to the db schema." [db ref] (and (vector? ref) (= 2 (count ref)) (contains? (::id-attrs db) (first ref)))) (declare pull) (defn- pull-join "Executes a pull map expression on entity." [db result pull-map entity] (reduce-kv (fn [result k join-expr] (if-let [val (get entity k)] (if (ref? db val) (assoc result k (pull db join-expr val)) (do (when-not (coll? val) (throw (ex-info "pull map pattern must be to a lookup ref or a collection of lookup refs." {:reason ::pull-join-not-ref ::pull-map-pattern pull-map ::entity entity ::attribute k ::value val}))) (assoc result k (keept #(pull db join-expr %) val)))) ;; no value for key result)) result pull-map)) (defn pull "Returns a map representation of the entity found at lookup ref in db. Builds nested maps following a pull pattern. A pull pattern is a vector containing any of the following forms: :key If the entity contains :key, includes it in the result. '* (literal symbol asterisk) Includes all keys from the entity in the result. { :key sub-pattern } The entity's value for key is a lookup ref or collection of lookup refs. Expands each lookup ref to the entity it refers to, then applies pull to each of those entities using the sub-pattern." [db pattern lookup-ref] (when-let [entity (get db lookup-ref)] (reduce (fn [result expr] (cond (keyword? expr) (if-let [[_ val] (find entity expr)] (assoc result expr val) result) (map? expr) (pull-join db result expr entity) (= '* expr) ; don't re-merge things we already joined (merge result (apply dissoc entity (keys result))) :else (throw (ex-info "Invalid form in pull pattern" {:reason ::invalid-pull-form ::form expr ::pattern pattern ::lookup-ref lookup-ref})))) {} pattern)))
[ { "context": "\n :authentication {:username \"zcaudate\"\n :password ", "end": 1883, "score": 0.9995612502098083, "start": 1875, "tag": "USERNAME", "value": "zcaudate" }, { "context": "\n :password \"hello\"}}\n RemoteRepository)\n ;;=> #", "end": 1939, "score": 0.9994156360626221, "start": 1934, "tag": "PASSWORD", "value": "hello" }, { "context": "itory)\n ;;=> #remote{:authentication {:username \"zcaudate\", :password \"hello\"},\n ;; :content-typ", "end": 2032, "score": 0.9992567300796509, "start": 2024, "tag": "USERNAME", "value": "zcaudate" }, { "context": ":authentication {:username \"zcaudate\", :password \"hello\"},\n ;; :content-type \"default\",\n ;; ", "end": 2051, "score": 0.9992061257362366, "start": 2046, "tag": "PASSWORD", "value": "hello" } ]
test/hara/lib/aether/remote_repo_test.clj
zcaudate/hara
309
(ns hara.lib.aether.remote-repo-test (:use hara.test) (:require [hara.object :as object] [hara.lib.aether.remote-repo]) (:import (org.eclipse.aether.repository RemoteRepository RemoteRepository$Builder RepositoryPolicy))) ^{:added "3.0"} (fact "creates a `RepositoryPolicy` from map" (object/from-data {:checksum-policy "warn", :update-policy "daily", :enabled? true} RepositoryPolicy) ;;=> #policy{:checksum-policy "warn", :update-policy "daily", :enabled? true} ) ^{:added "3.0"} (comment "creates a `RemoteRepository$Builder` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/"} RemoteRepository$Builder) ;;=> #builder.remote{:repository-manager false ;; :type "default" ;; :default-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :release-policy {:checksum-policy "warn" ;; :update-policy "daily" ;; :enabled? true} ;; :snapshots-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :id "clojars" ;; :url "http://clojars.org/repo/"} ) ^{:added 1.2} (fact "creates a `RemoteRepository` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/" :authentication {:username "zcaudate" :password "hello"}} RemoteRepository) ;;=> #remote{:authentication {:username "zcaudate", :password "hello"}, ;; :content-type "default", ;; :host "clojars.org", ;; :id "clojars", ;; :mirrored-repositories [], ;; :protocol "http", ;; :url "http://clojars.org/repo/", ;; :repository-manager? false} )
46225
(ns hara.lib.aether.remote-repo-test (:use hara.test) (:require [hara.object :as object] [hara.lib.aether.remote-repo]) (:import (org.eclipse.aether.repository RemoteRepository RemoteRepository$Builder RepositoryPolicy))) ^{:added "3.0"} (fact "creates a `RepositoryPolicy` from map" (object/from-data {:checksum-policy "warn", :update-policy "daily", :enabled? true} RepositoryPolicy) ;;=> #policy{:checksum-policy "warn", :update-policy "daily", :enabled? true} ) ^{:added "3.0"} (comment "creates a `RemoteRepository$Builder` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/"} RemoteRepository$Builder) ;;=> #builder.remote{:repository-manager false ;; :type "default" ;; :default-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :release-policy {:checksum-policy "warn" ;; :update-policy "daily" ;; :enabled? true} ;; :snapshots-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :id "clojars" ;; :url "http://clojars.org/repo/"} ) ^{:added 1.2} (fact "creates a `RemoteRepository` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/" :authentication {:username "zcaudate" :password "<PASSWORD>"}} RemoteRepository) ;;=> #remote{:authentication {:username "zcaudate", :password "<PASSWORD>"}, ;; :content-type "default", ;; :host "clojars.org", ;; :id "clojars", ;; :mirrored-repositories [], ;; :protocol "http", ;; :url "http://clojars.org/repo/", ;; :repository-manager? false} )
true
(ns hara.lib.aether.remote-repo-test (:use hara.test) (:require [hara.object :as object] [hara.lib.aether.remote-repo]) (:import (org.eclipse.aether.repository RemoteRepository RemoteRepository$Builder RepositoryPolicy))) ^{:added "3.0"} (fact "creates a `RepositoryPolicy` from map" (object/from-data {:checksum-policy "warn", :update-policy "daily", :enabled? true} RepositoryPolicy) ;;=> #policy{:checksum-policy "warn", :update-policy "daily", :enabled? true} ) ^{:added "3.0"} (comment "creates a `RemoteRepository$Builder` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/"} RemoteRepository$Builder) ;;=> #builder.remote{:repository-manager false ;; :type "default" ;; :default-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :release-policy {:checksum-policy "warn" ;; :update-policy "daily" ;; :enabled? true} ;; :snapshots-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :id "clojars" ;; :url "http://clojars.org/repo/"} ) ^{:added 1.2} (fact "creates a `RemoteRepository` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/" :authentication {:username "zcaudate" :password "PI:PASSWORD:<PASSWORD>END_PI"}} RemoteRepository) ;;=> #remote{:authentication {:username "zcaudate", :password "PI:PASSWORD:<PASSWORD>END_PI"}, ;; :content-type "default", ;; :host "clojars.org", ;; :id "clojars", ;; :mirrored-repositories [], ;; :protocol "http", ;; :url "http://clojars.org/repo/", ;; :repository-manager? false} )
[ { "context": ";; Copyright (c) 2014, Andrey Antukh\n;; Copyright (c) 2014, Alejandro Gómez\n;; All rig", "end": 36, "score": 0.9998785257339478, "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.9998614192008972, "start": 60, "tag": "NAME", "value": "Alejandro Gómez" } ]
src/cljx/cats/data.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.data "Data structures that are used in various places of the library.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Pair type constructor and functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype Pair [fst snd] #+clj clojure.lang.Seqable #+cljs cljs.core/ISeqable (#+cljs -seq #+clj seq [_] (list fst snd)) #+clj clojure.lang.Indexed #+cljs cljs.core/IIndexed (#+clj nth #+cljs -nth [_ i] (case i 0 fst 1 snd (throw #+clj (IndexOutOfBoundsException.) #+cljs (js/Error. "Out of index")))) (#+clj nth #+cljs -nth [_ i notfound] (case i 0 fst 1 snd notfound)) #+clj clojure.lang.Counted #+cljs cljs.core/ICounted (#+clj count #+cljs -count [_] 2) #+clj java.lang.Object #+cljs cljs.core/IEquiv (#+clj equals #+cljs -equiv [this other] (if (instance? Pair other) (and (= (.-fst this) (.-fst other)) (= (.-snd this) (.-snd other))) false)) #+clj (toString [this] (with-out-str (print [fst snd])))) (defn pair [fst snd] (Pair. fst snd)) (defn pair? [v] (instance? Pair v))
31057
;; 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.data "Data structures that are used in various places of the library.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Pair type constructor and functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype Pair [fst snd] #+clj clojure.lang.Seqable #+cljs cljs.core/ISeqable (#+cljs -seq #+clj seq [_] (list fst snd)) #+clj clojure.lang.Indexed #+cljs cljs.core/IIndexed (#+clj nth #+cljs -nth [_ i] (case i 0 fst 1 snd (throw #+clj (IndexOutOfBoundsException.) #+cljs (js/Error. "Out of index")))) (#+clj nth #+cljs -nth [_ i notfound] (case i 0 fst 1 snd notfound)) #+clj clojure.lang.Counted #+cljs cljs.core/ICounted (#+clj count #+cljs -count [_] 2) #+clj java.lang.Object #+cljs cljs.core/IEquiv (#+clj equals #+cljs -equiv [this other] (if (instance? Pair other) (and (= (.-fst this) (.-fst other)) (= (.-snd this) (.-snd other))) false)) #+clj (toString [this] (with-out-str (print [fst snd])))) (defn pair [fst snd] (Pair. fst snd)) (defn pair? [v] (instance? Pair v))
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.data "Data structures that are used in various places of the library.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Pair type constructor and functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype Pair [fst snd] #+clj clojure.lang.Seqable #+cljs cljs.core/ISeqable (#+cljs -seq #+clj seq [_] (list fst snd)) #+clj clojure.lang.Indexed #+cljs cljs.core/IIndexed (#+clj nth #+cljs -nth [_ i] (case i 0 fst 1 snd (throw #+clj (IndexOutOfBoundsException.) #+cljs (js/Error. "Out of index")))) (#+clj nth #+cljs -nth [_ i notfound] (case i 0 fst 1 snd notfound)) #+clj clojure.lang.Counted #+cljs cljs.core/ICounted (#+clj count #+cljs -count [_] 2) #+clj java.lang.Object #+cljs cljs.core/IEquiv (#+clj equals #+cljs -equiv [this other] (if (instance? Pair other) (and (= (.-fst this) (.-fst other)) (= (.-snd this) (.-snd other))) false)) #+clj (toString [this] (with-out-str (print [fst snd])))) (defn pair [fst snd] (Pair. fst snd)) (defn pair? [v] (instance? Pair v))
[ { "context": ") ;; warnings in cheshire.generate\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2017-11-13\"\n :date \"2017-11-", "end": 137, "score": 0.9040859937667847, "start": 111, "tag": "EMAIL", "value": "wahpenayo at gmail dot com" } ]
src/main/clojure/zana/io/cheshire.clj
wahpenayo/zana
2
(set! *warn-on-reflection* true) (set! *unchecked-math* false) ;; warnings in cheshire.generate (ns ^{:author "wahpenayo at gmail dot com" :since "2017-11-13" :date "2017-11-13" :doc "Generally useful cheshire (JSON) encoders. <p> Decoding (input) not yet supported, because obvious JSON encoding is lossy." } zana.io.cheshire (:require [cheshire.generate])) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (doseq [a [(boolean-array 0) (char-array 0) (double-array 0) (float-array 0) (int-array 0) (long-array 0) (short-array 0) (object-array 0)]] (cheshire.generate/add-encoder (class a) (fn encoder [x json-generator] (cheshire.generate/encode-seq x json-generator)))) ;;----------------------------------------------------------------
9127
(set! *warn-on-reflection* true) (set! *unchecked-math* false) ;; warnings in cheshire.generate (ns ^{:author "<EMAIL>" :since "2017-11-13" :date "2017-11-13" :doc "Generally useful cheshire (JSON) encoders. <p> Decoding (input) not yet supported, because obvious JSON encoding is lossy." } zana.io.cheshire (:require [cheshire.generate])) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (doseq [a [(boolean-array 0) (char-array 0) (double-array 0) (float-array 0) (int-array 0) (long-array 0) (short-array 0) (object-array 0)]] (cheshire.generate/add-encoder (class a) (fn encoder [x json-generator] (cheshire.generate/encode-seq x json-generator)))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* false) ;; warnings in cheshire.generate (ns ^{:author "PI:EMAIL:<EMAIL>END_PI" :since "2017-11-13" :date "2017-11-13" :doc "Generally useful cheshire (JSON) encoders. <p> Decoding (input) not yet supported, because obvious JSON encoding is lossy." } zana.io.cheshire (:require [cheshire.generate])) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (doseq [a [(boolean-array 0) (char-array 0) (double-array 0) (float-array 0) (int-array 0) (long-array 0) (short-array 0) (object-array 0)]] (cheshire.generate/add-encoder (class a) (fn encoder [x json-generator] (cheshire.generate/encode-seq x json-generator)))) ;;----------------------------------------------------------------
[ { "context": " (:import (java.sql SQLException)))\n\n(def passw \"bcrypt+sha512$a20e2dd70567d58028a5a108ce54b832$12$00a281eb5acd4dd11c37dffadc5f4aeb78288684029268a9\")\n\n(use-fixtures\n :once\n (fn [f]\n (mount/sta", "end": 427, "score": 0.9957932233810425, "start": 329, "tag": "PASSWORD", "value": "bcrypt+sha512$a20e2dd70567d58028a5a108ce54b832$12$00a281eb5acd4dd11c37dffadc5f4aeb78288684029268a9" }, { "context": "\n (is (= {:username \"admin\"\n :password ", "end": 865, "score": 0.9995611906051636, "start": 860, "tag": "USERNAME", "value": "admin" }, { "context": "n\"\n :password passw\n :admin t", "end": 920, "score": 0.9978984594345093, "start": 915, "tag": "PASSWORD", "value": "passw" }, { "context": " (dissoc (db/get-user {:username \"admin\"}) :user_id))))))\n\n(deftest get-all-users\n (jdbc", "end": 1103, "score": 0.9995173215866089, "start": 1098, "tag": "USERNAME", "value": "admin" }, { "context": " {:username \"newuser\"\n ", "end": 1703, "score": 0.9994224309921265, "start": 1696, "tag": "USERNAME", "value": "newuser" }, { "context": " :password \"pass\"\n ", "end": 1777, "score": 0.9995648860931396, "start": 1773, "tag": "PASSWORD", "value": "pass" }, { "context": "\n (is (= {:username \"newuser\"\n :password ", "end": 1912, "score": 0.9985901117324829, "start": 1905, "tag": "USERNAME", "value": "newuser" }, { "context": "\n :password \"pass\"\n :admin ", "end": 1967, "score": 0.9995575547218323, "start": 1963, "tag": "PASSWORD", "value": "pass" }, { "context": " (dissoc (db/get-user t-conn {:username \"newuser\"}) :user_id))))\n (test", "end": 2161, "score": 0.9996275901794434, "start": 2154, "tag": "USERNAME", "value": "newuser" }, { "context": " {:username \"newuser\"\n :p", "end": 2494, "score": 0.9996377825737, "start": 2487, "tag": "USERNAME", "value": "newuser" }, { "context": " :password \"pass\"\n :a", "end": 2557, "score": 0.9995638728141785, "start": 2553, "tag": "PASSWORD", "value": "pass" }, { "context": " {:username \"newuser\"\n ", "end": 2949, "score": 0.9996459484100342, "start": 2942, "tag": "USERNAME", "value": "newuser" }, { "context": " :password \"pass\"\n ", "end": 3023, "score": 0.9995643496513367, "start": 3019, "tag": "PASSWORD", "value": "pass" }, { "context": " {:username \"newuser\"})))\n (is (= nil\n ", "end": 3240, "score": 0.9996398687362671, "start": 3233, "tag": "USERNAME", "value": "newuser" }, { "context": " (dissoc (db/get-user t-conn {:username \"newuser\"}) :user_id))))))\n\n(deftest update-user-password\n", "end": 3371, "score": 0.9996587038040161, "start": 3364, "tag": "USERNAME", "value": "newuser" }, { "context": " {:username \"newuser\"\n :p", "end": 3643, "score": 0.9996507167816162, "start": 3636, "tag": "USERNAME", "value": "newuser" }, { "context": " :password \"pass\"\n :a", "end": 3706, "score": 0.9995238184928894, "start": 3702, "tag": "PASSWORD", "value": "pass" }, { "context": " {:username \"newuser\"\n ", "end": 3906, "score": 0.9996587634086609, "start": 3899, "tag": "USERNAME", "value": "newuser" }, { "context": " :password \"p\"})\n (is (= \"p\"\n ", "end": 3975, "score": 0.9623643755912781, "start": 3974, "tag": "PASSWORD", "value": "p" }, { "context": " (:password (db/get-user t-conn {:username \"newuser\"}))))))\n\n(deftest update-user-lang\n (jdbc/with-d", "end": 4103, "score": 0.9996471405029297, "start": 4096, "tag": "USERNAME", "value": "newuser" }, { "context": " {:username \"newuser\"\n :p", "end": 4361, "score": 0.9996446371078491, "start": 4354, "tag": "USERNAME", "value": "newuser" }, { "context": " :password \"pass\"\n :a", "end": 4424, "score": 0.9995805025100708, "start": 4420, "tag": "PASSWORD", "value": "pass" }, { "context": " {:username \"newuser\"\n ", "end": 4616, "score": 0.9996441602706909, "start": 4609, "tag": "USERNAME", "value": "newuser" }, { "context": " (:lang (db/get-user t-conn {:username \"newuser\"}))))))", "end": 4807, "score": 0.9996362924575806, "start": 4800, "tag": "USERNAME", "value": "newuser" } ]
test/copa/test/db/users.clj
hjrnunes/copa
2
(ns copa.test.db.users (:require [copa.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [copa.config :refer [env]] [mount.core :as mount]) (:import (java.sql SQLException))) (def passw "bcrypt+sha512$a20e2dd70567d58028a5a108ce54b832$12$00a281eb5acd4dd11c37dffadc5f4aeb78288684029268a9") (use-fixtures :once (fn [f] (mount/start #'copa.config/env #'copa.db.core/*db*) (migrations/migrate ["reset"] {:database-url "jdbc:h2:./copa_test;MVCC=true"}) (f))) (deftest get-user (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "get initial admin user" (is (= {:username "admin" :password passw :admin true :lang "en"} (dissoc (db/get-user {:username "admin"}) :user_id)))))) (deftest get-all-users (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "get all users" (is (= 1 (count (db/get-users t-conn))))))) (deftest insert-user (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "inserting new user" (is (= 1 (db/create-user! t-conn {:username "newuser" :password "pass" :admin false}))) (is (= {:username "newuser" :password "pass" :admin false :lang "en"} (dissoc (db/get-user t-conn {:username "newuser"}) :user_id)))) (testing "insert another user with same username fails" (is (thrown? SQLException (db/create-user! t-conn {:username "newuser" :password "pass" :admin false})))))) (deftest delete-user (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "deleting a user" (is (= 1 (db/create-user! t-conn {:username "newuser" :password "pass" :admin false}))) (is (= 1 (db/delete-user! t-conn {:username "newuser"}))) (is (= nil (dissoc (db/get-user t-conn {:username "newuser"}) :user_id)))))) (deftest update-user-password (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (db/create-user! t-conn {:username "newuser" :password "pass" :admin false}) (db/update-user-password! t-conn {:username "newuser" :password "p"}) (is (= "p" (:password (db/get-user t-conn {:username "newuser"})))))) (deftest update-user-lang (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (db/create-user! t-conn {:username "newuser" :password "pass" :admin false}) (db/update-user-lang! t-conn {:username "newuser" :lang "cz"}) (is (= "cz" (:lang (db/get-user t-conn {:username "newuser"}))))))
70912
(ns copa.test.db.users (:require [copa.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [copa.config :refer [env]] [mount.core :as mount]) (:import (java.sql SQLException))) (def passw "<PASSWORD>") (use-fixtures :once (fn [f] (mount/start #'copa.config/env #'copa.db.core/*db*) (migrations/migrate ["reset"] {:database-url "jdbc:h2:./copa_test;MVCC=true"}) (f))) (deftest get-user (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "get initial admin user" (is (= {:username "admin" :password <PASSWORD> :admin true :lang "en"} (dissoc (db/get-user {:username "admin"}) :user_id)))))) (deftest get-all-users (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "get all users" (is (= 1 (count (db/get-users t-conn))))))) (deftest insert-user (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "inserting new user" (is (= 1 (db/create-user! t-conn {:username "newuser" :password "<PASSWORD>" :admin false}))) (is (= {:username "newuser" :password "<PASSWORD>" :admin false :lang "en"} (dissoc (db/get-user t-conn {:username "newuser"}) :user_id)))) (testing "insert another user with same username fails" (is (thrown? SQLException (db/create-user! t-conn {:username "newuser" :password "<PASSWORD>" :admin false})))))) (deftest delete-user (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "deleting a user" (is (= 1 (db/create-user! t-conn {:username "newuser" :password "<PASSWORD>" :admin false}))) (is (= 1 (db/delete-user! t-conn {:username "newuser"}))) (is (= nil (dissoc (db/get-user t-conn {:username "newuser"}) :user_id)))))) (deftest update-user-password (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (db/create-user! t-conn {:username "newuser" :password "<PASSWORD>" :admin false}) (db/update-user-password! t-conn {:username "newuser" :password "<PASSWORD>"}) (is (= "p" (:password (db/get-user t-conn {:username "newuser"})))))) (deftest update-user-lang (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (db/create-user! t-conn {:username "newuser" :password "<PASSWORD>" :admin false}) (db/update-user-lang! t-conn {:username "newuser" :lang "cz"}) (is (= "cz" (:lang (db/get-user t-conn {:username "newuser"}))))))
true
(ns copa.test.db.users (:require [copa.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [copa.config :refer [env]] [mount.core :as mount]) (:import (java.sql SQLException))) (def passw "PI:PASSWORD:<PASSWORD>END_PI") (use-fixtures :once (fn [f] (mount/start #'copa.config/env #'copa.db.core/*db*) (migrations/migrate ["reset"] {:database-url "jdbc:h2:./copa_test;MVCC=true"}) (f))) (deftest get-user (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "get initial admin user" (is (= {:username "admin" :password PI:PASSWORD:<PASSWORD>END_PI :admin true :lang "en"} (dissoc (db/get-user {:username "admin"}) :user_id)))))) (deftest get-all-users (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "get all users" (is (= 1 (count (db/get-users t-conn))))))) (deftest insert-user (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "inserting new user" (is (= 1 (db/create-user! t-conn {:username "newuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :admin false}))) (is (= {:username "newuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :admin false :lang "en"} (dissoc (db/get-user t-conn {:username "newuser"}) :user_id)))) (testing "insert another user with same username fails" (is (thrown? SQLException (db/create-user! t-conn {:username "newuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :admin false})))))) (deftest delete-user (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "deleting a user" (is (= 1 (db/create-user! t-conn {:username "newuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :admin false}))) (is (= 1 (db/delete-user! t-conn {:username "newuser"}))) (is (= nil (dissoc (db/get-user t-conn {:username "newuser"}) :user_id)))))) (deftest update-user-password (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (db/create-user! t-conn {:username "newuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :admin false}) (db/update-user-password! t-conn {:username "newuser" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (is (= "p" (:password (db/get-user t-conn {:username "newuser"})))))) (deftest update-user-lang (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (db/create-user! t-conn {:username "newuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :admin false}) (db/update-user-lang! t-conn {:username "newuser" :lang "cz"}) (is (= "cz" (:lang (db/get-user t-conn {:username "newuser"}))))))
[ { "context": " :creator_id (mt/user->id :crowberto)\n :creator (user-detai", "end": 3565, "score": 0.9976882934570312, "start": 3556, "tag": "USERNAME", "value": "crowberto" }, { "context": "tor (user-details (mt/fetch-user :crowberto))\n :created_at true\n ", "end": 3643, "score": 0.9907436370849609, "start": 3634, "tag": "USERNAME", "value": "crowberto" }, { "context": "ble-id}]]\n (is (= {:name \"Costa Rica\"\n :description nil\n ", "end": 6412, "score": 0.9998692274093628, "start": 6402, "tag": "NAME", "value": "Costa Rica" }, { "context": " id\n :name \"Costa Rica\"\n :description nil\n ", "end": 7161, "score": 0.9998626708984375, "start": 7151, "tag": "NAME", "value": "Costa Rica" }, { "context": "t [{:keys [id]} {:creator_id (mt/user->id :crowberto)\n :t", "end": 11869, "score": 0.5054922699928284, "start": 11864, "tag": "USERNAME", "value": "berto" }, { "context": " :creator_id (mt/user->id :crowberto)\n :creator (user-det", "end": 12360, "score": 0.9490628838539124, "start": 12351, "tag": "USERNAME", "value": "crowberto" }, { "context": "tor (user-details (mt/fetch-user :crowberto))\n :created_at true\n ", "end": 12440, "score": 0.7217021584510803, "start": 12431, "tag": "USERNAME", "value": "crowberto" }, { "context": "Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto)\n :tab", "end": 13679, "score": 0.9978671669960022, "start": 13670, "tag": "USERNAME", "value": "crowberto" }, { "context": " :user_id (mt/user->id :crowberto)\n :object {:nam", "end": 14396, "score": 0.9980649352073669, "start": 14387, "tag": "USERNAME", "value": "crowberto" }, { "context": "id]} {:creator_id (mt/user->id :crowberto)\n ", "end": 16711, "score": 0.9969475865364075, "start": 16702, "tag": "USERNAME", "value": "crowberto" }, { "context": "ject {:creator_id (mt/user->id :crowberto)\n ", "end": 17663, "score": 0.9694378972053528, "start": 17654, "tag": "USERNAME", "value": "crowberto" }, { "context": " :user_id (mt/user->id :crowberto)\n ", "end": 18746, "score": 0.9982566833496094, "start": 18737, "tag": "USERNAME", "value": "crowberto" }, { "context": ":object {:creator_id (mt/user->id :crowberto)\n ", "end": 18856, "score": 0.9933908581733704, "start": 18847, "tag": "USERNAME", "value": "crowberto" }, { "context": " :user (-> (user-details (mt/fetch-user :crowberto))\n (dissoc :emai", "end": 19884, "score": 0.9880531430244446, "start": 19875, "tag": "USERNAME", "value": "crowberto" } ]
c#-metabase/test/metabase/api/segment_test.clj
hanakhry/Crime_Admin
0
(ns metabase.api.segment-test "Tests for /api/segment endpoints." (:require [clojure.test :refer :all] [metabase.http-client :as http] [metabase.models.database :refer [Database]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group] [metabase.models.revision :refer [Revision]] [metabase.models.segment :as segment :refer [Segment]] [metabase.models.table :refer [Table]] [metabase.server.middleware.util :as middleware.u] [metabase.test :as mt] [metabase.util :as u] [toucan.db :as db] [toucan.hydrate :refer [hydrate]])) ;; ## Helper Fns (defn- user-details [user] (select-keys user [:email :first_name :last_login :is_qbnewb :is_superuser :id :last_name :date_joined :common_name :locale])) (defn- segment-response [segment] (-> (into {} segment) (dissoc :id :table_id) (update :creator #(into {} %)) (update :created_at some?) (update :updated_at some?))) ;; ## /api/segment/* AUTHENTICATION Tests ;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same ;; authentication test on every single individual endpoint (deftest authentication-test (is (= (get middleware.u/response-unauthentic :body) (http/client :get 401 "segment"))) (is (= (get middleware.u/response-unauthentic :body) (http/client :put 401 "segment/13")))) ;; ## POST /api/segment (deftest create-segment-permissions-test (testing "POST /api/segment" (testing "Test security. Requires superuser perms." (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :post 403 "segment" {:name "abc" :table_id 123 :definition {}})))))) (deftest create-segment-input-validation-test (testing "POST /api/segment" (is (= {:errors {:name "value must be a non-blank string."}} (mt/user-http-request :crowberto :post 400 "segment" {}))) (is (= {:errors {:table_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc"}))) (is (= {:errors {:table_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc" :table_id "foobar"}))) (is (= {:errors {:definition "value must be a map."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc" :table_id 123}))) (is (= {:errors {:definition "value must be a map."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc" :table_id 123 :definition "foobar"}))))) (deftest create-segment-test (mt/with-temp* [Database [{database-id :id}] Table [{:keys [id]} {:db_id database-id}]] (is (= {:name "A Segment" :description "I did it!" :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :crowberto) :creator (user-details (mt/fetch-user :crowberto)) :created_at true :updated_at true :archived false :definition {:filter ["=" ["field" 10 nil] 20]}} (segment-response (mt/user-http-request :crowberto :post 200 "segment" {:name "A Segment" :description "I did it!" :show_in_getting_started false :caveats nil :points_of_interest nil :table_id id :definition {:filter [:= [:field-id 10] 20]}})))))) ;; ## PUT /api/segment (deftest update-permissions-test (testing "PUT /api/segment/:id" (testing "test security. requires superuser perms" (mt/with-temp Segment [segment] (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 (str "segment/" (:id segment)) {:name "abc" :definition {} :revision_message "something different"}))))))) (deftest update-input-validation-test (testing "PUT /api/segment/:id" (is (= {:errors {:name "value may be nil, or if non-nil, value must be a non-blank string."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name ""}))) (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc"}))) (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc" :revision_message ""}))) (is (= {:errors {:definition "value may be nil, or if non-nil, value must be a map."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc" :revision_message "123" :definition "foobar"}))))) (deftest update-test (testing "PUT /api/segment/:id" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:table_id table-id}]] (is (= {:name "Costa Rica" :description nil :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :rasta) :creator (user-details (mt/fetch-user :rasta)) :created_at true :updated_at true :archived false :definition {:filter ["!=" ["field" 2 nil] "cans"]}} (segment-response (mt/user-http-request :crowberto :put 200 (format "segment/%d" id) {:id id :name "Costa Rica" :description nil :show_in_getting_started false :caveats nil :points_of_interest nil :table_id 456 :revision_message "I got me some revisions" :definition {:filter [:!= [:field-id 2] "cans"]}}))))))) (deftest partial-update-test (testing "PUT /api/segment/:id" (testing "Can I update a segment's name without specifying `:points_of_interest` and `:show_in_getting_started`?" (mt/with-temp Segment [segment] ;; just make sure API call doesn't barf (is (some? (mt/user-http-request :crowberto :put 200 (str "segment/" (u/the-id segment)) {:name "Cool name" :revision_message "WOW HOW COOL" :definition {}}))))))) (deftest archive-test (testing "PUT /api/segment/:id" (testing "Can we archive a Segment with the PUT endpoint?" (mt/with-temp Segment [{:keys [id]}] (is (map? (mt/user-http-request :crowberto :put 200 (str "segment/" id) {:archived true, :revision_message "Archive the Segment"}))) (is (= true (db/select-one-field :archived Segment :id id))))))) (deftest unarchive-test (testing "PUT /api/segment/:id" (testing "Can we unarchive a Segment with the PUT endpoint?" (mt/with-temp Segment [{:keys [id]} {:archived true}] (is (map? (mt/user-http-request :crowberto :put 200 (str "segment/" id) {:archived false, :revision_message "Unarchive the Segment"}))) (is (= false (db/select-one-field :archived Segment :id id))))))) ;; ## DELETE /api/segment/:id (deftest delete-permissions-test (testing "DELETE /api/segment/:id" (testing "test security. requires superuser perms" (mt/with-temp Segment [{:keys [id]}] (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :delete 403 (str "segment/" id) :revision_message "yeeeehaw!"))))))) (deftest delete-input-validation-test (testing "DELETE /api/segment/:id" (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :delete 400 "segment/1" {:name "abc"}))) (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :delete 400 "segment/1" :revision_message ""))))) (deftest delete-test (testing "DELETE /api/segment/:id" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:table_id table-id}]] (is (= nil (mt/user-http-request :crowberto :delete 204 (format "segment/%d" id) :revision_message "carryon"))) (testing "should still be able to fetch the archived segment" (is (= {:name "Toucans in the rainforest" :description "Lookin' for a blueberry" :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :rasta) :creator (user-details (mt/fetch-user :rasta)) :created_at true :updated_at true :archived true :definition nil} (-> (mt/user-http-request :crowberto :get 200 (format "segment/%d" id)) segment-response (dissoc :query_description)))))))) ;; ## GET /api/segment/:id (deftest fetch-segment-permissions-test (testing "GET /api/segment/:id" (testing "test security. Requires read perms for the Table it references" (mt/with-temp* [Database [db] Table [table {:db_id (u/the-id db)}] Segment [segment {:table_id (u/the-id table)}]] (perms/revoke-permissions! (group/all-users) db) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :get 403 (str "segment/" (u/the-id segment))))))))) (deftest fetch-segment-test (testing "GET /api/segment/:id" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto) :table_id table-id :definition {:filter [:= [:field-id 2] "cans"]}}]] (is (= {:name "Toucans in the rainforest" :description "Lookin' for a blueberry" :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :crowberto) :creator (user-details (mt/fetch-user :crowberto)) :created_at true :updated_at true :archived false :definition {:filter ["=" ["field" 2 nil] "cans"]}} (-> (mt/user-http-request :rasta :get 200 (format "segment/%d" id)) segment-response (dissoc :query_description))))))) ;; ## GET /api/segment/:id/revisions (deftest revisions-permissions-test (testing "GET /api/segment/:id/revisions" (testing "test security. Requires read perms for the Table it references" (mt/with-temp* [Database [db] Table [table {:db_id (u/the-id db)}] Segment [segment {:table_id (u/the-id table)}]] (perms/revoke-permissions! (group/all-users) db) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :get 403 (format "segment/%d/revisions" (u/the-id segment))))))))) (deftest revisions-test (testing "GET /api/segment/:id/revisions" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto) :table_id table-id :definition {:database 123 :query {:filter [:= [:field-id 2] "cans"]}}}] Revision [_ {:model "Segment" :model_id id :object {:name "b" :definition {:filter [:and [:> 1 25]]}} :is_creation true}] Revision [_ {:model "Segment" :model_id id :user_id (mt/user->id :crowberto) :object {:name "c" :definition {:filter [:and [:> 1 25]]}} :message "updated"}]] (is (= [{:is_reversion false :is_creation false :message "updated" :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:before "b" :after "c"}} :description "renamed this Segment from \"b\" to \"c\"."} {:is_reversion false :is_creation true :message nil :user (-> (user-details (mt/fetch-user :rasta)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:after "b"} :definition {:after {:filter [">" ["field" 1 nil] 25]}}} :description nil}] (for [revision (mt/user-http-request :rasta :get 200 (format "segment/%d/revisions" id))] (dissoc revision :timestamp :id))))))) ;; ## POST /api/segment/:id/revert (deftest revert-permissions-test (testing "POST /api/segment/:id/revert" (testing "test security. requires superuser perms" (mt/with-temp Segment [{:keys [id]}] (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :post 403 (format "segment/%d/revert" id) {:revision_id 56}))))))) (deftest revert-input-validation-test (testing "POST /api/segment/:id/revert" (is (= {:errors {:revision_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment/1/revert" {}))) (is (= {:errors {:revision_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment/1/revert" {:revision_id "foobar"}))))) (deftest revert-test (testing "POST /api/segment/:id/revert" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto) :table_id table-id :name "One Segment to rule them all, one segment to define them" :description "One segment to bring them all, and in the DataModel bind them" :show_in_getting_started false :caveats nil :points_of_interest nil :definition {:filter [:= [:field-id 2] "cans"]}}] Revision [{revision-id :id} {:model "Segment" :model_id id :object {:creator_id (mt/user->id :crowberto) :table_id table-id :name "One Segment to rule them all, one segment to define them" :description "One segment to bring them all, and in the DataModel bind them" :show_in_getting_started false :caveats nil :points_of_interest nil :definition {:filter [:= [:field-id 2] "cans"]}} :is_creation true}] Revision [_ {:model "Segment" :model_id id :user_id (mt/user->id :crowberto) :object {:creator_id (mt/user->id :crowberto) :table_id table-id :name "Changed Segment Name" :description "One segment to bring them all, and in the DataModel bind them" :show_in_getting_started false :caveats nil :points_of_interest nil :definition {:filter [:= [:field-id 2] "cans"]}} :message "updated"}]] (testing "the api response" (is (= {:is_reversion true :is_creation false :message nil :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:before "Changed Segment Name" :after "One Segment to rule them all, one segment to define them"}} :description "renamed this Segment from \"Changed Segment Name\" to \"One Segment to rule them all, one segment to define them\"."} (-> (mt/user-http-request :crowberto :post 200 (format "segment/%d/revert" id) {:revision_id revision-id}) (dissoc :id :timestamp))))) (testing "full list of final revisions, first one should be same as the revision returned by the endpoint" (is (= [{:is_reversion true :is_creation false :message nil :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:before "Changed Segment Name" :after "One Segment to rule them all, one segment to define them"}} :description "renamed this Segment from \"Changed Segment Name\" to \"One Segment to rule them all, one segment to define them\"."} {:is_reversion false :is_creation false :message "updated" :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:after "Changed Segment Name" :before "One Segment to rule them all, one segment to define them"}} :description "renamed this Segment from \"One Segment to rule them all, one segment to define them\" to \"Changed Segment Name\"."} {:is_reversion false :is_creation true :message nil :user (-> (user-details (mt/fetch-user :rasta)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:after "One Segment to rule them all, one segment to define them"} :description {:after "One segment to bring them all, and in the DataModel bind them"} :definition {:after {:filter ["=" ["field" 2 nil] "cans"]}}} :description nil}] (for [revision (mt/user-http-request :crowberto :get 200 (format "segment/%d/revisions" id))] (dissoc revision :timestamp :id)))))))) ;;; GET /api/segement/ (deftest list-test (testing "GET /api/segement/" (mt/with-temp* [Segment [segment-1 {:name "Segment 1"}] Segment [segment-2 {:name "Segment 2"}] ;; inactive segments shouldn't show up Segment [_ {:archived true}]] (is (= (mt/derecordize (hydrate [segment-1 segment-2] :creator)) (map #(dissoc % :query_description) (mt/user-http-request :rasta :get 200 "segment/"))))) (is (= [] (mt/user-http-request :rasta :get 200 "segment/"))))) (deftest related-entities-test (testing "GET /api/segment/:id/related" (testing "related/recommended entities" (mt/with-temp Segment [{segment-id :id}] (is (= #{:table :metrics :segments :linked-from} (-> (mt/user-http-request :crowberto :get 200 (format "segment/%s/related" segment-id)) keys set)))))))
30252
(ns metabase.api.segment-test "Tests for /api/segment endpoints." (:require [clojure.test :refer :all] [metabase.http-client :as http] [metabase.models.database :refer [Database]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group] [metabase.models.revision :refer [Revision]] [metabase.models.segment :as segment :refer [Segment]] [metabase.models.table :refer [Table]] [metabase.server.middleware.util :as middleware.u] [metabase.test :as mt] [metabase.util :as u] [toucan.db :as db] [toucan.hydrate :refer [hydrate]])) ;; ## Helper Fns (defn- user-details [user] (select-keys user [:email :first_name :last_login :is_qbnewb :is_superuser :id :last_name :date_joined :common_name :locale])) (defn- segment-response [segment] (-> (into {} segment) (dissoc :id :table_id) (update :creator #(into {} %)) (update :created_at some?) (update :updated_at some?))) ;; ## /api/segment/* AUTHENTICATION Tests ;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same ;; authentication test on every single individual endpoint (deftest authentication-test (is (= (get middleware.u/response-unauthentic :body) (http/client :get 401 "segment"))) (is (= (get middleware.u/response-unauthentic :body) (http/client :put 401 "segment/13")))) ;; ## POST /api/segment (deftest create-segment-permissions-test (testing "POST /api/segment" (testing "Test security. Requires superuser perms." (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :post 403 "segment" {:name "abc" :table_id 123 :definition {}})))))) (deftest create-segment-input-validation-test (testing "POST /api/segment" (is (= {:errors {:name "value must be a non-blank string."}} (mt/user-http-request :crowberto :post 400 "segment" {}))) (is (= {:errors {:table_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc"}))) (is (= {:errors {:table_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc" :table_id "foobar"}))) (is (= {:errors {:definition "value must be a map."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc" :table_id 123}))) (is (= {:errors {:definition "value must be a map."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc" :table_id 123 :definition "foobar"}))))) (deftest create-segment-test (mt/with-temp* [Database [{database-id :id}] Table [{:keys [id]} {:db_id database-id}]] (is (= {:name "A Segment" :description "I did it!" :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :crowberto) :creator (user-details (mt/fetch-user :crowberto)) :created_at true :updated_at true :archived false :definition {:filter ["=" ["field" 10 nil] 20]}} (segment-response (mt/user-http-request :crowberto :post 200 "segment" {:name "A Segment" :description "I did it!" :show_in_getting_started false :caveats nil :points_of_interest nil :table_id id :definition {:filter [:= [:field-id 10] 20]}})))))) ;; ## PUT /api/segment (deftest update-permissions-test (testing "PUT /api/segment/:id" (testing "test security. requires superuser perms" (mt/with-temp Segment [segment] (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 (str "segment/" (:id segment)) {:name "abc" :definition {} :revision_message "something different"}))))))) (deftest update-input-validation-test (testing "PUT /api/segment/:id" (is (= {:errors {:name "value may be nil, or if non-nil, value must be a non-blank string."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name ""}))) (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc"}))) (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc" :revision_message ""}))) (is (= {:errors {:definition "value may be nil, or if non-nil, value must be a map."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc" :revision_message "123" :definition "foobar"}))))) (deftest update-test (testing "PUT /api/segment/:id" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:table_id table-id}]] (is (= {:name "<NAME>" :description nil :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :rasta) :creator (user-details (mt/fetch-user :rasta)) :created_at true :updated_at true :archived false :definition {:filter ["!=" ["field" 2 nil] "cans"]}} (segment-response (mt/user-http-request :crowberto :put 200 (format "segment/%d" id) {:id id :name "<NAME>" :description nil :show_in_getting_started false :caveats nil :points_of_interest nil :table_id 456 :revision_message "I got me some revisions" :definition {:filter [:!= [:field-id 2] "cans"]}}))))))) (deftest partial-update-test (testing "PUT /api/segment/:id" (testing "Can I update a segment's name without specifying `:points_of_interest` and `:show_in_getting_started`?" (mt/with-temp Segment [segment] ;; just make sure API call doesn't barf (is (some? (mt/user-http-request :crowberto :put 200 (str "segment/" (u/the-id segment)) {:name "Cool name" :revision_message "WOW HOW COOL" :definition {}}))))))) (deftest archive-test (testing "PUT /api/segment/:id" (testing "Can we archive a Segment with the PUT endpoint?" (mt/with-temp Segment [{:keys [id]}] (is (map? (mt/user-http-request :crowberto :put 200 (str "segment/" id) {:archived true, :revision_message "Archive the Segment"}))) (is (= true (db/select-one-field :archived Segment :id id))))))) (deftest unarchive-test (testing "PUT /api/segment/:id" (testing "Can we unarchive a Segment with the PUT endpoint?" (mt/with-temp Segment [{:keys [id]} {:archived true}] (is (map? (mt/user-http-request :crowberto :put 200 (str "segment/" id) {:archived false, :revision_message "Unarchive the Segment"}))) (is (= false (db/select-one-field :archived Segment :id id))))))) ;; ## DELETE /api/segment/:id (deftest delete-permissions-test (testing "DELETE /api/segment/:id" (testing "test security. requires superuser perms" (mt/with-temp Segment [{:keys [id]}] (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :delete 403 (str "segment/" id) :revision_message "yeeeehaw!"))))))) (deftest delete-input-validation-test (testing "DELETE /api/segment/:id" (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :delete 400 "segment/1" {:name "abc"}))) (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :delete 400 "segment/1" :revision_message ""))))) (deftest delete-test (testing "DELETE /api/segment/:id" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:table_id table-id}]] (is (= nil (mt/user-http-request :crowberto :delete 204 (format "segment/%d" id) :revision_message "carryon"))) (testing "should still be able to fetch the archived segment" (is (= {:name "Toucans in the rainforest" :description "Lookin' for a blueberry" :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :rasta) :creator (user-details (mt/fetch-user :rasta)) :created_at true :updated_at true :archived true :definition nil} (-> (mt/user-http-request :crowberto :get 200 (format "segment/%d" id)) segment-response (dissoc :query_description)))))))) ;; ## GET /api/segment/:id (deftest fetch-segment-permissions-test (testing "GET /api/segment/:id" (testing "test security. Requires read perms for the Table it references" (mt/with-temp* [Database [db] Table [table {:db_id (u/the-id db)}] Segment [segment {:table_id (u/the-id table)}]] (perms/revoke-permissions! (group/all-users) db) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :get 403 (str "segment/" (u/the-id segment))))))))) (deftest fetch-segment-test (testing "GET /api/segment/:id" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto) :table_id table-id :definition {:filter [:= [:field-id 2] "cans"]}}]] (is (= {:name "Toucans in the rainforest" :description "Lookin' for a blueberry" :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :crowberto) :creator (user-details (mt/fetch-user :crowberto)) :created_at true :updated_at true :archived false :definition {:filter ["=" ["field" 2 nil] "cans"]}} (-> (mt/user-http-request :rasta :get 200 (format "segment/%d" id)) segment-response (dissoc :query_description))))))) ;; ## GET /api/segment/:id/revisions (deftest revisions-permissions-test (testing "GET /api/segment/:id/revisions" (testing "test security. Requires read perms for the Table it references" (mt/with-temp* [Database [db] Table [table {:db_id (u/the-id db)}] Segment [segment {:table_id (u/the-id table)}]] (perms/revoke-permissions! (group/all-users) db) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :get 403 (format "segment/%d/revisions" (u/the-id segment))))))))) (deftest revisions-test (testing "GET /api/segment/:id/revisions" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto) :table_id table-id :definition {:database 123 :query {:filter [:= [:field-id 2] "cans"]}}}] Revision [_ {:model "Segment" :model_id id :object {:name "b" :definition {:filter [:and [:> 1 25]]}} :is_creation true}] Revision [_ {:model "Segment" :model_id id :user_id (mt/user->id :crowberto) :object {:name "c" :definition {:filter [:and [:> 1 25]]}} :message "updated"}]] (is (= [{:is_reversion false :is_creation false :message "updated" :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:before "b" :after "c"}} :description "renamed this Segment from \"b\" to \"c\"."} {:is_reversion false :is_creation true :message nil :user (-> (user-details (mt/fetch-user :rasta)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:after "b"} :definition {:after {:filter [">" ["field" 1 nil] 25]}}} :description nil}] (for [revision (mt/user-http-request :rasta :get 200 (format "segment/%d/revisions" id))] (dissoc revision :timestamp :id))))))) ;; ## POST /api/segment/:id/revert (deftest revert-permissions-test (testing "POST /api/segment/:id/revert" (testing "test security. requires superuser perms" (mt/with-temp Segment [{:keys [id]}] (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :post 403 (format "segment/%d/revert" id) {:revision_id 56}))))))) (deftest revert-input-validation-test (testing "POST /api/segment/:id/revert" (is (= {:errors {:revision_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment/1/revert" {}))) (is (= {:errors {:revision_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment/1/revert" {:revision_id "foobar"}))))) (deftest revert-test (testing "POST /api/segment/:id/revert" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto) :table_id table-id :name "One Segment to rule them all, one segment to define them" :description "One segment to bring them all, and in the DataModel bind them" :show_in_getting_started false :caveats nil :points_of_interest nil :definition {:filter [:= [:field-id 2] "cans"]}}] Revision [{revision-id :id} {:model "Segment" :model_id id :object {:creator_id (mt/user->id :crowberto) :table_id table-id :name "One Segment to rule them all, one segment to define them" :description "One segment to bring them all, and in the DataModel bind them" :show_in_getting_started false :caveats nil :points_of_interest nil :definition {:filter [:= [:field-id 2] "cans"]}} :is_creation true}] Revision [_ {:model "Segment" :model_id id :user_id (mt/user->id :crowberto) :object {:creator_id (mt/user->id :crowberto) :table_id table-id :name "Changed Segment Name" :description "One segment to bring them all, and in the DataModel bind them" :show_in_getting_started false :caveats nil :points_of_interest nil :definition {:filter [:= [:field-id 2] "cans"]}} :message "updated"}]] (testing "the api response" (is (= {:is_reversion true :is_creation false :message nil :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:before "Changed Segment Name" :after "One Segment to rule them all, one segment to define them"}} :description "renamed this Segment from \"Changed Segment Name\" to \"One Segment to rule them all, one segment to define them\"."} (-> (mt/user-http-request :crowberto :post 200 (format "segment/%d/revert" id) {:revision_id revision-id}) (dissoc :id :timestamp))))) (testing "full list of final revisions, first one should be same as the revision returned by the endpoint" (is (= [{:is_reversion true :is_creation false :message nil :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:before "Changed Segment Name" :after "One Segment to rule them all, one segment to define them"}} :description "renamed this Segment from \"Changed Segment Name\" to \"One Segment to rule them all, one segment to define them\"."} {:is_reversion false :is_creation false :message "updated" :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:after "Changed Segment Name" :before "One Segment to rule them all, one segment to define them"}} :description "renamed this Segment from \"One Segment to rule them all, one segment to define them\" to \"Changed Segment Name\"."} {:is_reversion false :is_creation true :message nil :user (-> (user-details (mt/fetch-user :rasta)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:after "One Segment to rule them all, one segment to define them"} :description {:after "One segment to bring them all, and in the DataModel bind them"} :definition {:after {:filter ["=" ["field" 2 nil] "cans"]}}} :description nil}] (for [revision (mt/user-http-request :crowberto :get 200 (format "segment/%d/revisions" id))] (dissoc revision :timestamp :id)))))))) ;;; GET /api/segement/ (deftest list-test (testing "GET /api/segement/" (mt/with-temp* [Segment [segment-1 {:name "Segment 1"}] Segment [segment-2 {:name "Segment 2"}] ;; inactive segments shouldn't show up Segment [_ {:archived true}]] (is (= (mt/derecordize (hydrate [segment-1 segment-2] :creator)) (map #(dissoc % :query_description) (mt/user-http-request :rasta :get 200 "segment/"))))) (is (= [] (mt/user-http-request :rasta :get 200 "segment/"))))) (deftest related-entities-test (testing "GET /api/segment/:id/related" (testing "related/recommended entities" (mt/with-temp Segment [{segment-id :id}] (is (= #{:table :metrics :segments :linked-from} (-> (mt/user-http-request :crowberto :get 200 (format "segment/%s/related" segment-id)) keys set)))))))
true
(ns metabase.api.segment-test "Tests for /api/segment endpoints." (:require [clojure.test :refer :all] [metabase.http-client :as http] [metabase.models.database :refer [Database]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group] [metabase.models.revision :refer [Revision]] [metabase.models.segment :as segment :refer [Segment]] [metabase.models.table :refer [Table]] [metabase.server.middleware.util :as middleware.u] [metabase.test :as mt] [metabase.util :as u] [toucan.db :as db] [toucan.hydrate :refer [hydrate]])) ;; ## Helper Fns (defn- user-details [user] (select-keys user [:email :first_name :last_login :is_qbnewb :is_superuser :id :last_name :date_joined :common_name :locale])) (defn- segment-response [segment] (-> (into {} segment) (dissoc :id :table_id) (update :creator #(into {} %)) (update :created_at some?) (update :updated_at some?))) ;; ## /api/segment/* AUTHENTICATION Tests ;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same ;; authentication test on every single individual endpoint (deftest authentication-test (is (= (get middleware.u/response-unauthentic :body) (http/client :get 401 "segment"))) (is (= (get middleware.u/response-unauthentic :body) (http/client :put 401 "segment/13")))) ;; ## POST /api/segment (deftest create-segment-permissions-test (testing "POST /api/segment" (testing "Test security. Requires superuser perms." (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :post 403 "segment" {:name "abc" :table_id 123 :definition {}})))))) (deftest create-segment-input-validation-test (testing "POST /api/segment" (is (= {:errors {:name "value must be a non-blank string."}} (mt/user-http-request :crowberto :post 400 "segment" {}))) (is (= {:errors {:table_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc"}))) (is (= {:errors {:table_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc" :table_id "foobar"}))) (is (= {:errors {:definition "value must be a map."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc" :table_id 123}))) (is (= {:errors {:definition "value must be a map."}} (mt/user-http-request :crowberto :post 400 "segment" {:name "abc" :table_id 123 :definition "foobar"}))))) (deftest create-segment-test (mt/with-temp* [Database [{database-id :id}] Table [{:keys [id]} {:db_id database-id}]] (is (= {:name "A Segment" :description "I did it!" :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :crowberto) :creator (user-details (mt/fetch-user :crowberto)) :created_at true :updated_at true :archived false :definition {:filter ["=" ["field" 10 nil] 20]}} (segment-response (mt/user-http-request :crowberto :post 200 "segment" {:name "A Segment" :description "I did it!" :show_in_getting_started false :caveats nil :points_of_interest nil :table_id id :definition {:filter [:= [:field-id 10] 20]}})))))) ;; ## PUT /api/segment (deftest update-permissions-test (testing "PUT /api/segment/:id" (testing "test security. requires superuser perms" (mt/with-temp Segment [segment] (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 (str "segment/" (:id segment)) {:name "abc" :definition {} :revision_message "something different"}))))))) (deftest update-input-validation-test (testing "PUT /api/segment/:id" (is (= {:errors {:name "value may be nil, or if non-nil, value must be a non-blank string."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name ""}))) (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc"}))) (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc" :revision_message ""}))) (is (= {:errors {:definition "value may be nil, or if non-nil, value must be a map."}} (mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc" :revision_message "123" :definition "foobar"}))))) (deftest update-test (testing "PUT /api/segment/:id" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:table_id table-id}]] (is (= {:name "PI:NAME:<NAME>END_PI" :description nil :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :rasta) :creator (user-details (mt/fetch-user :rasta)) :created_at true :updated_at true :archived false :definition {:filter ["!=" ["field" 2 nil] "cans"]}} (segment-response (mt/user-http-request :crowberto :put 200 (format "segment/%d" id) {:id id :name "PI:NAME:<NAME>END_PI" :description nil :show_in_getting_started false :caveats nil :points_of_interest nil :table_id 456 :revision_message "I got me some revisions" :definition {:filter [:!= [:field-id 2] "cans"]}}))))))) (deftest partial-update-test (testing "PUT /api/segment/:id" (testing "Can I update a segment's name without specifying `:points_of_interest` and `:show_in_getting_started`?" (mt/with-temp Segment [segment] ;; just make sure API call doesn't barf (is (some? (mt/user-http-request :crowberto :put 200 (str "segment/" (u/the-id segment)) {:name "Cool name" :revision_message "WOW HOW COOL" :definition {}}))))))) (deftest archive-test (testing "PUT /api/segment/:id" (testing "Can we archive a Segment with the PUT endpoint?" (mt/with-temp Segment [{:keys [id]}] (is (map? (mt/user-http-request :crowberto :put 200 (str "segment/" id) {:archived true, :revision_message "Archive the Segment"}))) (is (= true (db/select-one-field :archived Segment :id id))))))) (deftest unarchive-test (testing "PUT /api/segment/:id" (testing "Can we unarchive a Segment with the PUT endpoint?" (mt/with-temp Segment [{:keys [id]} {:archived true}] (is (map? (mt/user-http-request :crowberto :put 200 (str "segment/" id) {:archived false, :revision_message "Unarchive the Segment"}))) (is (= false (db/select-one-field :archived Segment :id id))))))) ;; ## DELETE /api/segment/:id (deftest delete-permissions-test (testing "DELETE /api/segment/:id" (testing "test security. requires superuser perms" (mt/with-temp Segment [{:keys [id]}] (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :delete 403 (str "segment/" id) :revision_message "yeeeehaw!"))))))) (deftest delete-input-validation-test (testing "DELETE /api/segment/:id" (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :delete 400 "segment/1" {:name "abc"}))) (is (= {:errors {:revision_message "value must be a non-blank string."}} (mt/user-http-request :crowberto :delete 400 "segment/1" :revision_message ""))))) (deftest delete-test (testing "DELETE /api/segment/:id" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:table_id table-id}]] (is (= nil (mt/user-http-request :crowberto :delete 204 (format "segment/%d" id) :revision_message "carryon"))) (testing "should still be able to fetch the archived segment" (is (= {:name "Toucans in the rainforest" :description "Lookin' for a blueberry" :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :rasta) :creator (user-details (mt/fetch-user :rasta)) :created_at true :updated_at true :archived true :definition nil} (-> (mt/user-http-request :crowberto :get 200 (format "segment/%d" id)) segment-response (dissoc :query_description)))))))) ;; ## GET /api/segment/:id (deftest fetch-segment-permissions-test (testing "GET /api/segment/:id" (testing "test security. Requires read perms for the Table it references" (mt/with-temp* [Database [db] Table [table {:db_id (u/the-id db)}] Segment [segment {:table_id (u/the-id table)}]] (perms/revoke-permissions! (group/all-users) db) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :get 403 (str "segment/" (u/the-id segment))))))))) (deftest fetch-segment-test (testing "GET /api/segment/:id" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto) :table_id table-id :definition {:filter [:= [:field-id 2] "cans"]}}]] (is (= {:name "Toucans in the rainforest" :description "Lookin' for a blueberry" :show_in_getting_started false :caveats nil :points_of_interest nil :creator_id (mt/user->id :crowberto) :creator (user-details (mt/fetch-user :crowberto)) :created_at true :updated_at true :archived false :definition {:filter ["=" ["field" 2 nil] "cans"]}} (-> (mt/user-http-request :rasta :get 200 (format "segment/%d" id)) segment-response (dissoc :query_description))))))) ;; ## GET /api/segment/:id/revisions (deftest revisions-permissions-test (testing "GET /api/segment/:id/revisions" (testing "test security. Requires read perms for the Table it references" (mt/with-temp* [Database [db] Table [table {:db_id (u/the-id db)}] Segment [segment {:table_id (u/the-id table)}]] (perms/revoke-permissions! (group/all-users) db) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :get 403 (format "segment/%d/revisions" (u/the-id segment))))))))) (deftest revisions-test (testing "GET /api/segment/:id/revisions" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto) :table_id table-id :definition {:database 123 :query {:filter [:= [:field-id 2] "cans"]}}}] Revision [_ {:model "Segment" :model_id id :object {:name "b" :definition {:filter [:and [:> 1 25]]}} :is_creation true}] Revision [_ {:model "Segment" :model_id id :user_id (mt/user->id :crowberto) :object {:name "c" :definition {:filter [:and [:> 1 25]]}} :message "updated"}]] (is (= [{:is_reversion false :is_creation false :message "updated" :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:before "b" :after "c"}} :description "renamed this Segment from \"b\" to \"c\"."} {:is_reversion false :is_creation true :message nil :user (-> (user-details (mt/fetch-user :rasta)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:after "b"} :definition {:after {:filter [">" ["field" 1 nil] 25]}}} :description nil}] (for [revision (mt/user-http-request :rasta :get 200 (format "segment/%d/revisions" id))] (dissoc revision :timestamp :id))))))) ;; ## POST /api/segment/:id/revert (deftest revert-permissions-test (testing "POST /api/segment/:id/revert" (testing "test security. requires superuser perms" (mt/with-temp Segment [{:keys [id]}] (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :post 403 (format "segment/%d/revert" id) {:revision_id 56}))))))) (deftest revert-input-validation-test (testing "POST /api/segment/:id/revert" (is (= {:errors {:revision_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment/1/revert" {}))) (is (= {:errors {:revision_id "value must be an integer greater than zero."}} (mt/user-http-request :crowberto :post 400 "segment/1/revert" {:revision_id "foobar"}))))) (deftest revert-test (testing "POST /api/segment/:id/revert" (mt/with-temp* [Database [{database-id :id}] Table [{table-id :id} {:db_id database-id}] Segment [{:keys [id]} {:creator_id (mt/user->id :crowberto) :table_id table-id :name "One Segment to rule them all, one segment to define them" :description "One segment to bring them all, and in the DataModel bind them" :show_in_getting_started false :caveats nil :points_of_interest nil :definition {:filter [:= [:field-id 2] "cans"]}}] Revision [{revision-id :id} {:model "Segment" :model_id id :object {:creator_id (mt/user->id :crowberto) :table_id table-id :name "One Segment to rule them all, one segment to define them" :description "One segment to bring them all, and in the DataModel bind them" :show_in_getting_started false :caveats nil :points_of_interest nil :definition {:filter [:= [:field-id 2] "cans"]}} :is_creation true}] Revision [_ {:model "Segment" :model_id id :user_id (mt/user->id :crowberto) :object {:creator_id (mt/user->id :crowberto) :table_id table-id :name "Changed Segment Name" :description "One segment to bring them all, and in the DataModel bind them" :show_in_getting_started false :caveats nil :points_of_interest nil :definition {:filter [:= [:field-id 2] "cans"]}} :message "updated"}]] (testing "the api response" (is (= {:is_reversion true :is_creation false :message nil :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:before "Changed Segment Name" :after "One Segment to rule them all, one segment to define them"}} :description "renamed this Segment from \"Changed Segment Name\" to \"One Segment to rule them all, one segment to define them\"."} (-> (mt/user-http-request :crowberto :post 200 (format "segment/%d/revert" id) {:revision_id revision-id}) (dissoc :id :timestamp))))) (testing "full list of final revisions, first one should be same as the revision returned by the endpoint" (is (= [{:is_reversion true :is_creation false :message nil :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:before "Changed Segment Name" :after "One Segment to rule them all, one segment to define them"}} :description "renamed this Segment from \"Changed Segment Name\" to \"One Segment to rule them all, one segment to define them\"."} {:is_reversion false :is_creation false :message "updated" :user (-> (user-details (mt/fetch-user :crowberto)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:after "Changed Segment Name" :before "One Segment to rule them all, one segment to define them"}} :description "renamed this Segment from \"One Segment to rule them all, one segment to define them\" to \"Changed Segment Name\"."} {:is_reversion false :is_creation true :message nil :user (-> (user-details (mt/fetch-user :rasta)) (dissoc :email :date_joined :last_login :is_superuser :is_qbnewb)) :diff {:name {:after "One Segment to rule them all, one segment to define them"} :description {:after "One segment to bring them all, and in the DataModel bind them"} :definition {:after {:filter ["=" ["field" 2 nil] "cans"]}}} :description nil}] (for [revision (mt/user-http-request :crowberto :get 200 (format "segment/%d/revisions" id))] (dissoc revision :timestamp :id)))))))) ;;; GET /api/segement/ (deftest list-test (testing "GET /api/segement/" (mt/with-temp* [Segment [segment-1 {:name "Segment 1"}] Segment [segment-2 {:name "Segment 2"}] ;; inactive segments shouldn't show up Segment [_ {:archived true}]] (is (= (mt/derecordize (hydrate [segment-1 segment-2] :creator)) (map #(dissoc % :query_description) (mt/user-http-request :rasta :get 200 "segment/"))))) (is (= [] (mt/user-http-request :rasta :get 200 "segment/"))))) (deftest related-entities-test (testing "GET /api/segment/:id/related" (testing "related/recommended entities" (mt/with-temp Segment [{segment-id :id}] (is (= #{:table :metrics :segments :linked-from} (-> (mt/user-http-request :crowberto :get 200 (format "segment/%s/related" segment-id)) keys set)))))))
[ { "context": " \"Address\"\n \"Customer Name\"\n \"License Plate\"\n ", "end": 9154, "score": 0.9155482649803162, "start": 9141, "tag": "NAME", "value": "Customer Name" } ]
src/dashboard/couriers.clj
Purple-Services/dashboard-service
3
(ns dashboard.couriers (:require [bouncer.core :as b] [bouncer.validators :as v] [clojure.string :as s] [clojure.edn :as edn] [common.couriers :refer [parse-courier-zones]] [common.db :refer [conn !select !update mysql-escape-str]] [common.util :refer [in? split-on-comma get-event-time unix->full cents->dollars]] [dashboard.utils :as utils] [dashboard.db :as db] [clojure.data.csv :as csv] [clojure.java.io :as io] [ring.util.io :as ring-io] [clojure.java.jdbc :as sql])) (defn get-by-id "Get a courier from db by courier's id" [db-conn id] (let [courier (first (!select db-conn "couriers" ["*"] {:id id}))] (if (empty? courier) {:success false :error (str "There is no courier with id: " id)} (assoc (parse-courier-zones courier) :timestamp_created (/ (.getTime (:timestamp_created courier)) 1000))))) (defn include-lateness "Given a courier map m, return a map with :lateness included using the past 100 orders" [db-conn m] (let [db-orders (->> (!select db-conn "orders" ["*"] {} :append (str "ORDER BY target_time_start DESC LIMIT 100")) (map #(assoc % :was-late (let [completion-time (-> (str "kludgeFix 1|" (:event_log %)) (s/split #"\||\s") (->> (apply hash-map)) (get "complete"))] (and completion-time (> (Integer. completion-time) (:target_time_end %)))))))] (map (fn [courier] (assoc courier :lateness (let [orders (filter #(and (= (:courier_id %) (:id courier)) (= (:status %) "complete")) db-orders) total (count orders) late (count (filter :was-late orders))] (if (pos? total) (str (format "%.0f" (float (- 100 (* (/ late total) 100)))) "%") "No orders.")))) m))) (defn include-os-and-app-version "Given a courier map m, return a map with :os and :app_version" [db-conn m] (let [courier-ids (distinct (map :id m)) courier-users (!select db-conn "users" [:os :app_version :id] {} :custom-where (str "id IN (\"" (s/join "\",\"" (concat courier-ids)) "\")"))] (map (fn [courier] (let [user-courier (first (filter #(= (:id courier) (:id %)) courier-users))] (assoc courier :os (:os user-courier) :app_version (:app_version user-courier)))) m))) (defn include-arn-endpoint "Given a hash-map of couriers m, return a map with :arn_endpoint assoc'd onto each courier" [db-conn m] (let [courier-ids (distinct (map :id m)) courier-users (!select db-conn "users" [:arn_endpoint :id] {} :custom-where (str "id IN (\"" (s/join "\",\"" (concat courier-ids)) "\")"))] (map (fn [courier] (let [user-courier (first (filter #(= (:id courier) (:id %)) courier-users))] (assoc courier :arn_endpoint (:arn_endpoint user-courier)))) m))) (def courier-validations {:zones [;; verify that the zone assignments can be read as edn ;; must be done first to prevent throwing an error ;; from edn-read [#(every? identity (->> % split-on-comma (map utils/edn-read?))) :message (str "Zones assignments must be " "comma-separated integer " "(whole number) values!") ] ;; verify that all zones are integers [#(every? integer? (->> % split-on-comma (map edn/read-string) (filter (comp not nil?)))) :message (str "All zones must be integer (whole number) " "values!")] ;; verify that all zone assignments exist [#(let [existant-zones-set (set (map :id (!select (conn) "zones" [:id] {}))) zones (->> % split-on-comma (map edn/read-string) (filter (comp not nil?)))] (every? identity (map (fn [zone] (contains? existant-zones-set zone)) zones))) :message (str "All zones in assignment must exist")]] :active [v/required v/boolean]}) (defn update-courier! "Update the zones for courier with user-id" [db-conn courier] ;; make sure the zones string will split into valid edn elements (if (b/valid? courier courier-validations) (let [{:keys [id zones active]} courier zones-str (->> zones split-on-comma (map edn/read-string) (filter (comp not nil?)) set sort (s/join ",")) ;; have to manually get this, get-by-id for courier process ;; the courier and leads to problems with timestamp_created db-courier (first (!select db-conn "couriers" ["*"] {:id id})) update-result (!update db-conn "couriers" (assoc db-courier :zones zones-str :active active) {:id id})] (if (:success update-result) (assoc update-result :id (:id db-courier)) {:success false :message "database errror"})) {:success false :validation (b/validate courier courier-validations)})) (defn download-courier-orders [db-conn courier-id] (let [results (db/raw-sql-query db-conn [(str "SELECT orders.id as `id`, " "orders.status as `status`, " "date_format(convert_tz(orders.timestamp_created, \"UTC\", " "\"America/Los_Angeles\"),\"%Y-%m-%d %H:%i:%S\") as `timestamp_created`, " "orders.event_log as `event_log`, " "orders.target_time_end as `target_time_end`, " "orders.auto_assign_note as `auto_assign_note`, " "orders.address_street as `address_street`, " "orders.address_zip as `address_zip`, " "users.name as `customer_name`, " "orders.license_plate as `license_plate`, " "orders.gas_type as `gas_type`, " "orders.gallons as `gallons`, " "if(orders.is_top_tier, 'Yes', 'No') as `is_top_tier` " "FROM `orders` " "LEFT JOIN users ON orders.user_id = users.id " "WHERE orders.courier_id = \"" (mysql-escape-str courier-id) "\" " "ORDER BY timestamp_created DESC")])] (ring-io/piped-input-stream (fn [ostream] (let [writer (io/writer ostream)] (csv/write-csv writer (apply vector (concat [["Order ID" "Status" "Time Placed" "Time Assigned" "Time Completed" "Deadline" "Duration" "Assigned By" "Address" "Customer Name" "License Plate" "Octane" "Gallons" "Top Tier?"]] (map (fn [o] (let [time-assigned (get-event-time (:event_log o) "assigned") time-completed (get-event-time (:event_log o) "complete")] (vec [(:id o) (:status o) (:timestamp_created o) (when time-assigned (unix->full time-assigned)) (when time-completed (unix->full time-completed)) (unix->full (:target_time_end o)) (when (and time-assigned time-completed) (let [diff (- time-completed time-assigned) hours (quot diff 3600) minutes (quot (mod diff 3600) 60)] (str hours "' " minutes "\""))) (:auto_assign_note o) (str (:address_street o) ", " (:address_zip o)) (:customer_name o) (:license_plate o) (:gas_type o) (:gallons o) (:is_top_tier o)]))) results)))) (.flush writer)))))) (defn download-courier-statistics [db-conn from-date to-date] (let [orders (db/raw-sql-query db-conn [(str "SELECT orders.id as `id`, " "orders.courier_id as `courier_id`, " "users.name as `courier_name`, " "orders.status as `status`, " "date_format(convert_tz(orders.timestamp_created, \"UTC\", " "\"America/Los_Angeles\"),\"%Y-%m-%d %H:%i:%S\") as `timestamp_created`, " "orders.event_log as `event_log`, " "orders.target_time_end as `target_time_end`, " "orders.number_rating as `number_rating`, " "orders.gas_type as `gas_type`, " "orders.gas_price as `gas_price`, " "orders.gallons as `gallons` " "FROM `orders` " "LEFT JOIN users ON orders.courier_id = users.id " "WHERE orders.target_time_start >= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") " AND orders.target_time_start <= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") "AND orders.status = 'complete' " "AND orders.courier_id != '' " "ORDER BY orders.timestamp_created DESC")]) fleet-deliveries (db/raw-sql-query db-conn [(str "SELECT fleet_deliveries.id as `id`, " "fleet_deliveries.courier_id as `courier_id`, " "fleet_deliveries.gallons as `gallons`, " "fleet_deliveries.total_price as `total_price`, " "fleet_deliveries.gas_price as `gas_price`, " "fleet_deliveries.gas_type as `gas_type`, " "fleet_deliveries.timestamp_recorded as `timestamp_recorded` " "FROM `fleet_deliveries` " "WHERE fleet_deliveries.timestamp_recorded >= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") " AND fleet_deliveries.timestamp_recorded <= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") "AND fleet_deliveries.deleted != 1 " "ORDER BY fleet_deliveries.timestamp_recorded DESC")]) gas-purchases (db/raw-sql-query db-conn [(str "SELECT gas_purchases.id as `id`, " "gas_purchases.courier_id as `courier_id`, " "gas_purchases.gallons as `gallons`, " "gas_purchases.total_price as `total_price`, " "gas_purchases.gas_type as `gas_type`, " "gas_purchases.timestamp_recorded as `timestamp_recorded` " "FROM `gas_purchases` " "WHERE gas_purchases.timestamp_recorded >= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") " AND gas_purchases.timestamp_recorded <= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") "AND gas_purchases.deleted != 1 " "ORDER BY gas_purchases.timestamp_recorded DESC")]) ;; all state log entries in date range state-log (db/raw-sql-query db-conn [(str "SELECT state_log.data as `data`, " "state_log.timestamp_created as `timestamp_created` " "FROM `state_log` " "WHERE state_log.timestamp_created >= " (str "CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC')") " AND state_log.timestamp_created <= " (str "CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC')"))]) _ (println "Time spent On Duty (number of Pings): " (reduce (fn [a b] (let [parsed-data (edn/read-string b) on-duty-ids (map :id (:on-duty-couriers parsed-data)) in-on-duty-ids? (partial in? on-duty-ids)] (into {} (map (fn [[k v]] [k (if (in-on-duty-ids? k) (inc v) v)]) a)))) (into {} (map (juxt identity (constantly 0)) (keys (group-by :courier_id orders)))) (map :data state-log))) grouped-orders (group-by :courier_id orders) grouped-fleet-deliveries (group-by :courier_id fleet-deliveries) grouped-gas-purchases (group-by :courier_id gas-purchases)] (ring-io/piped-input-stream (fn [ostream] (let [writer (io/writer ostream)] (csv/write-csv writer (apply vector (concat [["Courier Name" "# Orders" "# Fleet Deliveries" "# Gas Purchases" "Gallons Purchased" "Gallons Delivered (Orders)" "Gallons Delivered (Fleet Deliveries)" "Gallons Delivered Total - Purchased" "Avg. Gas Price Bought" "Avg. Gas Price Sold (Orders)" "Avg. Gas Price Sold (Fleet Deliveries)" "Avg. Assigned->Accepted Time" "Avg. Time Enroute" "Avg. Time Servicing" "Avg. Accepted->Completed Time" "% Late" "Avg. Rating (out of 5)" ]] (map (fn [[courier-id group-of-orders]] (let [gallons-purchased (->> (get grouped-gas-purchases courier-id) (map :gallons) (apply +) double) gallons-delivered-b2c (->> group-of-orders (map :gallons) (apply +) double) gallons-delivered-b2b (->> (get grouped-fleet-deliveries courier-id) (map :gallons) (apply +) double) avg-time-between-statuses (fn [start-status end-status] (let [diff (/ (apply + (map (fn [o] (- (get-event-time (:event_log o) end-status) (get-event-time (:event_log o) start-status))) group-of-orders)) (count group-of-orders)) hours (quot diff 3600) minutes (quot (mod diff 3600) 60)] (str hours "' " minutes "\"")))] (vec [(:courier_name (first group-of-orders)) (count group-of-orders) (count (get grouped-fleet-deliveries courier-id)) (count (get grouped-gas-purchases courier-id)) (format "%.2f" gallons-purchased) (format "%.2f" gallons-delivered-b2c) (format "%.2f" gallons-delivered-b2b) (format "%.2f" (- (+ gallons-delivered-b2c gallons-delivered-b2b) gallons-purchased)) (some->> (get grouped-gas-purchases courier-id) (map #(/ (:total_price %) (:gallons %))) (apply +) (#(/ % (count (get grouped-gas-purchases courier-id)))) int cents->dollars) (some->> group-of-orders (map :gas_price) (apply +) (#(/ % (count group-of-orders))) int cents->dollars) (some->> (get grouped-fleet-deliveries courier-id) (map :gas_price) (apply +) (#(/ % (count (get grouped-fleet-deliveries courier-id)))) int cents->dollars) (avg-time-between-statuses "assigned" "accepted") (avg-time-between-statuses "enroute" "servicing") (avg-time-between-statuses "servicing" "complete") (avg-time-between-statuses "accepted" "complete") (str (format "%.2f" (double (* 100 (/ (count (filter (fn [o] (> (get-event-time (:event_log o) "complete") (:target_time_end o))) group-of-orders)) (count group-of-orders))))) "%") (let [rated-orders (filter :number_rating group-of-orders)] (if (empty? rated-orders) "None" (format "%.2f" (double (/ (apply + (map :number_rating rated-orders)) (count rated-orders)))))) ]))) grouped-orders)))) (.flush writer))))))
30973
(ns dashboard.couriers (:require [bouncer.core :as b] [bouncer.validators :as v] [clojure.string :as s] [clojure.edn :as edn] [common.couriers :refer [parse-courier-zones]] [common.db :refer [conn !select !update mysql-escape-str]] [common.util :refer [in? split-on-comma get-event-time unix->full cents->dollars]] [dashboard.utils :as utils] [dashboard.db :as db] [clojure.data.csv :as csv] [clojure.java.io :as io] [ring.util.io :as ring-io] [clojure.java.jdbc :as sql])) (defn get-by-id "Get a courier from db by courier's id" [db-conn id] (let [courier (first (!select db-conn "couriers" ["*"] {:id id}))] (if (empty? courier) {:success false :error (str "There is no courier with id: " id)} (assoc (parse-courier-zones courier) :timestamp_created (/ (.getTime (:timestamp_created courier)) 1000))))) (defn include-lateness "Given a courier map m, return a map with :lateness included using the past 100 orders" [db-conn m] (let [db-orders (->> (!select db-conn "orders" ["*"] {} :append (str "ORDER BY target_time_start DESC LIMIT 100")) (map #(assoc % :was-late (let [completion-time (-> (str "kludgeFix 1|" (:event_log %)) (s/split #"\||\s") (->> (apply hash-map)) (get "complete"))] (and completion-time (> (Integer. completion-time) (:target_time_end %)))))))] (map (fn [courier] (assoc courier :lateness (let [orders (filter #(and (= (:courier_id %) (:id courier)) (= (:status %) "complete")) db-orders) total (count orders) late (count (filter :was-late orders))] (if (pos? total) (str (format "%.0f" (float (- 100 (* (/ late total) 100)))) "%") "No orders.")))) m))) (defn include-os-and-app-version "Given a courier map m, return a map with :os and :app_version" [db-conn m] (let [courier-ids (distinct (map :id m)) courier-users (!select db-conn "users" [:os :app_version :id] {} :custom-where (str "id IN (\"" (s/join "\",\"" (concat courier-ids)) "\")"))] (map (fn [courier] (let [user-courier (first (filter #(= (:id courier) (:id %)) courier-users))] (assoc courier :os (:os user-courier) :app_version (:app_version user-courier)))) m))) (defn include-arn-endpoint "Given a hash-map of couriers m, return a map with :arn_endpoint assoc'd onto each courier" [db-conn m] (let [courier-ids (distinct (map :id m)) courier-users (!select db-conn "users" [:arn_endpoint :id] {} :custom-where (str "id IN (\"" (s/join "\",\"" (concat courier-ids)) "\")"))] (map (fn [courier] (let [user-courier (first (filter #(= (:id courier) (:id %)) courier-users))] (assoc courier :arn_endpoint (:arn_endpoint user-courier)))) m))) (def courier-validations {:zones [;; verify that the zone assignments can be read as edn ;; must be done first to prevent throwing an error ;; from edn-read [#(every? identity (->> % split-on-comma (map utils/edn-read?))) :message (str "Zones assignments must be " "comma-separated integer " "(whole number) values!") ] ;; verify that all zones are integers [#(every? integer? (->> % split-on-comma (map edn/read-string) (filter (comp not nil?)))) :message (str "All zones must be integer (whole number) " "values!")] ;; verify that all zone assignments exist [#(let [existant-zones-set (set (map :id (!select (conn) "zones" [:id] {}))) zones (->> % split-on-comma (map edn/read-string) (filter (comp not nil?)))] (every? identity (map (fn [zone] (contains? existant-zones-set zone)) zones))) :message (str "All zones in assignment must exist")]] :active [v/required v/boolean]}) (defn update-courier! "Update the zones for courier with user-id" [db-conn courier] ;; make sure the zones string will split into valid edn elements (if (b/valid? courier courier-validations) (let [{:keys [id zones active]} courier zones-str (->> zones split-on-comma (map edn/read-string) (filter (comp not nil?)) set sort (s/join ",")) ;; have to manually get this, get-by-id for courier process ;; the courier and leads to problems with timestamp_created db-courier (first (!select db-conn "couriers" ["*"] {:id id})) update-result (!update db-conn "couriers" (assoc db-courier :zones zones-str :active active) {:id id})] (if (:success update-result) (assoc update-result :id (:id db-courier)) {:success false :message "database errror"})) {:success false :validation (b/validate courier courier-validations)})) (defn download-courier-orders [db-conn courier-id] (let [results (db/raw-sql-query db-conn [(str "SELECT orders.id as `id`, " "orders.status as `status`, " "date_format(convert_tz(orders.timestamp_created, \"UTC\", " "\"America/Los_Angeles\"),\"%Y-%m-%d %H:%i:%S\") as `timestamp_created`, " "orders.event_log as `event_log`, " "orders.target_time_end as `target_time_end`, " "orders.auto_assign_note as `auto_assign_note`, " "orders.address_street as `address_street`, " "orders.address_zip as `address_zip`, " "users.name as `customer_name`, " "orders.license_plate as `license_plate`, " "orders.gas_type as `gas_type`, " "orders.gallons as `gallons`, " "if(orders.is_top_tier, 'Yes', 'No') as `is_top_tier` " "FROM `orders` " "LEFT JOIN users ON orders.user_id = users.id " "WHERE orders.courier_id = \"" (mysql-escape-str courier-id) "\" " "ORDER BY timestamp_created DESC")])] (ring-io/piped-input-stream (fn [ostream] (let [writer (io/writer ostream)] (csv/write-csv writer (apply vector (concat [["Order ID" "Status" "Time Placed" "Time Assigned" "Time Completed" "Deadline" "Duration" "Assigned By" "Address" "<NAME>" "License Plate" "Octane" "Gallons" "Top Tier?"]] (map (fn [o] (let [time-assigned (get-event-time (:event_log o) "assigned") time-completed (get-event-time (:event_log o) "complete")] (vec [(:id o) (:status o) (:timestamp_created o) (when time-assigned (unix->full time-assigned)) (when time-completed (unix->full time-completed)) (unix->full (:target_time_end o)) (when (and time-assigned time-completed) (let [diff (- time-completed time-assigned) hours (quot diff 3600) minutes (quot (mod diff 3600) 60)] (str hours "' " minutes "\""))) (:auto_assign_note o) (str (:address_street o) ", " (:address_zip o)) (:customer_name o) (:license_plate o) (:gas_type o) (:gallons o) (:is_top_tier o)]))) results)))) (.flush writer)))))) (defn download-courier-statistics [db-conn from-date to-date] (let [orders (db/raw-sql-query db-conn [(str "SELECT orders.id as `id`, " "orders.courier_id as `courier_id`, " "users.name as `courier_name`, " "orders.status as `status`, " "date_format(convert_tz(orders.timestamp_created, \"UTC\", " "\"America/Los_Angeles\"),\"%Y-%m-%d %H:%i:%S\") as `timestamp_created`, " "orders.event_log as `event_log`, " "orders.target_time_end as `target_time_end`, " "orders.number_rating as `number_rating`, " "orders.gas_type as `gas_type`, " "orders.gas_price as `gas_price`, " "orders.gallons as `gallons` " "FROM `orders` " "LEFT JOIN users ON orders.courier_id = users.id " "WHERE orders.target_time_start >= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") " AND orders.target_time_start <= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") "AND orders.status = 'complete' " "AND orders.courier_id != '' " "ORDER BY orders.timestamp_created DESC")]) fleet-deliveries (db/raw-sql-query db-conn [(str "SELECT fleet_deliveries.id as `id`, " "fleet_deliveries.courier_id as `courier_id`, " "fleet_deliveries.gallons as `gallons`, " "fleet_deliveries.total_price as `total_price`, " "fleet_deliveries.gas_price as `gas_price`, " "fleet_deliveries.gas_type as `gas_type`, " "fleet_deliveries.timestamp_recorded as `timestamp_recorded` " "FROM `fleet_deliveries` " "WHERE fleet_deliveries.timestamp_recorded >= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") " AND fleet_deliveries.timestamp_recorded <= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") "AND fleet_deliveries.deleted != 1 " "ORDER BY fleet_deliveries.timestamp_recorded DESC")]) gas-purchases (db/raw-sql-query db-conn [(str "SELECT gas_purchases.id as `id`, " "gas_purchases.courier_id as `courier_id`, " "gas_purchases.gallons as `gallons`, " "gas_purchases.total_price as `total_price`, " "gas_purchases.gas_type as `gas_type`, " "gas_purchases.timestamp_recorded as `timestamp_recorded` " "FROM `gas_purchases` " "WHERE gas_purchases.timestamp_recorded >= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") " AND gas_purchases.timestamp_recorded <= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") "AND gas_purchases.deleted != 1 " "ORDER BY gas_purchases.timestamp_recorded DESC")]) ;; all state log entries in date range state-log (db/raw-sql-query db-conn [(str "SELECT state_log.data as `data`, " "state_log.timestamp_created as `timestamp_created` " "FROM `state_log` " "WHERE state_log.timestamp_created >= " (str "CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC')") " AND state_log.timestamp_created <= " (str "CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC')"))]) _ (println "Time spent On Duty (number of Pings): " (reduce (fn [a b] (let [parsed-data (edn/read-string b) on-duty-ids (map :id (:on-duty-couriers parsed-data)) in-on-duty-ids? (partial in? on-duty-ids)] (into {} (map (fn [[k v]] [k (if (in-on-duty-ids? k) (inc v) v)]) a)))) (into {} (map (juxt identity (constantly 0)) (keys (group-by :courier_id orders)))) (map :data state-log))) grouped-orders (group-by :courier_id orders) grouped-fleet-deliveries (group-by :courier_id fleet-deliveries) grouped-gas-purchases (group-by :courier_id gas-purchases)] (ring-io/piped-input-stream (fn [ostream] (let [writer (io/writer ostream)] (csv/write-csv writer (apply vector (concat [["Courier Name" "# Orders" "# Fleet Deliveries" "# Gas Purchases" "Gallons Purchased" "Gallons Delivered (Orders)" "Gallons Delivered (Fleet Deliveries)" "Gallons Delivered Total - Purchased" "Avg. Gas Price Bought" "Avg. Gas Price Sold (Orders)" "Avg. Gas Price Sold (Fleet Deliveries)" "Avg. Assigned->Accepted Time" "Avg. Time Enroute" "Avg. Time Servicing" "Avg. Accepted->Completed Time" "% Late" "Avg. Rating (out of 5)" ]] (map (fn [[courier-id group-of-orders]] (let [gallons-purchased (->> (get grouped-gas-purchases courier-id) (map :gallons) (apply +) double) gallons-delivered-b2c (->> group-of-orders (map :gallons) (apply +) double) gallons-delivered-b2b (->> (get grouped-fleet-deliveries courier-id) (map :gallons) (apply +) double) avg-time-between-statuses (fn [start-status end-status] (let [diff (/ (apply + (map (fn [o] (- (get-event-time (:event_log o) end-status) (get-event-time (:event_log o) start-status))) group-of-orders)) (count group-of-orders)) hours (quot diff 3600) minutes (quot (mod diff 3600) 60)] (str hours "' " minutes "\"")))] (vec [(:courier_name (first group-of-orders)) (count group-of-orders) (count (get grouped-fleet-deliveries courier-id)) (count (get grouped-gas-purchases courier-id)) (format "%.2f" gallons-purchased) (format "%.2f" gallons-delivered-b2c) (format "%.2f" gallons-delivered-b2b) (format "%.2f" (- (+ gallons-delivered-b2c gallons-delivered-b2b) gallons-purchased)) (some->> (get grouped-gas-purchases courier-id) (map #(/ (:total_price %) (:gallons %))) (apply +) (#(/ % (count (get grouped-gas-purchases courier-id)))) int cents->dollars) (some->> group-of-orders (map :gas_price) (apply +) (#(/ % (count group-of-orders))) int cents->dollars) (some->> (get grouped-fleet-deliveries courier-id) (map :gas_price) (apply +) (#(/ % (count (get grouped-fleet-deliveries courier-id)))) int cents->dollars) (avg-time-between-statuses "assigned" "accepted") (avg-time-between-statuses "enroute" "servicing") (avg-time-between-statuses "servicing" "complete") (avg-time-between-statuses "accepted" "complete") (str (format "%.2f" (double (* 100 (/ (count (filter (fn [o] (> (get-event-time (:event_log o) "complete") (:target_time_end o))) group-of-orders)) (count group-of-orders))))) "%") (let [rated-orders (filter :number_rating group-of-orders)] (if (empty? rated-orders) "None" (format "%.2f" (double (/ (apply + (map :number_rating rated-orders)) (count rated-orders)))))) ]))) grouped-orders)))) (.flush writer))))))
true
(ns dashboard.couriers (:require [bouncer.core :as b] [bouncer.validators :as v] [clojure.string :as s] [clojure.edn :as edn] [common.couriers :refer [parse-courier-zones]] [common.db :refer [conn !select !update mysql-escape-str]] [common.util :refer [in? split-on-comma get-event-time unix->full cents->dollars]] [dashboard.utils :as utils] [dashboard.db :as db] [clojure.data.csv :as csv] [clojure.java.io :as io] [ring.util.io :as ring-io] [clojure.java.jdbc :as sql])) (defn get-by-id "Get a courier from db by courier's id" [db-conn id] (let [courier (first (!select db-conn "couriers" ["*"] {:id id}))] (if (empty? courier) {:success false :error (str "There is no courier with id: " id)} (assoc (parse-courier-zones courier) :timestamp_created (/ (.getTime (:timestamp_created courier)) 1000))))) (defn include-lateness "Given a courier map m, return a map with :lateness included using the past 100 orders" [db-conn m] (let [db-orders (->> (!select db-conn "orders" ["*"] {} :append (str "ORDER BY target_time_start DESC LIMIT 100")) (map #(assoc % :was-late (let [completion-time (-> (str "kludgeFix 1|" (:event_log %)) (s/split #"\||\s") (->> (apply hash-map)) (get "complete"))] (and completion-time (> (Integer. completion-time) (:target_time_end %)))))))] (map (fn [courier] (assoc courier :lateness (let [orders (filter #(and (= (:courier_id %) (:id courier)) (= (:status %) "complete")) db-orders) total (count orders) late (count (filter :was-late orders))] (if (pos? total) (str (format "%.0f" (float (- 100 (* (/ late total) 100)))) "%") "No orders.")))) m))) (defn include-os-and-app-version "Given a courier map m, return a map with :os and :app_version" [db-conn m] (let [courier-ids (distinct (map :id m)) courier-users (!select db-conn "users" [:os :app_version :id] {} :custom-where (str "id IN (\"" (s/join "\",\"" (concat courier-ids)) "\")"))] (map (fn [courier] (let [user-courier (first (filter #(= (:id courier) (:id %)) courier-users))] (assoc courier :os (:os user-courier) :app_version (:app_version user-courier)))) m))) (defn include-arn-endpoint "Given a hash-map of couriers m, return a map with :arn_endpoint assoc'd onto each courier" [db-conn m] (let [courier-ids (distinct (map :id m)) courier-users (!select db-conn "users" [:arn_endpoint :id] {} :custom-where (str "id IN (\"" (s/join "\",\"" (concat courier-ids)) "\")"))] (map (fn [courier] (let [user-courier (first (filter #(= (:id courier) (:id %)) courier-users))] (assoc courier :arn_endpoint (:arn_endpoint user-courier)))) m))) (def courier-validations {:zones [;; verify that the zone assignments can be read as edn ;; must be done first to prevent throwing an error ;; from edn-read [#(every? identity (->> % split-on-comma (map utils/edn-read?))) :message (str "Zones assignments must be " "comma-separated integer " "(whole number) values!") ] ;; verify that all zones are integers [#(every? integer? (->> % split-on-comma (map edn/read-string) (filter (comp not nil?)))) :message (str "All zones must be integer (whole number) " "values!")] ;; verify that all zone assignments exist [#(let [existant-zones-set (set (map :id (!select (conn) "zones" [:id] {}))) zones (->> % split-on-comma (map edn/read-string) (filter (comp not nil?)))] (every? identity (map (fn [zone] (contains? existant-zones-set zone)) zones))) :message (str "All zones in assignment must exist")]] :active [v/required v/boolean]}) (defn update-courier! "Update the zones for courier with user-id" [db-conn courier] ;; make sure the zones string will split into valid edn elements (if (b/valid? courier courier-validations) (let [{:keys [id zones active]} courier zones-str (->> zones split-on-comma (map edn/read-string) (filter (comp not nil?)) set sort (s/join ",")) ;; have to manually get this, get-by-id for courier process ;; the courier and leads to problems with timestamp_created db-courier (first (!select db-conn "couriers" ["*"] {:id id})) update-result (!update db-conn "couriers" (assoc db-courier :zones zones-str :active active) {:id id})] (if (:success update-result) (assoc update-result :id (:id db-courier)) {:success false :message "database errror"})) {:success false :validation (b/validate courier courier-validations)})) (defn download-courier-orders [db-conn courier-id] (let [results (db/raw-sql-query db-conn [(str "SELECT orders.id as `id`, " "orders.status as `status`, " "date_format(convert_tz(orders.timestamp_created, \"UTC\", " "\"America/Los_Angeles\"),\"%Y-%m-%d %H:%i:%S\") as `timestamp_created`, " "orders.event_log as `event_log`, " "orders.target_time_end as `target_time_end`, " "orders.auto_assign_note as `auto_assign_note`, " "orders.address_street as `address_street`, " "orders.address_zip as `address_zip`, " "users.name as `customer_name`, " "orders.license_plate as `license_plate`, " "orders.gas_type as `gas_type`, " "orders.gallons as `gallons`, " "if(orders.is_top_tier, 'Yes', 'No') as `is_top_tier` " "FROM `orders` " "LEFT JOIN users ON orders.user_id = users.id " "WHERE orders.courier_id = \"" (mysql-escape-str courier-id) "\" " "ORDER BY timestamp_created DESC")])] (ring-io/piped-input-stream (fn [ostream] (let [writer (io/writer ostream)] (csv/write-csv writer (apply vector (concat [["Order ID" "Status" "Time Placed" "Time Assigned" "Time Completed" "Deadline" "Duration" "Assigned By" "Address" "PI:NAME:<NAME>END_PI" "License Plate" "Octane" "Gallons" "Top Tier?"]] (map (fn [o] (let [time-assigned (get-event-time (:event_log o) "assigned") time-completed (get-event-time (:event_log o) "complete")] (vec [(:id o) (:status o) (:timestamp_created o) (when time-assigned (unix->full time-assigned)) (when time-completed (unix->full time-completed)) (unix->full (:target_time_end o)) (when (and time-assigned time-completed) (let [diff (- time-completed time-assigned) hours (quot diff 3600) minutes (quot (mod diff 3600) 60)] (str hours "' " minutes "\""))) (:auto_assign_note o) (str (:address_street o) ", " (:address_zip o)) (:customer_name o) (:license_plate o) (:gas_type o) (:gallons o) (:is_top_tier o)]))) results)))) (.flush writer)))))) (defn download-courier-statistics [db-conn from-date to-date] (let [orders (db/raw-sql-query db-conn [(str "SELECT orders.id as `id`, " "orders.courier_id as `courier_id`, " "users.name as `courier_name`, " "orders.status as `status`, " "date_format(convert_tz(orders.timestamp_created, \"UTC\", " "\"America/Los_Angeles\"),\"%Y-%m-%d %H:%i:%S\") as `timestamp_created`, " "orders.event_log as `event_log`, " "orders.target_time_end as `target_time_end`, " "orders.number_rating as `number_rating`, " "orders.gas_type as `gas_type`, " "orders.gas_price as `gas_price`, " "orders.gallons as `gallons` " "FROM `orders` " "LEFT JOIN users ON orders.courier_id = users.id " "WHERE orders.target_time_start >= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") " AND orders.target_time_start <= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") "AND orders.status = 'complete' " "AND orders.courier_id != '' " "ORDER BY orders.timestamp_created DESC")]) fleet-deliveries (db/raw-sql-query db-conn [(str "SELECT fleet_deliveries.id as `id`, " "fleet_deliveries.courier_id as `courier_id`, " "fleet_deliveries.gallons as `gallons`, " "fleet_deliveries.total_price as `total_price`, " "fleet_deliveries.gas_price as `gas_price`, " "fleet_deliveries.gas_type as `gas_type`, " "fleet_deliveries.timestamp_recorded as `timestamp_recorded` " "FROM `fleet_deliveries` " "WHERE fleet_deliveries.timestamp_recorded >= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") " AND fleet_deliveries.timestamp_recorded <= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") "AND fleet_deliveries.deleted != 1 " "ORDER BY fleet_deliveries.timestamp_recorded DESC")]) gas-purchases (db/raw-sql-query db-conn [(str "SELECT gas_purchases.id as `id`, " "gas_purchases.courier_id as `courier_id`, " "gas_purchases.gallons as `gallons`, " "gas_purchases.total_price as `total_price`, " "gas_purchases.gas_type as `gas_type`, " "gas_purchases.timestamp_recorded as `timestamp_recorded` " "FROM `gas_purchases` " "WHERE gas_purchases.timestamp_recorded >= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") " AND gas_purchases.timestamp_recorded <= " (str "UNIX_TIMESTAMP(CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC'))") "AND gas_purchases.deleted != 1 " "ORDER BY gas_purchases.timestamp_recorded DESC")]) ;; all state log entries in date range state-log (db/raw-sql-query db-conn [(str "SELECT state_log.data as `data`, " "state_log.timestamp_created as `timestamp_created` " "FROM `state_log` " "WHERE state_log.timestamp_created >= " (str "CONVERT_TZ(STR_TO_DATE('" (-> from-date (str " 00:00:00") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC')") " AND state_log.timestamp_created <= " (str "CONVERT_TZ(STR_TO_DATE('" (-> to-date (str " 23:59:59") mysql-escape-str) "', '%Y-%m-%d %H:%i:%s'), 'America/Los_Angeles', 'UTC')"))]) _ (println "Time spent On Duty (number of Pings): " (reduce (fn [a b] (let [parsed-data (edn/read-string b) on-duty-ids (map :id (:on-duty-couriers parsed-data)) in-on-duty-ids? (partial in? on-duty-ids)] (into {} (map (fn [[k v]] [k (if (in-on-duty-ids? k) (inc v) v)]) a)))) (into {} (map (juxt identity (constantly 0)) (keys (group-by :courier_id orders)))) (map :data state-log))) grouped-orders (group-by :courier_id orders) grouped-fleet-deliveries (group-by :courier_id fleet-deliveries) grouped-gas-purchases (group-by :courier_id gas-purchases)] (ring-io/piped-input-stream (fn [ostream] (let [writer (io/writer ostream)] (csv/write-csv writer (apply vector (concat [["Courier Name" "# Orders" "# Fleet Deliveries" "# Gas Purchases" "Gallons Purchased" "Gallons Delivered (Orders)" "Gallons Delivered (Fleet Deliveries)" "Gallons Delivered Total - Purchased" "Avg. Gas Price Bought" "Avg. Gas Price Sold (Orders)" "Avg. Gas Price Sold (Fleet Deliveries)" "Avg. Assigned->Accepted Time" "Avg. Time Enroute" "Avg. Time Servicing" "Avg. Accepted->Completed Time" "% Late" "Avg. Rating (out of 5)" ]] (map (fn [[courier-id group-of-orders]] (let [gallons-purchased (->> (get grouped-gas-purchases courier-id) (map :gallons) (apply +) double) gallons-delivered-b2c (->> group-of-orders (map :gallons) (apply +) double) gallons-delivered-b2b (->> (get grouped-fleet-deliveries courier-id) (map :gallons) (apply +) double) avg-time-between-statuses (fn [start-status end-status] (let [diff (/ (apply + (map (fn [o] (- (get-event-time (:event_log o) end-status) (get-event-time (:event_log o) start-status))) group-of-orders)) (count group-of-orders)) hours (quot diff 3600) minutes (quot (mod diff 3600) 60)] (str hours "' " minutes "\"")))] (vec [(:courier_name (first group-of-orders)) (count group-of-orders) (count (get grouped-fleet-deliveries courier-id)) (count (get grouped-gas-purchases courier-id)) (format "%.2f" gallons-purchased) (format "%.2f" gallons-delivered-b2c) (format "%.2f" gallons-delivered-b2b) (format "%.2f" (- (+ gallons-delivered-b2c gallons-delivered-b2b) gallons-purchased)) (some->> (get grouped-gas-purchases courier-id) (map #(/ (:total_price %) (:gallons %))) (apply +) (#(/ % (count (get grouped-gas-purchases courier-id)))) int cents->dollars) (some->> group-of-orders (map :gas_price) (apply +) (#(/ % (count group-of-orders))) int cents->dollars) (some->> (get grouped-fleet-deliveries courier-id) (map :gas_price) (apply +) (#(/ % (count (get grouped-fleet-deliveries courier-id)))) int cents->dollars) (avg-time-between-statuses "assigned" "accepted") (avg-time-between-statuses "enroute" "servicing") (avg-time-between-statuses "servicing" "complete") (avg-time-between-statuses "accepted" "complete") (str (format "%.2f" (double (* 100 (/ (count (filter (fn [o] (> (get-event-time (:event_log o) "complete") (:target_time_end o))) group-of-orders)) (count group-of-orders))))) "%") (let [rated-orders (filter :number_rating group-of-orders)] (if (empty? rated-orders) "None" (format "%.2f" (double (/ (apply + (map :number_rating rated-orders)) (count rated-orders)))))) ]))) grouped-orders)))) (.flush writer))))))
[ { "context": ";; Copyright 2016 Timothy Brooks\n;;\n;; Licensed under the Apache License, Version ", "end": 32, "score": 0.9998681545257568, "start": 18, "tag": "NAME", "value": "Timothy Brooks" } ]
test/beehive/metrics_test.clj
tbrooks8/fault
2
;; Copyright 2016 Timothy Brooks ;; ;; 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 beehive.metrics-test (:require [clojure.test :refer :all] [beehive.metrics :as metrics]) (:import (net.uncontended.precipice.metrics.counts RollingCounts) (net.uncontended.precipice.metrics.latency LatencyRecorder TotalLatency))) (def clazz (beehive.enums/generate-result-class {:test-success true :test-error false :test-timeout false})) (def result-keys [:test-success :test-error :test-timeout]) (def key->enum (beehive.enums/enum-class-to-keyword->enum clazz)) (defn- assert-single-count-seq [metrics expected] (doseq [k result-keys] (let [{:keys [count start-millis end-millis]} (first (metrics/count-seq metrics k))] (is (= expected count)) (is (>= end-millis start-millis))))) (defn- assert-single-counts-seq [metrics expected] (let [{:keys [counts start-millis end-millis]} (first (metrics/counts-seq metrics))] (is (= (into {} (mapv (fn [k] [k expected]) result-keys)) counts)) (is (>= end-millis start-millis)))) (defn- assert-single-latency-seq [metrics expected] (doseq [k result-keys] (let [{:keys [latency start-millis end-millis]} (first (metrics/latency-seq metrics k))] (is (= expected latency)) (is (>= end-millis start-millis))))) (defn- assert-single-latencies-seq [metrics expected] (let [{:keys [latencies start-millis end-millis]} (first (metrics/latencies-seq metrics))] (is (= (into {} (mapv (fn [k] [k expected]) result-keys)) latencies)) (is (>= end-millis start-millis)))) (deftest counts-test (testing "Testing total counts return the results of the underlying java class" (let [metrics (metrics/total-counts clazz)] (metrics/increment metrics :test-success) (metrics/increment metrics :test-error) (metrics/increment metrics :test-timeout) (assert-single-count-seq metrics 1) (assert-single-counts-seq metrics 1))) (testing "Testing count recorder returns the results of the underlying java class" (let [metrics (metrics/count-recorder clazz)] (metrics/increment metrics :test-success) (metrics/increment metrics :test-success) (metrics/increment metrics :test-success) (metrics/add metrics :test-error 3) (metrics/add metrics :test-timeout 3) (let [{:keys [counts start-millis end-millis]} (first (metrics/counts-seq metrics))] (is (= {:test-error 3 :test-success 3 :test-timeout 3} counts)) (is (>= end-millis start-millis))) (assert-single-count-seq metrics 3) (assert-single-counts-seq metrics 3) (let [{:keys [counts start-millis end-millis] :as swapped} (metrics/counter-swap! metrics)] (is (= {:test-error 3 :test-success 3 :test-timeout 3} counts)) (is (>= end-millis start-millis)) (assert-single-count-seq metrics 0) (assert-single-counts-seq metrics 0) (metrics/counter-swap! metrics swapped) (is (= {:test-error 0 :test-success 0 :test-timeout 0} (:counts (metrics/counter-swap! metrics))))))) (testing "Testing rolling counts return the results of the underlying java class" (let [metrics (with-redefs [metrics/current-millis (fn [] 0)] (metrics/rolling-counts clazz 4 1 :seconds)) ^RollingCounts java-metrics (:precipice-metrics metrics) start-millis (:start-millis metrics)] (metrics/increment metrics :test-success) (metrics/increment metrics :test-error) (metrics/increment metrics :test-timeout) (with-redefs [metrics/current-millis (fn [] 3000)] ; (is (= 1 (vec (drop-last (metrics/get-count metrics :test-success))))) ) ; (is (= 1 (metrics/get-count metrics :test-error))) ; (is (= 1 (metrics/get-count metrics :test-timeout))) ;(is (= {:test-error 1 ; :test-success 1 ; :test-timeout 1} (:counts (first (metrics/get-counts metrics))))) ; ))) (deftest latency-test (testing "Testing total latency return the results of the underlying java class" (let [metrics (metrics/total-latency clazz) ^TotalLatency java-metrics (:precipice-metrics metrics)] (.write java-metrics (:test-success key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-error key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-timeout key->enum) 1 1 (System/nanoTime)) (assert-single-latency-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}) (assert-single-latencies-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}))) (testing "Testing latency recorder returns the results of the underlying java class" (let [metrics (metrics/latency-recorder clazz) ^LatencyRecorder java-metrics (:precipice-metrics metrics)] (.write java-metrics (:test-success key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-error key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-timeout key->enum) 1 1 (System/nanoTime)) (assert-single-latencies-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}) (assert-single-latency-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}) (let [{:keys [latencies start-millis end-millis] :as swapped} (metrics/latency-swap! metrics)] (is (= {:test-error {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1} :test-success {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1} :test-timeout {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}} latencies)) (is (>= end-millis start-millis)) (assert-single-latencies-seq metrics {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0}) (assert-single-latency-seq metrics {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0}) (metrics/latency-swap! metrics swapped) (is (= {:test-error {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0} :test-success {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0} :test-timeout {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0}} (:latencies (metrics/latency-swap! metrics))))))))
106335
;; Copyright 2016 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns beehive.metrics-test (:require [clojure.test :refer :all] [beehive.metrics :as metrics]) (:import (net.uncontended.precipice.metrics.counts RollingCounts) (net.uncontended.precipice.metrics.latency LatencyRecorder TotalLatency))) (def clazz (beehive.enums/generate-result-class {:test-success true :test-error false :test-timeout false})) (def result-keys [:test-success :test-error :test-timeout]) (def key->enum (beehive.enums/enum-class-to-keyword->enum clazz)) (defn- assert-single-count-seq [metrics expected] (doseq [k result-keys] (let [{:keys [count start-millis end-millis]} (first (metrics/count-seq metrics k))] (is (= expected count)) (is (>= end-millis start-millis))))) (defn- assert-single-counts-seq [metrics expected] (let [{:keys [counts start-millis end-millis]} (first (metrics/counts-seq metrics))] (is (= (into {} (mapv (fn [k] [k expected]) result-keys)) counts)) (is (>= end-millis start-millis)))) (defn- assert-single-latency-seq [metrics expected] (doseq [k result-keys] (let [{:keys [latency start-millis end-millis]} (first (metrics/latency-seq metrics k))] (is (= expected latency)) (is (>= end-millis start-millis))))) (defn- assert-single-latencies-seq [metrics expected] (let [{:keys [latencies start-millis end-millis]} (first (metrics/latencies-seq metrics))] (is (= (into {} (mapv (fn [k] [k expected]) result-keys)) latencies)) (is (>= end-millis start-millis)))) (deftest counts-test (testing "Testing total counts return the results of the underlying java class" (let [metrics (metrics/total-counts clazz)] (metrics/increment metrics :test-success) (metrics/increment metrics :test-error) (metrics/increment metrics :test-timeout) (assert-single-count-seq metrics 1) (assert-single-counts-seq metrics 1))) (testing "Testing count recorder returns the results of the underlying java class" (let [metrics (metrics/count-recorder clazz)] (metrics/increment metrics :test-success) (metrics/increment metrics :test-success) (metrics/increment metrics :test-success) (metrics/add metrics :test-error 3) (metrics/add metrics :test-timeout 3) (let [{:keys [counts start-millis end-millis]} (first (metrics/counts-seq metrics))] (is (= {:test-error 3 :test-success 3 :test-timeout 3} counts)) (is (>= end-millis start-millis))) (assert-single-count-seq metrics 3) (assert-single-counts-seq metrics 3) (let [{:keys [counts start-millis end-millis] :as swapped} (metrics/counter-swap! metrics)] (is (= {:test-error 3 :test-success 3 :test-timeout 3} counts)) (is (>= end-millis start-millis)) (assert-single-count-seq metrics 0) (assert-single-counts-seq metrics 0) (metrics/counter-swap! metrics swapped) (is (= {:test-error 0 :test-success 0 :test-timeout 0} (:counts (metrics/counter-swap! metrics))))))) (testing "Testing rolling counts return the results of the underlying java class" (let [metrics (with-redefs [metrics/current-millis (fn [] 0)] (metrics/rolling-counts clazz 4 1 :seconds)) ^RollingCounts java-metrics (:precipice-metrics metrics) start-millis (:start-millis metrics)] (metrics/increment metrics :test-success) (metrics/increment metrics :test-error) (metrics/increment metrics :test-timeout) (with-redefs [metrics/current-millis (fn [] 3000)] ; (is (= 1 (vec (drop-last (metrics/get-count metrics :test-success))))) ) ; (is (= 1 (metrics/get-count metrics :test-error))) ; (is (= 1 (metrics/get-count metrics :test-timeout))) ;(is (= {:test-error 1 ; :test-success 1 ; :test-timeout 1} (:counts (first (metrics/get-counts metrics))))) ; ))) (deftest latency-test (testing "Testing total latency return the results of the underlying java class" (let [metrics (metrics/total-latency clazz) ^TotalLatency java-metrics (:precipice-metrics metrics)] (.write java-metrics (:test-success key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-error key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-timeout key->enum) 1 1 (System/nanoTime)) (assert-single-latency-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}) (assert-single-latencies-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}))) (testing "Testing latency recorder returns the results of the underlying java class" (let [metrics (metrics/latency-recorder clazz) ^LatencyRecorder java-metrics (:precipice-metrics metrics)] (.write java-metrics (:test-success key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-error key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-timeout key->enum) 1 1 (System/nanoTime)) (assert-single-latencies-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}) (assert-single-latency-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}) (let [{:keys [latencies start-millis end-millis] :as swapped} (metrics/latency-swap! metrics)] (is (= {:test-error {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1} :test-success {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1} :test-timeout {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}} latencies)) (is (>= end-millis start-millis)) (assert-single-latencies-seq metrics {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0}) (assert-single-latency-seq metrics {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0}) (metrics/latency-swap! metrics swapped) (is (= {:test-error {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0} :test-success {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0} :test-timeout {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0}} (:latencies (metrics/latency-swap! metrics))))))))
true
;; Copyright 2016 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns beehive.metrics-test (:require [clojure.test :refer :all] [beehive.metrics :as metrics]) (:import (net.uncontended.precipice.metrics.counts RollingCounts) (net.uncontended.precipice.metrics.latency LatencyRecorder TotalLatency))) (def clazz (beehive.enums/generate-result-class {:test-success true :test-error false :test-timeout false})) (def result-keys [:test-success :test-error :test-timeout]) (def key->enum (beehive.enums/enum-class-to-keyword->enum clazz)) (defn- assert-single-count-seq [metrics expected] (doseq [k result-keys] (let [{:keys [count start-millis end-millis]} (first (metrics/count-seq metrics k))] (is (= expected count)) (is (>= end-millis start-millis))))) (defn- assert-single-counts-seq [metrics expected] (let [{:keys [counts start-millis end-millis]} (first (metrics/counts-seq metrics))] (is (= (into {} (mapv (fn [k] [k expected]) result-keys)) counts)) (is (>= end-millis start-millis)))) (defn- assert-single-latency-seq [metrics expected] (doseq [k result-keys] (let [{:keys [latency start-millis end-millis]} (first (metrics/latency-seq metrics k))] (is (= expected latency)) (is (>= end-millis start-millis))))) (defn- assert-single-latencies-seq [metrics expected] (let [{:keys [latencies start-millis end-millis]} (first (metrics/latencies-seq metrics))] (is (= (into {} (mapv (fn [k] [k expected]) result-keys)) latencies)) (is (>= end-millis start-millis)))) (deftest counts-test (testing "Testing total counts return the results of the underlying java class" (let [metrics (metrics/total-counts clazz)] (metrics/increment metrics :test-success) (metrics/increment metrics :test-error) (metrics/increment metrics :test-timeout) (assert-single-count-seq metrics 1) (assert-single-counts-seq metrics 1))) (testing "Testing count recorder returns the results of the underlying java class" (let [metrics (metrics/count-recorder clazz)] (metrics/increment metrics :test-success) (metrics/increment metrics :test-success) (metrics/increment metrics :test-success) (metrics/add metrics :test-error 3) (metrics/add metrics :test-timeout 3) (let [{:keys [counts start-millis end-millis]} (first (metrics/counts-seq metrics))] (is (= {:test-error 3 :test-success 3 :test-timeout 3} counts)) (is (>= end-millis start-millis))) (assert-single-count-seq metrics 3) (assert-single-counts-seq metrics 3) (let [{:keys [counts start-millis end-millis] :as swapped} (metrics/counter-swap! metrics)] (is (= {:test-error 3 :test-success 3 :test-timeout 3} counts)) (is (>= end-millis start-millis)) (assert-single-count-seq metrics 0) (assert-single-counts-seq metrics 0) (metrics/counter-swap! metrics swapped) (is (= {:test-error 0 :test-success 0 :test-timeout 0} (:counts (metrics/counter-swap! metrics))))))) (testing "Testing rolling counts return the results of the underlying java class" (let [metrics (with-redefs [metrics/current-millis (fn [] 0)] (metrics/rolling-counts clazz 4 1 :seconds)) ^RollingCounts java-metrics (:precipice-metrics metrics) start-millis (:start-millis metrics)] (metrics/increment metrics :test-success) (metrics/increment metrics :test-error) (metrics/increment metrics :test-timeout) (with-redefs [metrics/current-millis (fn [] 3000)] ; (is (= 1 (vec (drop-last (metrics/get-count metrics :test-success))))) ) ; (is (= 1 (metrics/get-count metrics :test-error))) ; (is (= 1 (metrics/get-count metrics :test-timeout))) ;(is (= {:test-error 1 ; :test-success 1 ; :test-timeout 1} (:counts (first (metrics/get-counts metrics))))) ; ))) (deftest latency-test (testing "Testing total latency return the results of the underlying java class" (let [metrics (metrics/total-latency clazz) ^TotalLatency java-metrics (:precipice-metrics metrics)] (.write java-metrics (:test-success key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-error key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-timeout key->enum) 1 1 (System/nanoTime)) (assert-single-latency-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}) (assert-single-latencies-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}))) (testing "Testing latency recorder returns the results of the underlying java class" (let [metrics (metrics/latency-recorder clazz) ^LatencyRecorder java-metrics (:precipice-metrics metrics)] (.write java-metrics (:test-success key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-error key->enum) 1 1 (System/nanoTime)) (.write java-metrics (:test-timeout key->enum) 1 1 (System/nanoTime)) (assert-single-latencies-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}) (assert-single-latency-seq metrics {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}) (let [{:keys [latencies start-millis end-millis] :as swapped} (metrics/latency-swap! metrics)] (is (= {:test-error {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1} :test-success {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1} :test-timeout {:10 1 :50 1 :90 1 :99 1 :99.9 1 :99.99 1 :99.999 1}} latencies)) (is (>= end-millis start-millis)) (assert-single-latencies-seq metrics {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0}) (assert-single-latency-seq metrics {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0}) (metrics/latency-swap! metrics swapped) (is (= {:test-error {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0} :test-success {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0} :test-timeout {:10 0 :50 0 :90 0 :99 0 :99.9 0 :99.99 0 :99.999 0}} (:latencies (metrics/latency-swap! metrics))))))))
[ { "context": "application registry.\"\n :url \"https://github.com/zalando-stups/kio\"\n\n :license {:name \"The Apache License, Vers", "end": 135, "score": 0.9984016418457031, "start": 122, "tag": "USERNAME", "value": "zalando-stups" }, { "context": ".kio.core\n :uberjar-name \"kio.jar\"\n\n :plugins [[io.sarnowski/lein-docker \"1.1.0\"]\n [org.z", "end": 769, "score": 0.7968453168869019, "start": 767, "tag": "USERNAME", "value": "io" }, { "context": "ore\n :uberjar-name \"kio.jar\"\n\n :plugins [[io.sarnowski/lein-docker \"1.1.0\"]\n [org.zalando.stu", "end": 779, "score": 0.8870611786842346, "start": 773, "tag": "USERNAME", "value": "nowski" }, { "context": "n [:developers\n [:developer {:id \"sarnowski\"}\n [:name \"Tobias Sarnowski\"]\n ", "end": 1689, "score": 0.9996640086174011, "start": 1680, "tag": "USERNAME", "value": "sarnowski" }, { "context": "loper {:id \"sarnowski\"}\n [:name \"Tobias Sarnowski\"]\n [:email \"tobias.sarnowski@zal", "end": 1734, "score": 0.9998493194580078, "start": 1718, "tag": "NAME", "value": "Tobias Sarnowski" }, { "context": "me \"Tobias Sarnowski\"]\n [:email \"tobias.sarnowski@zalando.de\"]\n [:role \"Maintainer\"]]]\n\n :te", "end": 1791, "score": 0.9999198913574219, "start": 1764, "tag": "EMAIL", "value": "tobias.sarnowski@zalando.de" } ]
project.clj
oporkka/kio
0
(defproject org.zalando.stups/kio "0.25.0-SNAPSHOT" :description "The application registry." :url "https://github.com/zalando-stups/kio" :license {:name "The Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.0.0" :dependencies [[org.clojure/clojure "1.10.0"] [org.zalando.stups/friboo "1.13.0"] [clj-time "0.13.0"] [org.zalando.stups/tokens "0.11.0-beta-2"] [yesql "0.5.3"] [org.clojure/core.memoize "0.7.1"]] :managed-dependencies [[org.flatland/ordered "1.5.7"] [marick/suchwow "6.0.2"]] :main ^:skip-aot org.zalando.stups.kio.core :uberjar-name "kio.jar" :plugins [[io.sarnowski/lein-docker "1.1.0"] [org.zalando.stups/lein-scm-source "0.3.0"] [lein-cloverage "1.0.7-SNAPSHOT"]] :docker {:image-name #=(eval (str (some-> (System/getenv "DEFAULT_DOCKER_REGISTRY") (str "/")) "stups/kio"))} :release-tasks [["vcs" "assert-committed"] ["clean"] ["test"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag"] ["uberjar"] ["scm-source"] ["docker" "build"] ["docker" "push"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]] :pom-addition [:developers [:developer {:id "sarnowski"} [:name "Tobias Sarnowski"] [:email "tobias.sarnowski@zalando.de"] [:role "Maintainer"]]] :test-selectors {:default :unit :unit :unit :integration :integration} :profiles {:uberjar {:aot :all} :dev {:repl-options {:init-ns user} :source-paths ["dev"] :dependencies [[org.clojure/tools.namespace "0.2.10"] [midje "1.9.8"] [org.clojure/java.classpath "0.2.3"]]}})
50620
(defproject org.zalando.stups/kio "0.25.0-SNAPSHOT" :description "The application registry." :url "https://github.com/zalando-stups/kio" :license {:name "The Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.0.0" :dependencies [[org.clojure/clojure "1.10.0"] [org.zalando.stups/friboo "1.13.0"] [clj-time "0.13.0"] [org.zalando.stups/tokens "0.11.0-beta-2"] [yesql "0.5.3"] [org.clojure/core.memoize "0.7.1"]] :managed-dependencies [[org.flatland/ordered "1.5.7"] [marick/suchwow "6.0.2"]] :main ^:skip-aot org.zalando.stups.kio.core :uberjar-name "kio.jar" :plugins [[io.sarnowski/lein-docker "1.1.0"] [org.zalando.stups/lein-scm-source "0.3.0"] [lein-cloverage "1.0.7-SNAPSHOT"]] :docker {:image-name #=(eval (str (some-> (System/getenv "DEFAULT_DOCKER_REGISTRY") (str "/")) "stups/kio"))} :release-tasks [["vcs" "assert-committed"] ["clean"] ["test"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag"] ["uberjar"] ["scm-source"] ["docker" "build"] ["docker" "push"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]] :pom-addition [:developers [:developer {:id "sarnowski"} [:name "<NAME>"] [:email "<EMAIL>"] [:role "Maintainer"]]] :test-selectors {:default :unit :unit :unit :integration :integration} :profiles {:uberjar {:aot :all} :dev {:repl-options {:init-ns user} :source-paths ["dev"] :dependencies [[org.clojure/tools.namespace "0.2.10"] [midje "1.9.8"] [org.clojure/java.classpath "0.2.3"]]}})
true
(defproject org.zalando.stups/kio "0.25.0-SNAPSHOT" :description "The application registry." :url "https://github.com/zalando-stups/kio" :license {:name "The Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.0.0" :dependencies [[org.clojure/clojure "1.10.0"] [org.zalando.stups/friboo "1.13.0"] [clj-time "0.13.0"] [org.zalando.stups/tokens "0.11.0-beta-2"] [yesql "0.5.3"] [org.clojure/core.memoize "0.7.1"]] :managed-dependencies [[org.flatland/ordered "1.5.7"] [marick/suchwow "6.0.2"]] :main ^:skip-aot org.zalando.stups.kio.core :uberjar-name "kio.jar" :plugins [[io.sarnowski/lein-docker "1.1.0"] [org.zalando.stups/lein-scm-source "0.3.0"] [lein-cloverage "1.0.7-SNAPSHOT"]] :docker {:image-name #=(eval (str (some-> (System/getenv "DEFAULT_DOCKER_REGISTRY") (str "/")) "stups/kio"))} :release-tasks [["vcs" "assert-committed"] ["clean"] ["test"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag"] ["uberjar"] ["scm-source"] ["docker" "build"] ["docker" "push"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]] :pom-addition [:developers [:developer {:id "sarnowski"} [:name "PI:NAME:<NAME>END_PI"] [:email "PI:EMAIL:<EMAIL>END_PI"] [:role "Maintainer"]]] :test-selectors {:default :unit :unit :unit :integration :integration} :profiles {:uberjar {:aot :all} :dev {:repl-options {:init-ns user} :source-paths ["dev"] :dependencies [[org.clojure/tools.namespace "0.2.10"] [midje "1.9.8"] [org.clojure/java.classpath "0.2.3"]]}})
[ { "context": "lex.arrays\n {:doc \"Array utilities.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2017-12-15\"})\n;;-------------------", "end": 249, "score": 0.86777663230896, "start": 213, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/main/clojure/palisades/lakes/collex/arrays.clj
palisades-lakes/collection-experiments
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.collex.arrays {:doc "Array utilities." :author "palisades dot lakes at gmail dot com" :version "2017-12-15"}) ;;---------------------------------------------------------------- ;; primitive arrays ;;---------------------------------------------------------------- (def ^Class boolean-array-type (let [a (boolean-array 0)] (class a))) (defn boolean-array? [x] (instance? boolean-array-type x)) (def ^Class byte-array-type (let [a (byte-array 0)] (class a))) (defn byte-array? [x] (instance? byte-array-type x)) (def ^Class char-array-type (let [a (char-array 0)] (class a))) (defn char-array? [x] (instance? char-array-type x)) (def ^Class double-array-type (let [a (double-array 0)] (class a))) (defn double-array? [x] (instance? double-array-type x)) (def ^Class float-array-type (let [a (float-array 0)] (class a))) (defn float-array? [x] (instance? float-array-type x)) (def ^Class int-array-type (let [a (int-array 0)] (class a))) (defn int-array? [x] (instance? int-array-type x)) (def ^Class long-array-type (let [a (long-array 0)] (class a))) (defn long-array? [x] (instance? long-array-type x)) (def ^Class short-array-type (let [a (short-array 0)] (class a))) (defn short-array? [x] (instance? short-array-type x)) ;;---------------------------------------------------------------- ;; more general arrays ;;---------------------------------------------------------------- (def ^Class object-array-type (let [a (object-array 0)] (class a))) (defn object-array? [x] (instance? object-array-type x)) (defn element-type ^Class [x] (let [c (.getClass ^Object x)] (assert (.isArray c)) (.getComponentType c))) (defn array? ([x] (and x (.isArray (.getClass ^Object x)))) ([x ^Class c] (and (array? x) (.equals c (element-type x))))) (defn elements-assignable-from? [x ^Class c] (and (array? x) (.isAssignableFrom (element-type x) c))) ;;----------------------------------------------------------------
55583
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.collex.arrays {:doc "Array utilities." :author "<EMAIL>" :version "2017-12-15"}) ;;---------------------------------------------------------------- ;; primitive arrays ;;---------------------------------------------------------------- (def ^Class boolean-array-type (let [a (boolean-array 0)] (class a))) (defn boolean-array? [x] (instance? boolean-array-type x)) (def ^Class byte-array-type (let [a (byte-array 0)] (class a))) (defn byte-array? [x] (instance? byte-array-type x)) (def ^Class char-array-type (let [a (char-array 0)] (class a))) (defn char-array? [x] (instance? char-array-type x)) (def ^Class double-array-type (let [a (double-array 0)] (class a))) (defn double-array? [x] (instance? double-array-type x)) (def ^Class float-array-type (let [a (float-array 0)] (class a))) (defn float-array? [x] (instance? float-array-type x)) (def ^Class int-array-type (let [a (int-array 0)] (class a))) (defn int-array? [x] (instance? int-array-type x)) (def ^Class long-array-type (let [a (long-array 0)] (class a))) (defn long-array? [x] (instance? long-array-type x)) (def ^Class short-array-type (let [a (short-array 0)] (class a))) (defn short-array? [x] (instance? short-array-type x)) ;;---------------------------------------------------------------- ;; more general arrays ;;---------------------------------------------------------------- (def ^Class object-array-type (let [a (object-array 0)] (class a))) (defn object-array? [x] (instance? object-array-type x)) (defn element-type ^Class [x] (let [c (.getClass ^Object x)] (assert (.isArray c)) (.getComponentType c))) (defn array? ([x] (and x (.isArray (.getClass ^Object x)))) ([x ^Class c] (and (array? x) (.equals c (element-type x))))) (defn elements-assignable-from? [x ^Class c] (and (array? x) (.isAssignableFrom (element-type x) c))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.collex.arrays {:doc "Array utilities." :author "PI:EMAIL:<EMAIL>END_PI" :version "2017-12-15"}) ;;---------------------------------------------------------------- ;; primitive arrays ;;---------------------------------------------------------------- (def ^Class boolean-array-type (let [a (boolean-array 0)] (class a))) (defn boolean-array? [x] (instance? boolean-array-type x)) (def ^Class byte-array-type (let [a (byte-array 0)] (class a))) (defn byte-array? [x] (instance? byte-array-type x)) (def ^Class char-array-type (let [a (char-array 0)] (class a))) (defn char-array? [x] (instance? char-array-type x)) (def ^Class double-array-type (let [a (double-array 0)] (class a))) (defn double-array? [x] (instance? double-array-type x)) (def ^Class float-array-type (let [a (float-array 0)] (class a))) (defn float-array? [x] (instance? float-array-type x)) (def ^Class int-array-type (let [a (int-array 0)] (class a))) (defn int-array? [x] (instance? int-array-type x)) (def ^Class long-array-type (let [a (long-array 0)] (class a))) (defn long-array? [x] (instance? long-array-type x)) (def ^Class short-array-type (let [a (short-array 0)] (class a))) (defn short-array? [x] (instance? short-array-type x)) ;;---------------------------------------------------------------- ;; more general arrays ;;---------------------------------------------------------------- (def ^Class object-array-type (let [a (object-array 0)] (class a))) (defn object-array? [x] (instance? object-array-type x)) (defn element-type ^Class [x] (let [c (.getClass ^Object x)] (assert (.isArray c)) (.getComponentType c))) (defn array? ([x] (and x (.isArray (.getClass ^Object x)))) ([x ^Class c] (and (array? x) (.equals c (element-type x))))) (defn elements-assignable-from? [x ^Class c] (and (array? x) (.isAssignableFrom (element-type x) c))) ;;----------------------------------------------------------------
[ { "context": " ;:key-password \"password\"\n ;:ssl-po", "end": 4930, "score": 0.9985736608505249, "start": 4922, "tag": "PASSWORD", "value": "password" } ]
src/master_menu/service.clj
mdgart/clojure_postgres_menu
3
(ns master-menu.service (:require [io.pedestal.http :as http] [io.pedestal.http.route :as route] [io.pedestal.http.body-params :as body-params] [ring.util.response :as ring-resp] [master-menu.databases.postgres.db :refer [db]] [master-menu.databases.postgres.sql :as sql])) ;; Defines common interceptors for json (def json-common-interceptors [(body-params/body-params) http/json-body]) ;; Define other specific interceptors ;; ;; Empty ;; insert section_item entries, both root or normal (defn create-root [json-params] (let [provider (:provider json-params) mf_account_id (:mf_account_id json-params)] (ring-resp/response (let [result (sql/insert-root db json-params)] (do (sql/insert-root-relations db { :section_item_id (:id (first result)) :mf_account_id mf_account_id :provider provider}) result))))) (defn create-section-item [json-params] (ring-resp/response (sql/insert-section-item db json-params))) (defn create-entry [{:keys [json-params] :as request}] (cond (clojure.string/blank? (str (:parent_id json-params))) (create-root json-params) :else (create-section-item json-params))) ;; update section_item entries (defn update-entry [{:keys [json-params] :as request}] (ring-resp/response (sql/update-section-item db json-params))) ;; delete section_item entries (defn delete-entry [{:keys [path-params] :as request}] (ring-resp/response (do (sql/delete-section-item-branch db path-params) path-params))) (defn delete-location-section-item [{:keys [path-params] :as request}] (ring-resp/response (do (sql/delete-location-section-item db path-params) path-params))) ;; Retrieve node (defn get-entry [{:keys [path-params] :as request}] (ring-resp/response {:result (sql/get-branch-by-node db {:node_labels (:node path-params)})})) ;; Retrieve node with location specific data (defn get-entry-location [{:keys [path-params] :as request}] (ring-resp/response {:result (sql/get-branch-by-node-with-location-data db { :node_labels (:node path-params) :mf_location_id (:mf_location_id path-params)})})) (defn find-roots-by-account-id [{:keys [path-params] :as request}] (ring-resp/response {:result (sql/find-roots-by-account-id db path-params)})) ;; upsert section_item entries (defn upsert-location-section-item [{:keys [json-params] :as request}] (ring-resp/response (sql/upsert-location-section-item db json-params))) ;; Routes (def routes #{["/get-entry/:node" :get (conj json-common-interceptors `get-entry)] ["/get-entry/:node/:mf_location_id" :get (conj json-common-interceptors `get-entry-location)] ["/find-roots-by-account-id/:id" :get (conj json-common-interceptors `find-roots-by-account-id)] ["/create-entry" :post (conj json-common-interceptors `create-entry)] ["/update-entry" :put (conj json-common-interceptors `update-entry)] ["/delete-entry/:id" :delete (conj json-common-interceptors `delete-entry)] ["/upsert-location-section-item" :put (conj json-common-interceptors `upsert-location-section-item)] ["/delete-location-section-item" :delete (conj json-common-interceptors `delete-location-section-item)]}) ;; Boilerplate ;; Consumed by master-menu.server/create-server ;; See http/default-interceptors for additional options you can configure (def service {:env :prod ;; You can bring your own non-default interceptors. Make ;; sure you include routing and set it up right for ;; dev-mode. If you do, many other keys for configuring ;; default interceptors will be ignored. ;; ::http/interceptors [] ::http/routes routes ;; Uncomment next line to enable CORS support, add ;; string(s) specifying scheme, host and port for ;; allowed source(s): ;; ;; "http://localhost:8080" ;; ;;::http/allowed-origins ["scheme://host:port"] ;; Root for resource interceptor that is available by default. ::http/resource-path "/public" ;; Either :jetty, :immutant or :tomcat (see comments in project.clj) ::http/type :jetty ;;::http/host "localhost" ::http/port 8890 ;; Options to pass to the container (Jetty) ::http/container-options {:h2c? true :h2? false ;:keystore "test/hp/keystore.jks" ;:key-password "password" ;:ssl-port 8443 :ssl? false}})
38900
(ns master-menu.service (:require [io.pedestal.http :as http] [io.pedestal.http.route :as route] [io.pedestal.http.body-params :as body-params] [ring.util.response :as ring-resp] [master-menu.databases.postgres.db :refer [db]] [master-menu.databases.postgres.sql :as sql])) ;; Defines common interceptors for json (def json-common-interceptors [(body-params/body-params) http/json-body]) ;; Define other specific interceptors ;; ;; Empty ;; insert section_item entries, both root or normal (defn create-root [json-params] (let [provider (:provider json-params) mf_account_id (:mf_account_id json-params)] (ring-resp/response (let [result (sql/insert-root db json-params)] (do (sql/insert-root-relations db { :section_item_id (:id (first result)) :mf_account_id mf_account_id :provider provider}) result))))) (defn create-section-item [json-params] (ring-resp/response (sql/insert-section-item db json-params))) (defn create-entry [{:keys [json-params] :as request}] (cond (clojure.string/blank? (str (:parent_id json-params))) (create-root json-params) :else (create-section-item json-params))) ;; update section_item entries (defn update-entry [{:keys [json-params] :as request}] (ring-resp/response (sql/update-section-item db json-params))) ;; delete section_item entries (defn delete-entry [{:keys [path-params] :as request}] (ring-resp/response (do (sql/delete-section-item-branch db path-params) path-params))) (defn delete-location-section-item [{:keys [path-params] :as request}] (ring-resp/response (do (sql/delete-location-section-item db path-params) path-params))) ;; Retrieve node (defn get-entry [{:keys [path-params] :as request}] (ring-resp/response {:result (sql/get-branch-by-node db {:node_labels (:node path-params)})})) ;; Retrieve node with location specific data (defn get-entry-location [{:keys [path-params] :as request}] (ring-resp/response {:result (sql/get-branch-by-node-with-location-data db { :node_labels (:node path-params) :mf_location_id (:mf_location_id path-params)})})) (defn find-roots-by-account-id [{:keys [path-params] :as request}] (ring-resp/response {:result (sql/find-roots-by-account-id db path-params)})) ;; upsert section_item entries (defn upsert-location-section-item [{:keys [json-params] :as request}] (ring-resp/response (sql/upsert-location-section-item db json-params))) ;; Routes (def routes #{["/get-entry/:node" :get (conj json-common-interceptors `get-entry)] ["/get-entry/:node/:mf_location_id" :get (conj json-common-interceptors `get-entry-location)] ["/find-roots-by-account-id/:id" :get (conj json-common-interceptors `find-roots-by-account-id)] ["/create-entry" :post (conj json-common-interceptors `create-entry)] ["/update-entry" :put (conj json-common-interceptors `update-entry)] ["/delete-entry/:id" :delete (conj json-common-interceptors `delete-entry)] ["/upsert-location-section-item" :put (conj json-common-interceptors `upsert-location-section-item)] ["/delete-location-section-item" :delete (conj json-common-interceptors `delete-location-section-item)]}) ;; Boilerplate ;; Consumed by master-menu.server/create-server ;; See http/default-interceptors for additional options you can configure (def service {:env :prod ;; You can bring your own non-default interceptors. Make ;; sure you include routing and set it up right for ;; dev-mode. If you do, many other keys for configuring ;; default interceptors will be ignored. ;; ::http/interceptors [] ::http/routes routes ;; Uncomment next line to enable CORS support, add ;; string(s) specifying scheme, host and port for ;; allowed source(s): ;; ;; "http://localhost:8080" ;; ;;::http/allowed-origins ["scheme://host:port"] ;; Root for resource interceptor that is available by default. ::http/resource-path "/public" ;; Either :jetty, :immutant or :tomcat (see comments in project.clj) ::http/type :jetty ;;::http/host "localhost" ::http/port 8890 ;; Options to pass to the container (Jetty) ::http/container-options {:h2c? true :h2? false ;:keystore "test/hp/keystore.jks" ;:key-password "<PASSWORD>" ;:ssl-port 8443 :ssl? false}})
true
(ns master-menu.service (:require [io.pedestal.http :as http] [io.pedestal.http.route :as route] [io.pedestal.http.body-params :as body-params] [ring.util.response :as ring-resp] [master-menu.databases.postgres.db :refer [db]] [master-menu.databases.postgres.sql :as sql])) ;; Defines common interceptors for json (def json-common-interceptors [(body-params/body-params) http/json-body]) ;; Define other specific interceptors ;; ;; Empty ;; insert section_item entries, both root or normal (defn create-root [json-params] (let [provider (:provider json-params) mf_account_id (:mf_account_id json-params)] (ring-resp/response (let [result (sql/insert-root db json-params)] (do (sql/insert-root-relations db { :section_item_id (:id (first result)) :mf_account_id mf_account_id :provider provider}) result))))) (defn create-section-item [json-params] (ring-resp/response (sql/insert-section-item db json-params))) (defn create-entry [{:keys [json-params] :as request}] (cond (clojure.string/blank? (str (:parent_id json-params))) (create-root json-params) :else (create-section-item json-params))) ;; update section_item entries (defn update-entry [{:keys [json-params] :as request}] (ring-resp/response (sql/update-section-item db json-params))) ;; delete section_item entries (defn delete-entry [{:keys [path-params] :as request}] (ring-resp/response (do (sql/delete-section-item-branch db path-params) path-params))) (defn delete-location-section-item [{:keys [path-params] :as request}] (ring-resp/response (do (sql/delete-location-section-item db path-params) path-params))) ;; Retrieve node (defn get-entry [{:keys [path-params] :as request}] (ring-resp/response {:result (sql/get-branch-by-node db {:node_labels (:node path-params)})})) ;; Retrieve node with location specific data (defn get-entry-location [{:keys [path-params] :as request}] (ring-resp/response {:result (sql/get-branch-by-node-with-location-data db { :node_labels (:node path-params) :mf_location_id (:mf_location_id path-params)})})) (defn find-roots-by-account-id [{:keys [path-params] :as request}] (ring-resp/response {:result (sql/find-roots-by-account-id db path-params)})) ;; upsert section_item entries (defn upsert-location-section-item [{:keys [json-params] :as request}] (ring-resp/response (sql/upsert-location-section-item db json-params))) ;; Routes (def routes #{["/get-entry/:node" :get (conj json-common-interceptors `get-entry)] ["/get-entry/:node/:mf_location_id" :get (conj json-common-interceptors `get-entry-location)] ["/find-roots-by-account-id/:id" :get (conj json-common-interceptors `find-roots-by-account-id)] ["/create-entry" :post (conj json-common-interceptors `create-entry)] ["/update-entry" :put (conj json-common-interceptors `update-entry)] ["/delete-entry/:id" :delete (conj json-common-interceptors `delete-entry)] ["/upsert-location-section-item" :put (conj json-common-interceptors `upsert-location-section-item)] ["/delete-location-section-item" :delete (conj json-common-interceptors `delete-location-section-item)]}) ;; Boilerplate ;; Consumed by master-menu.server/create-server ;; See http/default-interceptors for additional options you can configure (def service {:env :prod ;; You can bring your own non-default interceptors. Make ;; sure you include routing and set it up right for ;; dev-mode. If you do, many other keys for configuring ;; default interceptors will be ignored. ;; ::http/interceptors [] ::http/routes routes ;; Uncomment next line to enable CORS support, add ;; string(s) specifying scheme, host and port for ;; allowed source(s): ;; ;; "http://localhost:8080" ;; ;;::http/allowed-origins ["scheme://host:port"] ;; Root for resource interceptor that is available by default. ::http/resource-path "/public" ;; Either :jetty, :immutant or :tomcat (see comments in project.clj) ::http/type :jetty ;;::http/host "localhost" ::http/port 8890 ;; Options to pass to the container (Jetty) ::http/container-options {:h2c? true :h2? false ;:keystore "test/hp/keystore.jks" ;:key-password "PI:PASSWORD:<PASSWORD>END_PI" ;:ssl-port 8443 :ssl? false}})
[ { "context": "t\" \"Subject\" \"Message\"]\n [\"foo@bar.com\" \"test\" \"msg\"]\n [\"foo2@bar", "end": 439, "score": 0.9999189376831055, "start": 428, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": "@bar.com\" \"test\" \"msg\"]\n [\"foo2@bar.com\" \"test2\" \"msg2\"]] \"Queue\")\n url ", "end": 493, "score": 0.9999222755432129, "start": 481, "tag": "EMAIL", "value": "foo2@bar.com" } ]
test/appscriptlib/functions_test.cljc
charignon/mailmerge
3
(ns appscriptlib.functions-test (:require [appscriptlib.functions :as f] [appscriptlib.protocols :refer :all] [appscriptlib.fake-google-apis :refer :all] [clojure.test :refer :all])) (deftest mail-merge-basics (testing "Can send email" (let [log-sheet (fake-sheet [["Date" "Message"]] "Log") queue-sheet (fake-sheet [["Dest" "Subject" "Message"] ["foo@bar.com" "test" "msg"] ["foo2@bar.com" "test2" "msg2"]] "Queue") url "mailmerge" shdoc (fake-spreadsheet-document url [queue-sheet log-sheet]) date "2018-12-21" allfiles (atom {url shdoc}) gmail (fake-gmail) sheetapp (fake-document-app-backed-by-store allfiles)] (f/mail-merge {:gmail gmail :sheet sheetapp :transformer identity :url url :date date}) (is (= [[date "Processed 2 email"]] (getSheetValues log-sheet 2 1 20 20) )) (is (= 2 (count @(:emailqueue gmail)))))))
25028
(ns appscriptlib.functions-test (:require [appscriptlib.functions :as f] [appscriptlib.protocols :refer :all] [appscriptlib.fake-google-apis :refer :all] [clojure.test :refer :all])) (deftest mail-merge-basics (testing "Can send email" (let [log-sheet (fake-sheet [["Date" "Message"]] "Log") queue-sheet (fake-sheet [["Dest" "Subject" "Message"] ["<EMAIL>" "test" "msg"] ["<EMAIL>" "test2" "msg2"]] "Queue") url "mailmerge" shdoc (fake-spreadsheet-document url [queue-sheet log-sheet]) date "2018-12-21" allfiles (atom {url shdoc}) gmail (fake-gmail) sheetapp (fake-document-app-backed-by-store allfiles)] (f/mail-merge {:gmail gmail :sheet sheetapp :transformer identity :url url :date date}) (is (= [[date "Processed 2 email"]] (getSheetValues log-sheet 2 1 20 20) )) (is (= 2 (count @(:emailqueue gmail)))))))
true
(ns appscriptlib.functions-test (:require [appscriptlib.functions :as f] [appscriptlib.protocols :refer :all] [appscriptlib.fake-google-apis :refer :all] [clojure.test :refer :all])) (deftest mail-merge-basics (testing "Can send email" (let [log-sheet (fake-sheet [["Date" "Message"]] "Log") queue-sheet (fake-sheet [["Dest" "Subject" "Message"] ["PI:EMAIL:<EMAIL>END_PI" "test" "msg"] ["PI:EMAIL:<EMAIL>END_PI" "test2" "msg2"]] "Queue") url "mailmerge" shdoc (fake-spreadsheet-document url [queue-sheet log-sheet]) date "2018-12-21" allfiles (atom {url shdoc}) gmail (fake-gmail) sheetapp (fake-document-app-backed-by-store allfiles)] (f/mail-merge {:gmail gmail :sheet sheetapp :transformer identity :url url :date date}) (is (= [[date "Processed 2 email"]] (getSheetValues log-sheet 2 1 20 20) )) (is (= 2 (count @(:emailqueue gmail)))))))
[ { "context": "ref) [smaug bilbo gandalf])\n;;({:health 0, :name \"Smaug\"} {:health 294.0770800776351, :name \"Bilbo\"} {:ma", "end": 5889, "score": 0.989764392375946, "start": 5884, "tag": "NAME", "value": "Smaug" }, { "context": ":name \"Smaug\"} {:health 294.0770800776351, :name \"Bilbo\"} {:mana -1.871433951409358, :health 75, :name \"G", "end": 5932, "score": 0.991394579410553, "start": 5927, "tag": "NAME", "value": "Bilbo" }, { "context": "o\"} {:mana -1.871433951409358, :health 75, :name \"Gandalf\"})\n\n;ref-set来设置ref的状态\n;ref-set会把ref的事务内的状态设置到一个给定", "end": 5988, "score": 0.9967498183250427, "start": 5981, "tag": "NAME", "value": "Gandalf" }, { "context": "ef的事务内的状态设置到一个给定的值\n(dosync [ref-set bilbo {:name \"Bilbo\"}])\n\n;如果在当前事务提交之前,ref的状态在当前事务之外被改变了的话,这个事务会被重试。\n;", "end": 6077, "score": 0.7695117592811584, "start": 6072, "tag": "NAME", "value": "Bilbo" }, { "context": "-in [:health] + aid)))))\n\n(def smaug (character \"Smaug\" :health 500 :strength 400 :items (set (range 50)", "end": 7101, "score": 0.5897313952445984, "start": 7097, "tag": "NAME", "value": "maug" }, { "context": ":items (set (range 50))))\n(def bilbo (character \"Bilbo\" :health 100 :strength 100 :max-health 130))\n(d", "end": 7181, "score": 0.6057842969894409, "start": 7179, "tag": "NAME", "value": "il" }, { "context": "h] 95))\n;;{:strength 100, :max-health 130, :name \"Bilbo\", :items #{}, :health 95}\n(heal gandalf bilbo)\n;;", "end": 7379, "score": 0.8164994120597839, "start": 7374, "tag": "NAME", "value": "Bilbo" }, { "context": "bilbo)\n;;{:strength 100, :max-health 130, :name \"Bilbo\", :items #{}, :health 130}\n(heal gandalf bilbo)\n;", "end": 7474, "score": 0.7778052091598511, "start": 7470, "tag": "NAME", "value": "ilbo" } ]
src/clojure_tutorial/concurrent/ref.clj
edgar615/clojure-tutorial
1
(ns clojure-tutorial.concurrent.ref) ;ref是Clojure提供的协调引用类型。使用它可以保证多个线程可以交互地对这个ref进行操作 ; ref会一直保持在一个一致的状态,任何条件下都不会出现外界可见的一致性的状态 ; 在多个ref之间不可能会产生竞争条件 ; 不需要你手动地去使用锁、monitor或者其他底层的同步原语 ; 不可能出现死锁 ; 软件事务内存STM是任何对并发修改一系列内存地址的行为进行协调的方法。 ; 对于一系列ref的每个修改都是具有事务语义的,而每个STM事务保证对于ref的修改是: 原子的、一致的、隔离的 ; Clojure的STM满足ACID属性里面的A、C、I,而D(持久性)则不是STM所关心的,因为STM是纯内存的实现 ;创建游戏角色的函数 (defn character [name & {:as opts}] (ref (merge {:name name :items #{} :health 500} opts))) ;定义一些具体的角色 (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100)) (def gandalf (character "Gandalf" :health 75 :mana 750)) ;dosync规定了一个事务的边界,所有对于ref的修改毕夏要发生在一个事务里面,对于这些修改的处理是以同步的方式进行的。 ;也就是说,启动一个事务的线程在这个事务完成之前是不能继续执行其他代码的 ;两个对共享ref进行修改的事务冲突与否,是由对ref进行修改所使用的函数来决定的。 ; 有三个函数:alter、commute以及ref-set——它们每一个都有不同的、是否产生(或者避免)冲突的语义 ;把一个角色的武器转移到另外一个角色那里的函数 (defn loot [from to] (dosync (when-let [items (first (:items @from))] (alter to update-in [:items] conj items) (alter from update-in [:items] disj items)))) ;接受表达式作为参数,返回n个future (defmacro futures [n & exprs] (vec (for [_ (range n) expr exprs] `(future ~expr)))) ;wait-futures,始终返回nil并且阻塞REPL直到所有的future都实例化 (defmacro wait-futures [& args] `(doseq [f# (futures ~@args)] @f#)) ;Bilbo和Gandalf瓜分Smaug的武器 (wait-futures 1 (while (loot smaug bilbo)) (while (loot smaug gandalf))) ;测试瓜分武器的正确性 (map (comp :items deref) [bilbo gandalf]) ;;(#{20 27 1 24 15 48 22 36 29 44 6 28 25 34 17 3 12 2 23 47 35 19 11 5 14 45 26 16 38 30 10 18 42 37 49} #{0 7 39 46 4 21 31 32 40 33 13 41 43 9 8}) (filter (:items @bilbo) (:items @gandalf)) ;;() ;alter函数 ;参数:要被修改的ref、一个函数f以及这个函数所需要的其他参数。当alter函数返回的时候,ref在这个“事务内的值”会被改变成函数f的返回结果 ;所有对于ref的状态进行修改的函数是在一个独立的时间线上执行的,这个时间线开始的时间是这个ref第一次被修改的时候。 ;接下来对于ref的所有修改、访问都是在这个独立的时间线上进行的,而这个时间线只在这个事务内存在,而且只能在这个事务中被访问。 ;当控制流要离开这个事务的时候,STM会尝试提交这个事务,在最乐观的情况下,提交会成功,ref的状态被修改成这个事务内ref的新值 ;而这个新值会对所有的线程/事务可见——不只是在某个事务内可见了。但是如果外部的时间线已经对ref的状态进行了修改,并且已经提交了,那么事务提交就会跟它发生冲突, ;这会导致整个事务重试,利用ref的新值来重新执行一遍。 ;在这个过程中,任何只读线程(比如解引用)不会被阻塞住或者需要等待。而且那些对ref的值进行修改的线程直到成功提交之后,它们对于ref的修改才会对其他线程可见, ;也就不会影响其他线程对于ref的只读操作了。 ;alter的独特语义是,当一个事务要提交的时候,ref的全局值必须跟这个事务内第一次调用alter时候的值一样,否则整个事务会被重启,从头再执行一遍。 ;Clojure的STM可以这样理解:它是一个乐观地尝试对并发的修改操作进行重新排序,以使得它们可以顺序地执行的一个过程。 ;利用commute来最小化事务冲突 ;因为alter没有对修改ref的可重排序性做任何假设,因此它对ref状态进行修改的最安全的方式,不过,在一些情况下,可以安全把对ref的修改的操作进行重排序; ;这样就可以使用commute来代替alter,可以减少潜在冲突几率以及事务重试次数,从而最大化总体的吞吐量。 ;commute应该只用在可以对修改ref状态的操作进行重排的场景中。 ;commute跟alter有两个方面的不同。首先alter的返回值是要更新到这个ref的全局状态的值,这个事务内的值回收最终提交的值。 ;而另一方面,由commute产生的事务内的值不一定会是最终提交的那个值,因为所有被commute的函数在最终提交的时候会利用ref的最小全局值重新计算一遍。 ;利用commute对ref进行的修改从来不会导致冲突,因此也从来不会导致一个事务重试。这个显然潜在地提高了性能以及吞吐量 (def x (ref 0)) (time (wait-futures 5 (dotimes [_ 1000] (dosync (alter x + (apply + (range 1000))))) (dotimes [_ 1000] (dosync (alter x - (apply + (range 1000))))))) ;;"Elapsed time: 3289.451101 msecs" (time (wait-futures 5 (dotimes [_ 1000] (dosync (commute x + (apply + (range 1000))))) (dotimes [_ 1000] (dosync (commute x - (apply + (range 1000))))))) ;;"Elapsed time: 850.658269 msecs" ;;使用commute有问题的函数 (defn flawed-loot [from to] (dosync (when-let [item (first (:items @from))] (commute to update-in [:items] conj item) (commute from update-in [:items] disj item)))) (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100)) (def gandalf (character "Gandalf" :health 75 :mana 750)) ;Bilbo和Gandalf瓜分Smaug的武器 (wait-futures 1 (while (flawed-loot smaug bilbo)) (while (flawed-loot smaug gandalf))) ;测试瓜分武器的正确性 (map (comp count :items deref) [bilbo gandalf]) ;;(43 49) (filter (:items @bilbo) (:items @gandalf)) ;;(0 7 20 27 1 24 39 4 15 48 21 31 32 40 33 13 36 43 29 6 28 34 17 12 2 23 47 19 11 9 5 14 45 26 16 38 30 10 18 42 8 49) ;修改 (defn fixed-loot [from to] (dosync (when-let [item (first (:items @from))] (commute to update-in [:items] conj item) (alter from update-in [:items] disj item)))) (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100)) (def gandalf (character "Gandalf" :health 75 :mana 750)) ;Bilbo和Gandalf瓜分Smaug的武器 (wait-futures 1 (while (fixed-loot smaug bilbo)) (while (fixed-loot smaug gandalf))) ;测试瓜分武器的正确性 (map (comp count :items deref) [bilbo gandalf]) ;;(46 4) (filter (:items @bilbo) (:items @gandalf)) ;;() ;;攻击函数 (defn attack [aggressor target] (dosync (let [damage (* (rand 0.1) (:strength @aggressor))] (commute target update-in [:health] #(max 0 (- % damage)))))) ;;加血函数 (defn heal [healer target] (dosync (let [aid (* (rand 0.1) (:mana @healer))] (when (pos? aid) (commute healer update-in [:mana] - (max 5 (/ aid 5))) (commute target update-in [:health] + aid))))) ;;游戏玩家模拟函数 (def alive? (comp pos? :health)) (defn play [character action other] (while (and (alive? @character) (alive? @other) (action character other)) (Thread/sleep (rand-int 50)))) ;bilbo VS smaug (wait-futures 1 (play bilbo attack smaug) (play smaug attack bilbo)) (map (comp :health deref) [smaug bilbo]) ;;(486.0400189366669 0) ;三个人之间的战斗 (dosync (alter smaug assoc :health 500) (alter bilbo assoc :health 100)) (wait-futures 1 (play bilbo attack smaug) (play smaug attack bilbo) (play gandalf heal bilbo)) (map (comp #(select-keys % [:name :health :mana]) deref) [smaug bilbo gandalf]) ;;({:health 0, :name "Smaug"} {:health 294.0770800776351, :name "Bilbo"} {:mana -1.871433951409358, :health 75, :name "Gandalf"}) ;ref-set来设置ref的状态 ;ref-set会把ref的事务内的状态设置到一个给定的值 (dosync [ref-set bilbo {:name "Bilbo"}]) ;如果在当前事务提交之前,ref的状态在当前事务之外被改变了的话,这个事务会被重试。 ;ref-set通常用来重新初始化ref的状态到初始值 ;校验器 ;(defn enforce-max-health ; [{:keys [name health]}] ; (fn [character-data] ; (or (<= (:health character-data) health) ; (throw (IllegalStateException. (str name " is already at max health!")))))) ;(defn character ; [name & {:as opts}] ; (let [cdata (merge {:name name :items #{} :health 500} ; opts) ; cdata (assoc cdata :max-health (:health cdata)) ; validators (list* (enforce-max-health name (:health cdata)) ; (:validators cdata))] ; (ref (dissoc cdata :validators) ; :validator #(every? (fn [v] (v %)) validators)))) ;只加到最大血量 (defn heal [healer target] (dosync (let [aid (min (* (rand 0.1) (:mana @healer)) (- (:max-health @target) (:health @target)))] (when (pos? aid) (commute healer update-in [:mana] - (max 5 (/ aid 5))) (commute target update-in [:health] + aid))))) (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100 :max-health 130)) (def gandalf (character "Gandalf" :health 75 :mana 750)) (dosync (alter bilbo assoc-in [:health] 95)) ;;{:strength 100, :max-health 130, :name "Bilbo", :items #{}, :health 95} (heal gandalf bilbo) ;;{:strength 100, :max-health 130, :name "Bilbo", :items #{}, :health 130} (heal gandalf bilbo) ;;nil ;STM的缺点 ;事务内绝对不能执行有副作用的函数 ;io!宏:当它被放在一个事务中执行,它会抛出一个错误 ;因此如果你有一个函数可能会被误用在一个事务里面,那么可以把其中有副作用的部分用io!包起来。 (defn unsafe [] (io! (println "writing to database..."))) (dosync (unsafe)) ;;IllegalStateException I/O in transaction ;被ref持有的值一定要是不可变的。Clojure不会阻止你放一个可变对象到ref里面去,但是重试将会导致可变对象最终处于你意料不到的状态 (def x (ref (java.util.ArrayList.))) (wait-futures 2 (dosync (dotimes [v 5] (Thread/sleep (rand-int 50)) (alter x #(doto % (.add v)))))) @x ;;[0 1 0 2 3 4 0 1 2 3 4] ;barging ;在某些情况下,当一个老事务跟一个新事务进行竞争的时候,系统会强迫较新的事务进行重试。而如果barging了一定次数之后这个老事务还是不能成功提交,那么系统会让这个事务失败 (def x (ref 0)) (dosync @(future (dosync (ref-set x 0))) (ref-set x 1)) ;;RuntimeException Transaction failed after reaching retry limit @x ;;0 ;读线程也可能重试 ;STM维护事务中涉及的ref的一定长度的历史版本值,这个历史版本的长度在每次事务重试的时候递增。 ;这使得在某个时间点,我们的事务终于不用再重试了,因为虽然ref还在被其他事务并行地更新,但是我们需要的值还是在历史记录中 ;历史版本的长度可以利用ref-history-cout、ref-max-history以及ref-min-history来查询(以及调整) ;我们创建ref的时候也可以通过指定:min-history和:max-history关键字参数来设置ref历史的最小长度和最大长度 (ref-max-history (ref "abc" :min-history 3 :max-history 30)) ;;30 ;deref的重试通常出现在那些只读事务中,在这些事务中,我们想获取对一些被活跃修改的ref的快照。可以通过一个单个ref以及一个很慢的只读事务来展示这种情况 (def a (ref 0)) (future (dotimes [_ 500] (dosync (Thread/sleep 200) (alter a inc)))) @(future (dosync (Thread/sleep 1000) @a)) ;;57 (ref-history-count a) ;;5 ;a通过一些历史记录使得读取事务可以读到它想要读的值。 ;加快写事务 (def a (ref 0)) (future (dotimes [_ 500] (dosync (Thread/sleep 20) (alter a inc)))) @(future (dosync (Thread/sleep 1000) @a)) ;;500 (ref-history-count a) ;;8 (def a (ref 0 :min-history 50 :max-history 100)) (future (dotimes [_ 500] (dosync (Thread/sleep 20) (alter a inc)))) @(future (dosync (Thread/sleep 1000) @a)) ;;43 (ref-history-count a) ;;50 ;write skew ;如果事务要读取的ref值在事务进行到一半的时候在别的事务中被修改了,而事务依赖的还是那个旧的值,那么当事务提交的时候,整个状态就不一致了,这种情况称为write skew ;使用ensure可以保证读取的值是最新的值
98894
(ns clojure-tutorial.concurrent.ref) ;ref是Clojure提供的协调引用类型。使用它可以保证多个线程可以交互地对这个ref进行操作 ; ref会一直保持在一个一致的状态,任何条件下都不会出现外界可见的一致性的状态 ; 在多个ref之间不可能会产生竞争条件 ; 不需要你手动地去使用锁、monitor或者其他底层的同步原语 ; 不可能出现死锁 ; 软件事务内存STM是任何对并发修改一系列内存地址的行为进行协调的方法。 ; 对于一系列ref的每个修改都是具有事务语义的,而每个STM事务保证对于ref的修改是: 原子的、一致的、隔离的 ; Clojure的STM满足ACID属性里面的A、C、I,而D(持久性)则不是STM所关心的,因为STM是纯内存的实现 ;创建游戏角色的函数 (defn character [name & {:as opts}] (ref (merge {:name name :items #{} :health 500} opts))) ;定义一些具体的角色 (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100)) (def gandalf (character "Gandalf" :health 75 :mana 750)) ;dosync规定了一个事务的边界,所有对于ref的修改毕夏要发生在一个事务里面,对于这些修改的处理是以同步的方式进行的。 ;也就是说,启动一个事务的线程在这个事务完成之前是不能继续执行其他代码的 ;两个对共享ref进行修改的事务冲突与否,是由对ref进行修改所使用的函数来决定的。 ; 有三个函数:alter、commute以及ref-set——它们每一个都有不同的、是否产生(或者避免)冲突的语义 ;把一个角色的武器转移到另外一个角色那里的函数 (defn loot [from to] (dosync (when-let [items (first (:items @from))] (alter to update-in [:items] conj items) (alter from update-in [:items] disj items)))) ;接受表达式作为参数,返回n个future (defmacro futures [n & exprs] (vec (for [_ (range n) expr exprs] `(future ~expr)))) ;wait-futures,始终返回nil并且阻塞REPL直到所有的future都实例化 (defmacro wait-futures [& args] `(doseq [f# (futures ~@args)] @f#)) ;Bilbo和Gandalf瓜分Smaug的武器 (wait-futures 1 (while (loot smaug bilbo)) (while (loot smaug gandalf))) ;测试瓜分武器的正确性 (map (comp :items deref) [bilbo gandalf]) ;;(#{20 27 1 24 15 48 22 36 29 44 6 28 25 34 17 3 12 2 23 47 35 19 11 5 14 45 26 16 38 30 10 18 42 37 49} #{0 7 39 46 4 21 31 32 40 33 13 41 43 9 8}) (filter (:items @bilbo) (:items @gandalf)) ;;() ;alter函数 ;参数:要被修改的ref、一个函数f以及这个函数所需要的其他参数。当alter函数返回的时候,ref在这个“事务内的值”会被改变成函数f的返回结果 ;所有对于ref的状态进行修改的函数是在一个独立的时间线上执行的,这个时间线开始的时间是这个ref第一次被修改的时候。 ;接下来对于ref的所有修改、访问都是在这个独立的时间线上进行的,而这个时间线只在这个事务内存在,而且只能在这个事务中被访问。 ;当控制流要离开这个事务的时候,STM会尝试提交这个事务,在最乐观的情况下,提交会成功,ref的状态被修改成这个事务内ref的新值 ;而这个新值会对所有的线程/事务可见——不只是在某个事务内可见了。但是如果外部的时间线已经对ref的状态进行了修改,并且已经提交了,那么事务提交就会跟它发生冲突, ;这会导致整个事务重试,利用ref的新值来重新执行一遍。 ;在这个过程中,任何只读线程(比如解引用)不会被阻塞住或者需要等待。而且那些对ref的值进行修改的线程直到成功提交之后,它们对于ref的修改才会对其他线程可见, ;也就不会影响其他线程对于ref的只读操作了。 ;alter的独特语义是,当一个事务要提交的时候,ref的全局值必须跟这个事务内第一次调用alter时候的值一样,否则整个事务会被重启,从头再执行一遍。 ;Clojure的STM可以这样理解:它是一个乐观地尝试对并发的修改操作进行重新排序,以使得它们可以顺序地执行的一个过程。 ;利用commute来最小化事务冲突 ;因为alter没有对修改ref的可重排序性做任何假设,因此它对ref状态进行修改的最安全的方式,不过,在一些情况下,可以安全把对ref的修改的操作进行重排序; ;这样就可以使用commute来代替alter,可以减少潜在冲突几率以及事务重试次数,从而最大化总体的吞吐量。 ;commute应该只用在可以对修改ref状态的操作进行重排的场景中。 ;commute跟alter有两个方面的不同。首先alter的返回值是要更新到这个ref的全局状态的值,这个事务内的值回收最终提交的值。 ;而另一方面,由commute产生的事务内的值不一定会是最终提交的那个值,因为所有被commute的函数在最终提交的时候会利用ref的最小全局值重新计算一遍。 ;利用commute对ref进行的修改从来不会导致冲突,因此也从来不会导致一个事务重试。这个显然潜在地提高了性能以及吞吐量 (def x (ref 0)) (time (wait-futures 5 (dotimes [_ 1000] (dosync (alter x + (apply + (range 1000))))) (dotimes [_ 1000] (dosync (alter x - (apply + (range 1000))))))) ;;"Elapsed time: 3289.451101 msecs" (time (wait-futures 5 (dotimes [_ 1000] (dosync (commute x + (apply + (range 1000))))) (dotimes [_ 1000] (dosync (commute x - (apply + (range 1000))))))) ;;"Elapsed time: 850.658269 msecs" ;;使用commute有问题的函数 (defn flawed-loot [from to] (dosync (when-let [item (first (:items @from))] (commute to update-in [:items] conj item) (commute from update-in [:items] disj item)))) (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100)) (def gandalf (character "Gandalf" :health 75 :mana 750)) ;Bilbo和Gandalf瓜分Smaug的武器 (wait-futures 1 (while (flawed-loot smaug bilbo)) (while (flawed-loot smaug gandalf))) ;测试瓜分武器的正确性 (map (comp count :items deref) [bilbo gandalf]) ;;(43 49) (filter (:items @bilbo) (:items @gandalf)) ;;(0 7 20 27 1 24 39 4 15 48 21 31 32 40 33 13 36 43 29 6 28 34 17 12 2 23 47 19 11 9 5 14 45 26 16 38 30 10 18 42 8 49) ;修改 (defn fixed-loot [from to] (dosync (when-let [item (first (:items @from))] (commute to update-in [:items] conj item) (alter from update-in [:items] disj item)))) (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100)) (def gandalf (character "Gandalf" :health 75 :mana 750)) ;Bilbo和Gandalf瓜分Smaug的武器 (wait-futures 1 (while (fixed-loot smaug bilbo)) (while (fixed-loot smaug gandalf))) ;测试瓜分武器的正确性 (map (comp count :items deref) [bilbo gandalf]) ;;(46 4) (filter (:items @bilbo) (:items @gandalf)) ;;() ;;攻击函数 (defn attack [aggressor target] (dosync (let [damage (* (rand 0.1) (:strength @aggressor))] (commute target update-in [:health] #(max 0 (- % damage)))))) ;;加血函数 (defn heal [healer target] (dosync (let [aid (* (rand 0.1) (:mana @healer))] (when (pos? aid) (commute healer update-in [:mana] - (max 5 (/ aid 5))) (commute target update-in [:health] + aid))))) ;;游戏玩家模拟函数 (def alive? (comp pos? :health)) (defn play [character action other] (while (and (alive? @character) (alive? @other) (action character other)) (Thread/sleep (rand-int 50)))) ;bilbo VS smaug (wait-futures 1 (play bilbo attack smaug) (play smaug attack bilbo)) (map (comp :health deref) [smaug bilbo]) ;;(486.0400189366669 0) ;三个人之间的战斗 (dosync (alter smaug assoc :health 500) (alter bilbo assoc :health 100)) (wait-futures 1 (play bilbo attack smaug) (play smaug attack bilbo) (play gandalf heal bilbo)) (map (comp #(select-keys % [:name :health :mana]) deref) [smaug bilbo gandalf]) ;;({:health 0, :name "<NAME>"} {:health 294.0770800776351, :name "<NAME>"} {:mana -1.871433951409358, :health 75, :name "<NAME>"}) ;ref-set来设置ref的状态 ;ref-set会把ref的事务内的状态设置到一个给定的值 (dosync [ref-set bilbo {:name "<NAME>"}]) ;如果在当前事务提交之前,ref的状态在当前事务之外被改变了的话,这个事务会被重试。 ;ref-set通常用来重新初始化ref的状态到初始值 ;校验器 ;(defn enforce-max-health ; [{:keys [name health]}] ; (fn [character-data] ; (or (<= (:health character-data) health) ; (throw (IllegalStateException. (str name " is already at max health!")))))) ;(defn character ; [name & {:as opts}] ; (let [cdata (merge {:name name :items #{} :health 500} ; opts) ; cdata (assoc cdata :max-health (:health cdata)) ; validators (list* (enforce-max-health name (:health cdata)) ; (:validators cdata))] ; (ref (dissoc cdata :validators) ; :validator #(every? (fn [v] (v %)) validators)))) ;只加到最大血量 (defn heal [healer target] (dosync (let [aid (min (* (rand 0.1) (:mana @healer)) (- (:max-health @target) (:health @target)))] (when (pos? aid) (commute healer update-in [:mana] - (max 5 (/ aid 5))) (commute target update-in [:health] + aid))))) (def smaug (character "S<NAME>" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "B<NAME>bo" :health 100 :strength 100 :max-health 130)) (def gandalf (character "Gandalf" :health 75 :mana 750)) (dosync (alter bilbo assoc-in [:health] 95)) ;;{:strength 100, :max-health 130, :name "<NAME>", :items #{}, :health 95} (heal gandalf bilbo) ;;{:strength 100, :max-health 130, :name "B<NAME>", :items #{}, :health 130} (heal gandalf bilbo) ;;nil ;STM的缺点 ;事务内绝对不能执行有副作用的函数 ;io!宏:当它被放在一个事务中执行,它会抛出一个错误 ;因此如果你有一个函数可能会被误用在一个事务里面,那么可以把其中有副作用的部分用io!包起来。 (defn unsafe [] (io! (println "writing to database..."))) (dosync (unsafe)) ;;IllegalStateException I/O in transaction ;被ref持有的值一定要是不可变的。Clojure不会阻止你放一个可变对象到ref里面去,但是重试将会导致可变对象最终处于你意料不到的状态 (def x (ref (java.util.ArrayList.))) (wait-futures 2 (dosync (dotimes [v 5] (Thread/sleep (rand-int 50)) (alter x #(doto % (.add v)))))) @x ;;[0 1 0 2 3 4 0 1 2 3 4] ;barging ;在某些情况下,当一个老事务跟一个新事务进行竞争的时候,系统会强迫较新的事务进行重试。而如果barging了一定次数之后这个老事务还是不能成功提交,那么系统会让这个事务失败 (def x (ref 0)) (dosync @(future (dosync (ref-set x 0))) (ref-set x 1)) ;;RuntimeException Transaction failed after reaching retry limit @x ;;0 ;读线程也可能重试 ;STM维护事务中涉及的ref的一定长度的历史版本值,这个历史版本的长度在每次事务重试的时候递增。 ;这使得在某个时间点,我们的事务终于不用再重试了,因为虽然ref还在被其他事务并行地更新,但是我们需要的值还是在历史记录中 ;历史版本的长度可以利用ref-history-cout、ref-max-history以及ref-min-history来查询(以及调整) ;我们创建ref的时候也可以通过指定:min-history和:max-history关键字参数来设置ref历史的最小长度和最大长度 (ref-max-history (ref "abc" :min-history 3 :max-history 30)) ;;30 ;deref的重试通常出现在那些只读事务中,在这些事务中,我们想获取对一些被活跃修改的ref的快照。可以通过一个单个ref以及一个很慢的只读事务来展示这种情况 (def a (ref 0)) (future (dotimes [_ 500] (dosync (Thread/sleep 200) (alter a inc)))) @(future (dosync (Thread/sleep 1000) @a)) ;;57 (ref-history-count a) ;;5 ;a通过一些历史记录使得读取事务可以读到它想要读的值。 ;加快写事务 (def a (ref 0)) (future (dotimes [_ 500] (dosync (Thread/sleep 20) (alter a inc)))) @(future (dosync (Thread/sleep 1000) @a)) ;;500 (ref-history-count a) ;;8 (def a (ref 0 :min-history 50 :max-history 100)) (future (dotimes [_ 500] (dosync (Thread/sleep 20) (alter a inc)))) @(future (dosync (Thread/sleep 1000) @a)) ;;43 (ref-history-count a) ;;50 ;write skew ;如果事务要读取的ref值在事务进行到一半的时候在别的事务中被修改了,而事务依赖的还是那个旧的值,那么当事务提交的时候,整个状态就不一致了,这种情况称为write skew ;使用ensure可以保证读取的值是最新的值
true
(ns clojure-tutorial.concurrent.ref) ;ref是Clojure提供的协调引用类型。使用它可以保证多个线程可以交互地对这个ref进行操作 ; ref会一直保持在一个一致的状态,任何条件下都不会出现外界可见的一致性的状态 ; 在多个ref之间不可能会产生竞争条件 ; 不需要你手动地去使用锁、monitor或者其他底层的同步原语 ; 不可能出现死锁 ; 软件事务内存STM是任何对并发修改一系列内存地址的行为进行协调的方法。 ; 对于一系列ref的每个修改都是具有事务语义的,而每个STM事务保证对于ref的修改是: 原子的、一致的、隔离的 ; Clojure的STM满足ACID属性里面的A、C、I,而D(持久性)则不是STM所关心的,因为STM是纯内存的实现 ;创建游戏角色的函数 (defn character [name & {:as opts}] (ref (merge {:name name :items #{} :health 500} opts))) ;定义一些具体的角色 (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100)) (def gandalf (character "Gandalf" :health 75 :mana 750)) ;dosync规定了一个事务的边界,所有对于ref的修改毕夏要发生在一个事务里面,对于这些修改的处理是以同步的方式进行的。 ;也就是说,启动一个事务的线程在这个事务完成之前是不能继续执行其他代码的 ;两个对共享ref进行修改的事务冲突与否,是由对ref进行修改所使用的函数来决定的。 ; 有三个函数:alter、commute以及ref-set——它们每一个都有不同的、是否产生(或者避免)冲突的语义 ;把一个角色的武器转移到另外一个角色那里的函数 (defn loot [from to] (dosync (when-let [items (first (:items @from))] (alter to update-in [:items] conj items) (alter from update-in [:items] disj items)))) ;接受表达式作为参数,返回n个future (defmacro futures [n & exprs] (vec (for [_ (range n) expr exprs] `(future ~expr)))) ;wait-futures,始终返回nil并且阻塞REPL直到所有的future都实例化 (defmacro wait-futures [& args] `(doseq [f# (futures ~@args)] @f#)) ;Bilbo和Gandalf瓜分Smaug的武器 (wait-futures 1 (while (loot smaug bilbo)) (while (loot smaug gandalf))) ;测试瓜分武器的正确性 (map (comp :items deref) [bilbo gandalf]) ;;(#{20 27 1 24 15 48 22 36 29 44 6 28 25 34 17 3 12 2 23 47 35 19 11 5 14 45 26 16 38 30 10 18 42 37 49} #{0 7 39 46 4 21 31 32 40 33 13 41 43 9 8}) (filter (:items @bilbo) (:items @gandalf)) ;;() ;alter函数 ;参数:要被修改的ref、一个函数f以及这个函数所需要的其他参数。当alter函数返回的时候,ref在这个“事务内的值”会被改变成函数f的返回结果 ;所有对于ref的状态进行修改的函数是在一个独立的时间线上执行的,这个时间线开始的时间是这个ref第一次被修改的时候。 ;接下来对于ref的所有修改、访问都是在这个独立的时间线上进行的,而这个时间线只在这个事务内存在,而且只能在这个事务中被访问。 ;当控制流要离开这个事务的时候,STM会尝试提交这个事务,在最乐观的情况下,提交会成功,ref的状态被修改成这个事务内ref的新值 ;而这个新值会对所有的线程/事务可见——不只是在某个事务内可见了。但是如果外部的时间线已经对ref的状态进行了修改,并且已经提交了,那么事务提交就会跟它发生冲突, ;这会导致整个事务重试,利用ref的新值来重新执行一遍。 ;在这个过程中,任何只读线程(比如解引用)不会被阻塞住或者需要等待。而且那些对ref的值进行修改的线程直到成功提交之后,它们对于ref的修改才会对其他线程可见, ;也就不会影响其他线程对于ref的只读操作了。 ;alter的独特语义是,当一个事务要提交的时候,ref的全局值必须跟这个事务内第一次调用alter时候的值一样,否则整个事务会被重启,从头再执行一遍。 ;Clojure的STM可以这样理解:它是一个乐观地尝试对并发的修改操作进行重新排序,以使得它们可以顺序地执行的一个过程。 ;利用commute来最小化事务冲突 ;因为alter没有对修改ref的可重排序性做任何假设,因此它对ref状态进行修改的最安全的方式,不过,在一些情况下,可以安全把对ref的修改的操作进行重排序; ;这样就可以使用commute来代替alter,可以减少潜在冲突几率以及事务重试次数,从而最大化总体的吞吐量。 ;commute应该只用在可以对修改ref状态的操作进行重排的场景中。 ;commute跟alter有两个方面的不同。首先alter的返回值是要更新到这个ref的全局状态的值,这个事务内的值回收最终提交的值。 ;而另一方面,由commute产生的事务内的值不一定会是最终提交的那个值,因为所有被commute的函数在最终提交的时候会利用ref的最小全局值重新计算一遍。 ;利用commute对ref进行的修改从来不会导致冲突,因此也从来不会导致一个事务重试。这个显然潜在地提高了性能以及吞吐量 (def x (ref 0)) (time (wait-futures 5 (dotimes [_ 1000] (dosync (alter x + (apply + (range 1000))))) (dotimes [_ 1000] (dosync (alter x - (apply + (range 1000))))))) ;;"Elapsed time: 3289.451101 msecs" (time (wait-futures 5 (dotimes [_ 1000] (dosync (commute x + (apply + (range 1000))))) (dotimes [_ 1000] (dosync (commute x - (apply + (range 1000))))))) ;;"Elapsed time: 850.658269 msecs" ;;使用commute有问题的函数 (defn flawed-loot [from to] (dosync (when-let [item (first (:items @from))] (commute to update-in [:items] conj item) (commute from update-in [:items] disj item)))) (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100)) (def gandalf (character "Gandalf" :health 75 :mana 750)) ;Bilbo和Gandalf瓜分Smaug的武器 (wait-futures 1 (while (flawed-loot smaug bilbo)) (while (flawed-loot smaug gandalf))) ;测试瓜分武器的正确性 (map (comp count :items deref) [bilbo gandalf]) ;;(43 49) (filter (:items @bilbo) (:items @gandalf)) ;;(0 7 20 27 1 24 39 4 15 48 21 31 32 40 33 13 36 43 29 6 28 34 17 12 2 23 47 19 11 9 5 14 45 26 16 38 30 10 18 42 8 49) ;修改 (defn fixed-loot [from to] (dosync (when-let [item (first (:items @from))] (commute to update-in [:items] conj item) (alter from update-in [:items] disj item)))) (def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "Bilbo" :health 100 :strength 100)) (def gandalf (character "Gandalf" :health 75 :mana 750)) ;Bilbo和Gandalf瓜分Smaug的武器 (wait-futures 1 (while (fixed-loot smaug bilbo)) (while (fixed-loot smaug gandalf))) ;测试瓜分武器的正确性 (map (comp count :items deref) [bilbo gandalf]) ;;(46 4) (filter (:items @bilbo) (:items @gandalf)) ;;() ;;攻击函数 (defn attack [aggressor target] (dosync (let [damage (* (rand 0.1) (:strength @aggressor))] (commute target update-in [:health] #(max 0 (- % damage)))))) ;;加血函数 (defn heal [healer target] (dosync (let [aid (* (rand 0.1) (:mana @healer))] (when (pos? aid) (commute healer update-in [:mana] - (max 5 (/ aid 5))) (commute target update-in [:health] + aid))))) ;;游戏玩家模拟函数 (def alive? (comp pos? :health)) (defn play [character action other] (while (and (alive? @character) (alive? @other) (action character other)) (Thread/sleep (rand-int 50)))) ;bilbo VS smaug (wait-futures 1 (play bilbo attack smaug) (play smaug attack bilbo)) (map (comp :health deref) [smaug bilbo]) ;;(486.0400189366669 0) ;三个人之间的战斗 (dosync (alter smaug assoc :health 500) (alter bilbo assoc :health 100)) (wait-futures 1 (play bilbo attack smaug) (play smaug attack bilbo) (play gandalf heal bilbo)) (map (comp #(select-keys % [:name :health :mana]) deref) [smaug bilbo gandalf]) ;;({:health 0, :name "PI:NAME:<NAME>END_PI"} {:health 294.0770800776351, :name "PI:NAME:<NAME>END_PI"} {:mana -1.871433951409358, :health 75, :name "PI:NAME:<NAME>END_PI"}) ;ref-set来设置ref的状态 ;ref-set会把ref的事务内的状态设置到一个给定的值 (dosync [ref-set bilbo {:name "PI:NAME:<NAME>END_PI"}]) ;如果在当前事务提交之前,ref的状态在当前事务之外被改变了的话,这个事务会被重试。 ;ref-set通常用来重新初始化ref的状态到初始值 ;校验器 ;(defn enforce-max-health ; [{:keys [name health]}] ; (fn [character-data] ; (or (<= (:health character-data) health) ; (throw (IllegalStateException. (str name " is already at max health!")))))) ;(defn character ; [name & {:as opts}] ; (let [cdata (merge {:name name :items #{} :health 500} ; opts) ; cdata (assoc cdata :max-health (:health cdata)) ; validators (list* (enforce-max-health name (:health cdata)) ; (:validators cdata))] ; (ref (dissoc cdata :validators) ; :validator #(every? (fn [v] (v %)) validators)))) ;只加到最大血量 (defn heal [healer target] (dosync (let [aid (min (* (rand 0.1) (:mana @healer)) (- (:max-health @target) (:health @target)))] (when (pos? aid) (commute healer update-in [:mana] - (max 5 (/ aid 5))) (commute target update-in [:health] + aid))))) (def smaug (character "SPI:NAME:<NAME>END_PI" :health 500 :strength 400 :items (set (range 50)))) (def bilbo (character "BPI:NAME:<NAME>END_PIbo" :health 100 :strength 100 :max-health 130)) (def gandalf (character "Gandalf" :health 75 :mana 750)) (dosync (alter bilbo assoc-in [:health] 95)) ;;{:strength 100, :max-health 130, :name "PI:NAME:<NAME>END_PI", :items #{}, :health 95} (heal gandalf bilbo) ;;{:strength 100, :max-health 130, :name "BPI:NAME:<NAME>END_PI", :items #{}, :health 130} (heal gandalf bilbo) ;;nil ;STM的缺点 ;事务内绝对不能执行有副作用的函数 ;io!宏:当它被放在一个事务中执行,它会抛出一个错误 ;因此如果你有一个函数可能会被误用在一个事务里面,那么可以把其中有副作用的部分用io!包起来。 (defn unsafe [] (io! (println "writing to database..."))) (dosync (unsafe)) ;;IllegalStateException I/O in transaction ;被ref持有的值一定要是不可变的。Clojure不会阻止你放一个可变对象到ref里面去,但是重试将会导致可变对象最终处于你意料不到的状态 (def x (ref (java.util.ArrayList.))) (wait-futures 2 (dosync (dotimes [v 5] (Thread/sleep (rand-int 50)) (alter x #(doto % (.add v)))))) @x ;;[0 1 0 2 3 4 0 1 2 3 4] ;barging ;在某些情况下,当一个老事务跟一个新事务进行竞争的时候,系统会强迫较新的事务进行重试。而如果barging了一定次数之后这个老事务还是不能成功提交,那么系统会让这个事务失败 (def x (ref 0)) (dosync @(future (dosync (ref-set x 0))) (ref-set x 1)) ;;RuntimeException Transaction failed after reaching retry limit @x ;;0 ;读线程也可能重试 ;STM维护事务中涉及的ref的一定长度的历史版本值,这个历史版本的长度在每次事务重试的时候递增。 ;这使得在某个时间点,我们的事务终于不用再重试了,因为虽然ref还在被其他事务并行地更新,但是我们需要的值还是在历史记录中 ;历史版本的长度可以利用ref-history-cout、ref-max-history以及ref-min-history来查询(以及调整) ;我们创建ref的时候也可以通过指定:min-history和:max-history关键字参数来设置ref历史的最小长度和最大长度 (ref-max-history (ref "abc" :min-history 3 :max-history 30)) ;;30 ;deref的重试通常出现在那些只读事务中,在这些事务中,我们想获取对一些被活跃修改的ref的快照。可以通过一个单个ref以及一个很慢的只读事务来展示这种情况 (def a (ref 0)) (future (dotimes [_ 500] (dosync (Thread/sleep 200) (alter a inc)))) @(future (dosync (Thread/sleep 1000) @a)) ;;57 (ref-history-count a) ;;5 ;a通过一些历史记录使得读取事务可以读到它想要读的值。 ;加快写事务 (def a (ref 0)) (future (dotimes [_ 500] (dosync (Thread/sleep 20) (alter a inc)))) @(future (dosync (Thread/sleep 1000) @a)) ;;500 (ref-history-count a) ;;8 (def a (ref 0 :min-history 50 :max-history 100)) (future (dotimes [_ 500] (dosync (Thread/sleep 20) (alter a inc)))) @(future (dosync (Thread/sleep 1000) @a)) ;;43 (ref-history-count a) ;;50 ;write skew ;如果事务要读取的ref值在事务进行到一半的时候在别的事务中被修改了,而事务依赖的还是那个旧的值,那么当事务提交的时候,整个状态就不一致了,这种情况称为write skew ;使用ensure可以保证读取的值是最新的值
[ { "context": " \n {:doc \"collect software tags.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2018-11-30\"}\n \n (:require [clojur", "end": 262, "score": 0.622672438621521, "start": 229, "tag": "EMAIL", "value": "isades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/curate/scripts/wxh.clj
palisades-lakes/curate
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.scripts.wxh {:doc "collect software tags." :author "palisades dot lakes at gmail dot com" :version "2018-11-30"} (:require [clojure.java.io :as io] [clojure.pprint :as pp] [palisades.lakes.curate.curate :as curate])) ;; clj src\scripts\clojure\palisades\lakes\curate\scripts\wxh.clj > wxh.txt ;;---------------------------------------------------------------- (let [d (io/file "e:/" "pic")] (pp/pprint (sort (into #{} (map curate/exif-wxh (curate/image-file-seq d)))))) ;;----------------------------------------------------------------
109648
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.scripts.wxh {:doc "collect software tags." :author "pal<EMAIL>" :version "2018-11-30"} (:require [clojure.java.io :as io] [clojure.pprint :as pp] [palisades.lakes.curate.curate :as curate])) ;; clj src\scripts\clojure\palisades\lakes\curate\scripts\wxh.clj > wxh.txt ;;---------------------------------------------------------------- (let [d (io/file "e:/" "pic")] (pp/pprint (sort (into #{} (map curate/exif-wxh (curate/image-file-seq d)))))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.scripts.wxh {:doc "collect software tags." :author "palPI:EMAIL:<EMAIL>END_PI" :version "2018-11-30"} (:require [clojure.java.io :as io] [clojure.pprint :as pp] [palisades.lakes.curate.curate :as curate])) ;; clj src\scripts\clojure\palisades\lakes\curate\scripts\wxh.clj > wxh.txt ;;---------------------------------------------------------------- (let [d (io/file "e:/" "pic")] (pp/pprint (sort (into #{} (map curate/exif-wxh (curate/image-file-seq d)))))) ;;----------------------------------------------------------------
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\r\n; The use and distributi", "end": 30, "score": 0.999749481678009, "start": 19, "tag": "NAME", "value": "Rich Hickey" } ]
Source/clojure/spec/test.clj
pjago/Arcadia
0
; 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 clojure.spec.test (:refer-clojure :exclude [test]) (:require [clojure.pprint :as pp] [clojure.spec :as s] [clojure.spec.gen :as gen] [clojure.string :as str])) (in-ns 'clojure.spec.test.check) (in-ns 'clojure.spec.test) (alias 'stc 'clojure.spec.test.check) (defn- throwable? [x] (instance? Exception x)) ;;; Throwable (defn ->sym [x] (@#'s/->sym x)) (defn- ->var [s-or-v] (if (var? s-or-v) s-or-v (let [v (and (symbol? s-or-v) (resolve s-or-v))] (if (var? v) v (throw (ArgumentException. (str (pr-str s-or-v) " does not name a var"))))))) ;;; IllegalArgumentException. (defn- collectionize [x] (if (symbol? x) (list x) x)) (defn enumerate-namespace "Given a symbol naming an ns, or a collection of such symbols, returns the set of all symbols naming vars in those nses." [ns-sym-or-syms] (into #{} (mapcat (fn [ns-sym] (map (fn [name-sym] (symbol (name ns-sym) (name name-sym))) (keys (ns-interns ns-sym))))) (collectionize ns-sym-or-syms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; instrument ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private ^:dynamic *instrument-enabled* "if false, instrumented fns call straight through" true) (defn- fn-spec? "Fn-spec must include at least :args or :ret specs." [m] (or (:args m) (:ret m))) (defmacro with-instrument-disabled "Disables instrument's checking of calls, within a scope." [& body] `(binding [*instrument-enabled* nil] ~@body)) (defn- interpret-stack-trace-element "Given the vector-of-syms form of a stacktrace element produced by e.g. Throwable->map, returns a map form that adds some keys guessing the original Clojure names. Returns a map with :class class name symbol from stack trace :method method symbol from stack trace :file filename from stack trace :line line number from stack trace :var-scope optional Clojure var symbol scoping fn def :local-fn optional local Clojure symbol scoping fn def For non-Clojure fns, :scope and :local-fn will be absent." [[cls method file line]] (let [clojure? (contains? '#{invoke invokeStatic} method) demunge #(clojure.lang.Compiler/demunge %) degensym #(str/replace % #"--.*" "") [ns-sym name-sym local] (when clojure? (->> (str/split (str cls) #"\$" 3) (map demunge)))] (merge {:file file :line line :method method :class cls} (when (and ns-sym name-sym) {:var-scope (symbol ns-sym name-sym)}) (when local {:local-fn (symbol (degensym local))})))) (defn- stacktrace-relevant-to-instrument "Takes a coll of stack trace elements (as returned by StackTraceElement->vec) and returns a coll of maps as per interpret-stack-trace-element that are relevant to a failure in instrument." [elems] (let [plumbing? (fn [{:keys [var-scope]}] (contains? '#{clojure.spec.alpha.test/spec-checking-fn} var-scope))] (sequence (comp (map StackTraceElement->vec) (map interpret-stack-trace-element) (filter :var-scope) (drop-while plumbing?)) elems))) (defn- spec-checking-fn [v f fn-spec] (let [fn-spec (@#'s/maybe-spec fn-spec) conform! (fn [v role spec data args] (let [conformed (s/conform spec data)] (if (= ::s/invalid conformed) (let [caller (->> (System.Diagnostics.StackTrace. true) ;;; (.getStackTrace (Thread/currentThread)) stacktrace-relevant-to-instrument first) ed (merge (assoc (s/explain-data* spec [role] [] [] data) ::s/args args ::s/failure :instrument) (when caller {::caller (dissoc caller :class :method)}))] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (s/explain-out ed))) ed))) conformed)))] (fn [& args] (if *instrument-enabled* (with-instrument-disabled (when (:args fn-spec) (conform! v :args (:args fn-spec) args args)) (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args))) (.applyTo ^clojure.lang.IFn f args))))) (defn- no-fspec [v spec] (ex-info (str "Fn at " v " is not spec'ed.") {:var v :spec spec ::s/failure :no-fspec})) (defonce ^:private instrumented-vars (atom {})) (defn- instrument-choose-fn "Helper for instrument." [f spec sym {over :gen :keys [stub replace]}] (if (some #{sym} stub) (-> spec (s/gen over) gen/generate) (get replace sym f))) (defn- instrument-choose-spec "Helper for instrument" [spec sym {overrides :spec}] (get overrides sym spec)) (defn- instrument-1 [s opts] (when-let [v (resolve s)] (when-not (-> v meta :macro) (let [spec (s/get-spec v) {:keys [raw wrapped]} (get @instrumented-vars v) current @v to-wrap (if (= wrapped current) raw current) ospec (or (instrument-choose-spec spec s opts) (throw (no-fspec v spec))) ofn (instrument-choose-fn to-wrap ospec s opts) checked (spec-checking-fn v ofn ospec)] (alter-var-root v (constantly checked)) (swap! instrumented-vars assoc v {:raw to-wrap :wrapped checked}) (->sym v))))) (defn- unstrument-1 [s] (when-let [v (resolve s)] (when-let [{:keys [raw wrapped]} (get @instrumented-vars v)] (swap! instrumented-vars dissoc v) (let [current @v] (when (= wrapped current) (alter-var-root v (constantly raw)) (->sym v)))))) (defn- opt-syms "Returns set of symbols referenced by 'instrument' opts map" [opts] (reduce into #{} [(:stub opts) (keys (:replace opts)) (keys (:spec opts))])) (defn- fn-spec-name? [s] (and (symbol? s) (not (some-> (resolve s) meta :macro)))) (defn instrumentable-syms "Given an opts map as per instrument, returns the set of syms that can be instrumented." ([] (instrumentable-syms nil)) ([opts] (assert (every? ident? (keys (:gen opts))) "instrument :gen expects ident keys") (reduce into #{} [(filter fn-spec-name? (keys (s/registry))) (keys (:spec opts)) (:stub opts) (keys (:replace opts))]))) (defn instrument "Instruments the vars named by sym-or-syms, a symbol or collection of symbols, or all instrumentable vars if sym-or-syms is not specified. If a var has an :args fn-spec, sets the var's root binding to a fn that checks arg conformance (throwing an exception on failure) before delegating to the original fn. The opts map can be used to override registered specs, and/or to replace fn implementations entirely. Opts for symbols not included in sym-or-syms are ignored. This facilitates sharing a common options map across many different calls to instrument. The opts map may have the following keys: :spec a map from var-name symbols to override specs :stub a set of var-name symbols to be replaced by stubs :gen a map from spec names to generator overrides :replace a map from var-name symbols to replacement fns :spec overrides registered fn-specs with specs your provide. Use :spec overrides to provide specs for libraries that do not have them, or to constrain your own use of a fn to a subset of its spec'ed contract. :stub replaces a fn with a stub that checks :args, then uses the :ret spec to generate a return value. :gen overrides are used only for :stub generation. :replace replaces a fn with a fn that checks args conformance, then invokes the fn you provide, enabling arbitrary stubbing and mocking. :spec can be used in combination with :stub or :replace. Returns a collection of syms naming the vars instrumented." ([] (instrument (instrumentable-syms))) ([sym-or-syms] (instrument sym-or-syms nil)) ([sym-or-syms opts] (locking instrumented-vars (into [] (comp (filter (instrumentable-syms opts)) (distinct) (map #(instrument-1 % opts)) (remove nil?)) (collectionize sym-or-syms))))) (defn unstrument "Undoes instrument on the vars named by sym-or-syms, specified as in instrument. With no args, unstruments all instrumented vars. Returns a collection of syms naming the vars unstrumented." ([] (unstrument (map ->sym (keys @instrumented-vars)))) ([sym-or-syms] (locking instrumented-vars (into [] (comp (filter symbol?) (map unstrument-1) (remove nil?)) (collectionize sym-or-syms))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; testing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- explain-check [args spec v role] (ex-info "Specification-based check failed" (when-not (s/valid? spec v nil) (assoc (s/explain-data* spec [role] [] [] v) ::args args ::val v ::s/failure :check-failed)))) (defn- check-call "Returns true if call passes specs, otherwise *returns* an exception with explain-data + ::s/failure." [f specs args] (let [cargs (when (:args specs) (s/conform (:args specs) args))] (if (= cargs ::s/invalid) (explain-check args (:args specs) args :args) (let [ret (apply f args) cret (when (:ret specs) (s/conform (:ret specs) ret))] (if (= cret ::s/invalid) (explain-check args (:ret specs) ret :ret) (if (and (:args specs) (:ret specs) (:fn specs)) (if (s/valid? (:fn specs) {:args cargs :ret cret}) true (explain-check args (:fn specs) {:args cargs :ret cret} :fn)) true)))))) (defn- quick-check [f specs {gen :gen opts ::stc/opts}] (let [{:keys [num-tests] :or {num-tests 1000}} opts g (try (s/gen (:args specs) gen) (catch Exception t t))] ;;; Throwable (if (throwable? g) {:result g} (let [prop (gen/for-all* [g] #(check-call f specs %))] (apply gen/quick-check num-tests prop (mapcat identity opts)))))) (defn- make-check-result "Builds spec result map." [check-sym spec test-check-ret] (merge {:spec spec ::stc/ret test-check-ret} (when check-sym {:sym check-sym}) (when-let [result (-> test-check-ret :result)] (when-not (true? result) {:failure result})) (when-let [shrunk (-> test-check-ret :shrunk)] {:failure (:result shrunk)}))) (defn- check-1 [{:keys [s f v spec]} opts] (let [re-inst? (and v (seq (unstrument s)) true) f (or f (when v @v)) specd (s/spec spec)] (try (cond (or (nil? f) (some-> v meta :macro)) {:failure (ex-info "No fn to spec" {::s/failure :no-fn}) :sym s :spec spec} (:args specd) (let [tcret (quick-check f specd opts)] (make-check-result s spec tcret)) :default {:failure (ex-info "No :args spec" {::s/failure :no-args-spec}) :sym s :spec spec}) (finally (when re-inst? (instrument s)))))) (defn- sym->check-map [s] (let [v (resolve s)] {:s s :v v :spec (when v (s/get-spec v))})) (defn- validate-check-opts [opts] (assert (every? ident? (keys (:gen opts))) "check :gen expects ident keys")) (defn check-fn "Runs generative tests for fn f using spec and opts. See 'check' for options and return." ([f spec] (check-fn f spec nil)) ([f spec opts] (validate-check-opts opts) (check-1 {:f f :spec spec} opts))) (defn checkable-syms "Given an opts map as per check, returns the set of syms that can be checked." ([] (checkable-syms nil)) ([opts] (validate-check-opts opts) (reduce into #{} [(filter fn-spec-name? (keys (s/registry))) (keys (:spec opts))]))) (defn check "Run generative tests for spec conformance on vars named by sym-or-syms, a symbol or collection of symbols. If sym-or-syms is not specified, check all checkable vars. The opts map includes the following optional keys, where stc aliases clojure.spec.test.check: ::stc/opts opts to flow through test.check/quick-check :gen map from spec names to generator overrides The ::stc/opts include :num-tests in addition to the keys documented by test.check. Generator overrides are passed to spec/gen when generating function args. Returns a lazy sequence of check result maps with the following keys :spec the spec tested :sym optional symbol naming the var tested :failure optional test failure ::stc/ret optional value returned by test.check/quick-check The value for :failure can be any exception. Exceptions thrown by spec itself will have an ::s/failure value in ex-data: :check-failed at least one checked return did not conform :no-args-spec no :args spec provided :no-fn no fn provided :no-fspec no fspec provided :no-gen unable to generate :args :instrument invalid args detected by instrument " ([] (check (checkable-syms))) ([sym-or-syms] (check sym-or-syms nil)) ([sym-or-syms opts] (->> (collectionize sym-or-syms) (filter (checkable-syms opts)) (pmap #(check-1 (sym->check-map %) opts))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; check reporting ;;;;;;;;;;;;;;;;;;;;;;;; (defn- failure-type [x] (::s/failure (ex-data x))) (defn- unwrap-failure [x] (if (failure-type x) (ex-data x) x)) (defn- result-type "Returns the type of the check result. This can be any of the ::s/failure keywords documented in 'check', or: :check-passed all checked fn returns conformed :check-threw checked fn threw an exception" [ret] (let [failure (:failure ret)] (cond (nil? failure) :check-passed (failure-type failure) (failure-type failure) :default :check-threw))) (defn abbrev-result "Given a check result, returns an abbreviated version suitable for summary use." [x] (if (:failure x) (-> (dissoc x ::stc/ret) (update :spec s/describe) (update :failure unwrap-failure)) (dissoc x :spec ::stc/ret))) (defn summarize-results "Given a collection of check-results, e.g. from 'check', pretty prints the summary-result (default abbrev-result) of each. Returns a map with :total, the total number of results, plus a key with a count for each different :type of result." ([check-results] (summarize-results check-results abbrev-result)) ([check-results summary-result] (reduce (fn [summary result] (pp/pprint (summary-result result)) (-> summary (update :total inc) (update (result-type result) (fnil inc 0)))) {:total 0} check-results)))
67861
; 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 clojure.spec.test (:refer-clojure :exclude [test]) (:require [clojure.pprint :as pp] [clojure.spec :as s] [clojure.spec.gen :as gen] [clojure.string :as str])) (in-ns 'clojure.spec.test.check) (in-ns 'clojure.spec.test) (alias 'stc 'clojure.spec.test.check) (defn- throwable? [x] (instance? Exception x)) ;;; Throwable (defn ->sym [x] (@#'s/->sym x)) (defn- ->var [s-or-v] (if (var? s-or-v) s-or-v (let [v (and (symbol? s-or-v) (resolve s-or-v))] (if (var? v) v (throw (ArgumentException. (str (pr-str s-or-v) " does not name a var"))))))) ;;; IllegalArgumentException. (defn- collectionize [x] (if (symbol? x) (list x) x)) (defn enumerate-namespace "Given a symbol naming an ns, or a collection of such symbols, returns the set of all symbols naming vars in those nses." [ns-sym-or-syms] (into #{} (mapcat (fn [ns-sym] (map (fn [name-sym] (symbol (name ns-sym) (name name-sym))) (keys (ns-interns ns-sym))))) (collectionize ns-sym-or-syms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; instrument ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private ^:dynamic *instrument-enabled* "if false, instrumented fns call straight through" true) (defn- fn-spec? "Fn-spec must include at least :args or :ret specs." [m] (or (:args m) (:ret m))) (defmacro with-instrument-disabled "Disables instrument's checking of calls, within a scope." [& body] `(binding [*instrument-enabled* nil] ~@body)) (defn- interpret-stack-trace-element "Given the vector-of-syms form of a stacktrace element produced by e.g. Throwable->map, returns a map form that adds some keys guessing the original Clojure names. Returns a map with :class class name symbol from stack trace :method method symbol from stack trace :file filename from stack trace :line line number from stack trace :var-scope optional Clojure var symbol scoping fn def :local-fn optional local Clojure symbol scoping fn def For non-Clojure fns, :scope and :local-fn will be absent." [[cls method file line]] (let [clojure? (contains? '#{invoke invokeStatic} method) demunge #(clojure.lang.Compiler/demunge %) degensym #(str/replace % #"--.*" "") [ns-sym name-sym local] (when clojure? (->> (str/split (str cls) #"\$" 3) (map demunge)))] (merge {:file file :line line :method method :class cls} (when (and ns-sym name-sym) {:var-scope (symbol ns-sym name-sym)}) (when local {:local-fn (symbol (degensym local))})))) (defn- stacktrace-relevant-to-instrument "Takes a coll of stack trace elements (as returned by StackTraceElement->vec) and returns a coll of maps as per interpret-stack-trace-element that are relevant to a failure in instrument." [elems] (let [plumbing? (fn [{:keys [var-scope]}] (contains? '#{clojure.spec.alpha.test/spec-checking-fn} var-scope))] (sequence (comp (map StackTraceElement->vec) (map interpret-stack-trace-element) (filter :var-scope) (drop-while plumbing?)) elems))) (defn- spec-checking-fn [v f fn-spec] (let [fn-spec (@#'s/maybe-spec fn-spec) conform! (fn [v role spec data args] (let [conformed (s/conform spec data)] (if (= ::s/invalid conformed) (let [caller (->> (System.Diagnostics.StackTrace. true) ;;; (.getStackTrace (Thread/currentThread)) stacktrace-relevant-to-instrument first) ed (merge (assoc (s/explain-data* spec [role] [] [] data) ::s/args args ::s/failure :instrument) (when caller {::caller (dissoc caller :class :method)}))] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (s/explain-out ed))) ed))) conformed)))] (fn [& args] (if *instrument-enabled* (with-instrument-disabled (when (:args fn-spec) (conform! v :args (:args fn-spec) args args)) (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args))) (.applyTo ^clojure.lang.IFn f args))))) (defn- no-fspec [v spec] (ex-info (str "Fn at " v " is not spec'ed.") {:var v :spec spec ::s/failure :no-fspec})) (defonce ^:private instrumented-vars (atom {})) (defn- instrument-choose-fn "Helper for instrument." [f spec sym {over :gen :keys [stub replace]}] (if (some #{sym} stub) (-> spec (s/gen over) gen/generate) (get replace sym f))) (defn- instrument-choose-spec "Helper for instrument" [spec sym {overrides :spec}] (get overrides sym spec)) (defn- instrument-1 [s opts] (when-let [v (resolve s)] (when-not (-> v meta :macro) (let [spec (s/get-spec v) {:keys [raw wrapped]} (get @instrumented-vars v) current @v to-wrap (if (= wrapped current) raw current) ospec (or (instrument-choose-spec spec s opts) (throw (no-fspec v spec))) ofn (instrument-choose-fn to-wrap ospec s opts) checked (spec-checking-fn v ofn ospec)] (alter-var-root v (constantly checked)) (swap! instrumented-vars assoc v {:raw to-wrap :wrapped checked}) (->sym v))))) (defn- unstrument-1 [s] (when-let [v (resolve s)] (when-let [{:keys [raw wrapped]} (get @instrumented-vars v)] (swap! instrumented-vars dissoc v) (let [current @v] (when (= wrapped current) (alter-var-root v (constantly raw)) (->sym v)))))) (defn- opt-syms "Returns set of symbols referenced by 'instrument' opts map" [opts] (reduce into #{} [(:stub opts) (keys (:replace opts)) (keys (:spec opts))])) (defn- fn-spec-name? [s] (and (symbol? s) (not (some-> (resolve s) meta :macro)))) (defn instrumentable-syms "Given an opts map as per instrument, returns the set of syms that can be instrumented." ([] (instrumentable-syms nil)) ([opts] (assert (every? ident? (keys (:gen opts))) "instrument :gen expects ident keys") (reduce into #{} [(filter fn-spec-name? (keys (s/registry))) (keys (:spec opts)) (:stub opts) (keys (:replace opts))]))) (defn instrument "Instruments the vars named by sym-or-syms, a symbol or collection of symbols, or all instrumentable vars if sym-or-syms is not specified. If a var has an :args fn-spec, sets the var's root binding to a fn that checks arg conformance (throwing an exception on failure) before delegating to the original fn. The opts map can be used to override registered specs, and/or to replace fn implementations entirely. Opts for symbols not included in sym-or-syms are ignored. This facilitates sharing a common options map across many different calls to instrument. The opts map may have the following keys: :spec a map from var-name symbols to override specs :stub a set of var-name symbols to be replaced by stubs :gen a map from spec names to generator overrides :replace a map from var-name symbols to replacement fns :spec overrides registered fn-specs with specs your provide. Use :spec overrides to provide specs for libraries that do not have them, or to constrain your own use of a fn to a subset of its spec'ed contract. :stub replaces a fn with a stub that checks :args, then uses the :ret spec to generate a return value. :gen overrides are used only for :stub generation. :replace replaces a fn with a fn that checks args conformance, then invokes the fn you provide, enabling arbitrary stubbing and mocking. :spec can be used in combination with :stub or :replace. Returns a collection of syms naming the vars instrumented." ([] (instrument (instrumentable-syms))) ([sym-or-syms] (instrument sym-or-syms nil)) ([sym-or-syms opts] (locking instrumented-vars (into [] (comp (filter (instrumentable-syms opts)) (distinct) (map #(instrument-1 % opts)) (remove nil?)) (collectionize sym-or-syms))))) (defn unstrument "Undoes instrument on the vars named by sym-or-syms, specified as in instrument. With no args, unstruments all instrumented vars. Returns a collection of syms naming the vars unstrumented." ([] (unstrument (map ->sym (keys @instrumented-vars)))) ([sym-or-syms] (locking instrumented-vars (into [] (comp (filter symbol?) (map unstrument-1) (remove nil?)) (collectionize sym-or-syms))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; testing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- explain-check [args spec v role] (ex-info "Specification-based check failed" (when-not (s/valid? spec v nil) (assoc (s/explain-data* spec [role] [] [] v) ::args args ::val v ::s/failure :check-failed)))) (defn- check-call "Returns true if call passes specs, otherwise *returns* an exception with explain-data + ::s/failure." [f specs args] (let [cargs (when (:args specs) (s/conform (:args specs) args))] (if (= cargs ::s/invalid) (explain-check args (:args specs) args :args) (let [ret (apply f args) cret (when (:ret specs) (s/conform (:ret specs) ret))] (if (= cret ::s/invalid) (explain-check args (:ret specs) ret :ret) (if (and (:args specs) (:ret specs) (:fn specs)) (if (s/valid? (:fn specs) {:args cargs :ret cret}) true (explain-check args (:fn specs) {:args cargs :ret cret} :fn)) true)))))) (defn- quick-check [f specs {gen :gen opts ::stc/opts}] (let [{:keys [num-tests] :or {num-tests 1000}} opts g (try (s/gen (:args specs) gen) (catch Exception t t))] ;;; Throwable (if (throwable? g) {:result g} (let [prop (gen/for-all* [g] #(check-call f specs %))] (apply gen/quick-check num-tests prop (mapcat identity opts)))))) (defn- make-check-result "Builds spec result map." [check-sym spec test-check-ret] (merge {:spec spec ::stc/ret test-check-ret} (when check-sym {:sym check-sym}) (when-let [result (-> test-check-ret :result)] (when-not (true? result) {:failure result})) (when-let [shrunk (-> test-check-ret :shrunk)] {:failure (:result shrunk)}))) (defn- check-1 [{:keys [s f v spec]} opts] (let [re-inst? (and v (seq (unstrument s)) true) f (or f (when v @v)) specd (s/spec spec)] (try (cond (or (nil? f) (some-> v meta :macro)) {:failure (ex-info "No fn to spec" {::s/failure :no-fn}) :sym s :spec spec} (:args specd) (let [tcret (quick-check f specd opts)] (make-check-result s spec tcret)) :default {:failure (ex-info "No :args spec" {::s/failure :no-args-spec}) :sym s :spec spec}) (finally (when re-inst? (instrument s)))))) (defn- sym->check-map [s] (let [v (resolve s)] {:s s :v v :spec (when v (s/get-spec v))})) (defn- validate-check-opts [opts] (assert (every? ident? (keys (:gen opts))) "check :gen expects ident keys")) (defn check-fn "Runs generative tests for fn f using spec and opts. See 'check' for options and return." ([f spec] (check-fn f spec nil)) ([f spec opts] (validate-check-opts opts) (check-1 {:f f :spec spec} opts))) (defn checkable-syms "Given an opts map as per check, returns the set of syms that can be checked." ([] (checkable-syms nil)) ([opts] (validate-check-opts opts) (reduce into #{} [(filter fn-spec-name? (keys (s/registry))) (keys (:spec opts))]))) (defn check "Run generative tests for spec conformance on vars named by sym-or-syms, a symbol or collection of symbols. If sym-or-syms is not specified, check all checkable vars. The opts map includes the following optional keys, where stc aliases clojure.spec.test.check: ::stc/opts opts to flow through test.check/quick-check :gen map from spec names to generator overrides The ::stc/opts include :num-tests in addition to the keys documented by test.check. Generator overrides are passed to spec/gen when generating function args. Returns a lazy sequence of check result maps with the following keys :spec the spec tested :sym optional symbol naming the var tested :failure optional test failure ::stc/ret optional value returned by test.check/quick-check The value for :failure can be any exception. Exceptions thrown by spec itself will have an ::s/failure value in ex-data: :check-failed at least one checked return did not conform :no-args-spec no :args spec provided :no-fn no fn provided :no-fspec no fspec provided :no-gen unable to generate :args :instrument invalid args detected by instrument " ([] (check (checkable-syms))) ([sym-or-syms] (check sym-or-syms nil)) ([sym-or-syms opts] (->> (collectionize sym-or-syms) (filter (checkable-syms opts)) (pmap #(check-1 (sym->check-map %) opts))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; check reporting ;;;;;;;;;;;;;;;;;;;;;;;; (defn- failure-type [x] (::s/failure (ex-data x))) (defn- unwrap-failure [x] (if (failure-type x) (ex-data x) x)) (defn- result-type "Returns the type of the check result. This can be any of the ::s/failure keywords documented in 'check', or: :check-passed all checked fn returns conformed :check-threw checked fn threw an exception" [ret] (let [failure (:failure ret)] (cond (nil? failure) :check-passed (failure-type failure) (failure-type failure) :default :check-threw))) (defn abbrev-result "Given a check result, returns an abbreviated version suitable for summary use." [x] (if (:failure x) (-> (dissoc x ::stc/ret) (update :spec s/describe) (update :failure unwrap-failure)) (dissoc x :spec ::stc/ret))) (defn summarize-results "Given a collection of check-results, e.g. from 'check', pretty prints the summary-result (default abbrev-result) of each. Returns a map with :total, the total number of results, plus a key with a count for each different :type of result." ([check-results] (summarize-results check-results abbrev-result)) ([check-results summary-result] (reduce (fn [summary result] (pp/pprint (summary-result result)) (-> summary (update :total inc) (update (result-type result) (fnil inc 0)))) {:total 0} check-results)))
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 clojure.spec.test (:refer-clojure :exclude [test]) (:require [clojure.pprint :as pp] [clojure.spec :as s] [clojure.spec.gen :as gen] [clojure.string :as str])) (in-ns 'clojure.spec.test.check) (in-ns 'clojure.spec.test) (alias 'stc 'clojure.spec.test.check) (defn- throwable? [x] (instance? Exception x)) ;;; Throwable (defn ->sym [x] (@#'s/->sym x)) (defn- ->var [s-or-v] (if (var? s-or-v) s-or-v (let [v (and (symbol? s-or-v) (resolve s-or-v))] (if (var? v) v (throw (ArgumentException. (str (pr-str s-or-v) " does not name a var"))))))) ;;; IllegalArgumentException. (defn- collectionize [x] (if (symbol? x) (list x) x)) (defn enumerate-namespace "Given a symbol naming an ns, or a collection of such symbols, returns the set of all symbols naming vars in those nses." [ns-sym-or-syms] (into #{} (mapcat (fn [ns-sym] (map (fn [name-sym] (symbol (name ns-sym) (name name-sym))) (keys (ns-interns ns-sym))))) (collectionize ns-sym-or-syms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; instrument ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private ^:dynamic *instrument-enabled* "if false, instrumented fns call straight through" true) (defn- fn-spec? "Fn-spec must include at least :args or :ret specs." [m] (or (:args m) (:ret m))) (defmacro with-instrument-disabled "Disables instrument's checking of calls, within a scope." [& body] `(binding [*instrument-enabled* nil] ~@body)) (defn- interpret-stack-trace-element "Given the vector-of-syms form of a stacktrace element produced by e.g. Throwable->map, returns a map form that adds some keys guessing the original Clojure names. Returns a map with :class class name symbol from stack trace :method method symbol from stack trace :file filename from stack trace :line line number from stack trace :var-scope optional Clojure var symbol scoping fn def :local-fn optional local Clojure symbol scoping fn def For non-Clojure fns, :scope and :local-fn will be absent." [[cls method file line]] (let [clojure? (contains? '#{invoke invokeStatic} method) demunge #(clojure.lang.Compiler/demunge %) degensym #(str/replace % #"--.*" "") [ns-sym name-sym local] (when clojure? (->> (str/split (str cls) #"\$" 3) (map demunge)))] (merge {:file file :line line :method method :class cls} (when (and ns-sym name-sym) {:var-scope (symbol ns-sym name-sym)}) (when local {:local-fn (symbol (degensym local))})))) (defn- stacktrace-relevant-to-instrument "Takes a coll of stack trace elements (as returned by StackTraceElement->vec) and returns a coll of maps as per interpret-stack-trace-element that are relevant to a failure in instrument." [elems] (let [plumbing? (fn [{:keys [var-scope]}] (contains? '#{clojure.spec.alpha.test/spec-checking-fn} var-scope))] (sequence (comp (map StackTraceElement->vec) (map interpret-stack-trace-element) (filter :var-scope) (drop-while plumbing?)) elems))) (defn- spec-checking-fn [v f fn-spec] (let [fn-spec (@#'s/maybe-spec fn-spec) conform! (fn [v role spec data args] (let [conformed (s/conform spec data)] (if (= ::s/invalid conformed) (let [caller (->> (System.Diagnostics.StackTrace. true) ;;; (.getStackTrace (Thread/currentThread)) stacktrace-relevant-to-instrument first) ed (merge (assoc (s/explain-data* spec [role] [] [] data) ::s/args args ::s/failure :instrument) (when caller {::caller (dissoc caller :class :method)}))] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (s/explain-out ed))) ed))) conformed)))] (fn [& args] (if *instrument-enabled* (with-instrument-disabled (when (:args fn-spec) (conform! v :args (:args fn-spec) args args)) (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args))) (.applyTo ^clojure.lang.IFn f args))))) (defn- no-fspec [v spec] (ex-info (str "Fn at " v " is not spec'ed.") {:var v :spec spec ::s/failure :no-fspec})) (defonce ^:private instrumented-vars (atom {})) (defn- instrument-choose-fn "Helper for instrument." [f spec sym {over :gen :keys [stub replace]}] (if (some #{sym} stub) (-> spec (s/gen over) gen/generate) (get replace sym f))) (defn- instrument-choose-spec "Helper for instrument" [spec sym {overrides :spec}] (get overrides sym spec)) (defn- instrument-1 [s opts] (when-let [v (resolve s)] (when-not (-> v meta :macro) (let [spec (s/get-spec v) {:keys [raw wrapped]} (get @instrumented-vars v) current @v to-wrap (if (= wrapped current) raw current) ospec (or (instrument-choose-spec spec s opts) (throw (no-fspec v spec))) ofn (instrument-choose-fn to-wrap ospec s opts) checked (spec-checking-fn v ofn ospec)] (alter-var-root v (constantly checked)) (swap! instrumented-vars assoc v {:raw to-wrap :wrapped checked}) (->sym v))))) (defn- unstrument-1 [s] (when-let [v (resolve s)] (when-let [{:keys [raw wrapped]} (get @instrumented-vars v)] (swap! instrumented-vars dissoc v) (let [current @v] (when (= wrapped current) (alter-var-root v (constantly raw)) (->sym v)))))) (defn- opt-syms "Returns set of symbols referenced by 'instrument' opts map" [opts] (reduce into #{} [(:stub opts) (keys (:replace opts)) (keys (:spec opts))])) (defn- fn-spec-name? [s] (and (symbol? s) (not (some-> (resolve s) meta :macro)))) (defn instrumentable-syms "Given an opts map as per instrument, returns the set of syms that can be instrumented." ([] (instrumentable-syms nil)) ([opts] (assert (every? ident? (keys (:gen opts))) "instrument :gen expects ident keys") (reduce into #{} [(filter fn-spec-name? (keys (s/registry))) (keys (:spec opts)) (:stub opts) (keys (:replace opts))]))) (defn instrument "Instruments the vars named by sym-or-syms, a symbol or collection of symbols, or all instrumentable vars if sym-or-syms is not specified. If a var has an :args fn-spec, sets the var's root binding to a fn that checks arg conformance (throwing an exception on failure) before delegating to the original fn. The opts map can be used to override registered specs, and/or to replace fn implementations entirely. Opts for symbols not included in sym-or-syms are ignored. This facilitates sharing a common options map across many different calls to instrument. The opts map may have the following keys: :spec a map from var-name symbols to override specs :stub a set of var-name symbols to be replaced by stubs :gen a map from spec names to generator overrides :replace a map from var-name symbols to replacement fns :spec overrides registered fn-specs with specs your provide. Use :spec overrides to provide specs for libraries that do not have them, or to constrain your own use of a fn to a subset of its spec'ed contract. :stub replaces a fn with a stub that checks :args, then uses the :ret spec to generate a return value. :gen overrides are used only for :stub generation. :replace replaces a fn with a fn that checks args conformance, then invokes the fn you provide, enabling arbitrary stubbing and mocking. :spec can be used in combination with :stub or :replace. Returns a collection of syms naming the vars instrumented." ([] (instrument (instrumentable-syms))) ([sym-or-syms] (instrument sym-or-syms nil)) ([sym-or-syms opts] (locking instrumented-vars (into [] (comp (filter (instrumentable-syms opts)) (distinct) (map #(instrument-1 % opts)) (remove nil?)) (collectionize sym-or-syms))))) (defn unstrument "Undoes instrument on the vars named by sym-or-syms, specified as in instrument. With no args, unstruments all instrumented vars. Returns a collection of syms naming the vars unstrumented." ([] (unstrument (map ->sym (keys @instrumented-vars)))) ([sym-or-syms] (locking instrumented-vars (into [] (comp (filter symbol?) (map unstrument-1) (remove nil?)) (collectionize sym-or-syms))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; testing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- explain-check [args spec v role] (ex-info "Specification-based check failed" (when-not (s/valid? spec v nil) (assoc (s/explain-data* spec [role] [] [] v) ::args args ::val v ::s/failure :check-failed)))) (defn- check-call "Returns true if call passes specs, otherwise *returns* an exception with explain-data + ::s/failure." [f specs args] (let [cargs (when (:args specs) (s/conform (:args specs) args))] (if (= cargs ::s/invalid) (explain-check args (:args specs) args :args) (let [ret (apply f args) cret (when (:ret specs) (s/conform (:ret specs) ret))] (if (= cret ::s/invalid) (explain-check args (:ret specs) ret :ret) (if (and (:args specs) (:ret specs) (:fn specs)) (if (s/valid? (:fn specs) {:args cargs :ret cret}) true (explain-check args (:fn specs) {:args cargs :ret cret} :fn)) true)))))) (defn- quick-check [f specs {gen :gen opts ::stc/opts}] (let [{:keys [num-tests] :or {num-tests 1000}} opts g (try (s/gen (:args specs) gen) (catch Exception t t))] ;;; Throwable (if (throwable? g) {:result g} (let [prop (gen/for-all* [g] #(check-call f specs %))] (apply gen/quick-check num-tests prop (mapcat identity opts)))))) (defn- make-check-result "Builds spec result map." [check-sym spec test-check-ret] (merge {:spec spec ::stc/ret test-check-ret} (when check-sym {:sym check-sym}) (when-let [result (-> test-check-ret :result)] (when-not (true? result) {:failure result})) (when-let [shrunk (-> test-check-ret :shrunk)] {:failure (:result shrunk)}))) (defn- check-1 [{:keys [s f v spec]} opts] (let [re-inst? (and v (seq (unstrument s)) true) f (or f (when v @v)) specd (s/spec spec)] (try (cond (or (nil? f) (some-> v meta :macro)) {:failure (ex-info "No fn to spec" {::s/failure :no-fn}) :sym s :spec spec} (:args specd) (let [tcret (quick-check f specd opts)] (make-check-result s spec tcret)) :default {:failure (ex-info "No :args spec" {::s/failure :no-args-spec}) :sym s :spec spec}) (finally (when re-inst? (instrument s)))))) (defn- sym->check-map [s] (let [v (resolve s)] {:s s :v v :spec (when v (s/get-spec v))})) (defn- validate-check-opts [opts] (assert (every? ident? (keys (:gen opts))) "check :gen expects ident keys")) (defn check-fn "Runs generative tests for fn f using spec and opts. See 'check' for options and return." ([f spec] (check-fn f spec nil)) ([f spec opts] (validate-check-opts opts) (check-1 {:f f :spec spec} opts))) (defn checkable-syms "Given an opts map as per check, returns the set of syms that can be checked." ([] (checkable-syms nil)) ([opts] (validate-check-opts opts) (reduce into #{} [(filter fn-spec-name? (keys (s/registry))) (keys (:spec opts))]))) (defn check "Run generative tests for spec conformance on vars named by sym-or-syms, a symbol or collection of symbols. If sym-or-syms is not specified, check all checkable vars. The opts map includes the following optional keys, where stc aliases clojure.spec.test.check: ::stc/opts opts to flow through test.check/quick-check :gen map from spec names to generator overrides The ::stc/opts include :num-tests in addition to the keys documented by test.check. Generator overrides are passed to spec/gen when generating function args. Returns a lazy sequence of check result maps with the following keys :spec the spec tested :sym optional symbol naming the var tested :failure optional test failure ::stc/ret optional value returned by test.check/quick-check The value for :failure can be any exception. Exceptions thrown by spec itself will have an ::s/failure value in ex-data: :check-failed at least one checked return did not conform :no-args-spec no :args spec provided :no-fn no fn provided :no-fspec no fspec provided :no-gen unable to generate :args :instrument invalid args detected by instrument " ([] (check (checkable-syms))) ([sym-or-syms] (check sym-or-syms nil)) ([sym-or-syms opts] (->> (collectionize sym-or-syms) (filter (checkable-syms opts)) (pmap #(check-1 (sym->check-map %) opts))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; check reporting ;;;;;;;;;;;;;;;;;;;;;;;; (defn- failure-type [x] (::s/failure (ex-data x))) (defn- unwrap-failure [x] (if (failure-type x) (ex-data x) x)) (defn- result-type "Returns the type of the check result. This can be any of the ::s/failure keywords documented in 'check', or: :check-passed all checked fn returns conformed :check-threw checked fn threw an exception" [ret] (let [failure (:failure ret)] (cond (nil? failure) :check-passed (failure-type failure) (failure-type failure) :default :check-threw))) (defn abbrev-result "Given a check result, returns an abbreviated version suitable for summary use." [x] (if (:failure x) (-> (dissoc x ::stc/ret) (update :spec s/describe) (update :failure unwrap-failure)) (dissoc x :spec ::stc/ret))) (defn summarize-results "Given a collection of check-results, e.g. from 'check', pretty prints the summary-result (default abbrev-result) of each. Returns a map with :total, the total number of results, plus a key with a count for each different :type of result." ([check-results] (summarize-results check-results abbrev-result)) ([check-results summary-result] (reduce (fn [summary result] (pp/pprint (summary-result result)) (-> summary (update :total inc) (update (result-type result) (fnil inc 0)))) {:total 0} check-results)))
[ { "context": " keyrings \"/usr/share/keyrings\"\n key \"google-chrome-key\"\n repo \"deb [arch=amd64] http://dl.google.", "end": 729, "score": 0.6337774991989136, "start": 712, "tag": "KEY", "value": "google-chrome-key" }, { "context": "in\"]\n (download url (<< \"~{keyrings}/~{key}\") \"5dfdccb6f67eea65aeb717f1ef90a81fa80fe77c60f4d3dfdf45c969748069c5\")\n (key-file (<< \"~{keyrings}/~{key}\"))\n (f", "end": 924, "score": 0.9997557997703552, "start": 860, "tag": "KEY", "value": "5dfdccb6f67eea65aeb717f1ef90a81fa80fe77c60f4d3dfdf45c969748069c5" } ]
src/re_cipes/chrome.clj
re-ops/re-cipes
7
(ns re-cipes.chrome "Google chrome" (:require [re-cipes.access :refer (permissions)] [clojure.core.strint :refer (<<)] [re-cog.resources.file :refer (file line)] [re-cog.resources.package :refer (package key-file update-)] [re-cog.resources.user :refer (group-add)] [re-cog.resources.download :refer (download)] [re-cog.common.recipe :refer (require-recipe)])) (require-recipe) (def-inline {:depends #'re-cipes.access/permissions} install "Install google chrome" [] (let [sources "/etc/apt/sources.list.d" listing (<< "~{sources}/google-chrome.list") url "https://dl-ssl.google.com/linux/linux_signing_key.pub" keyrings "/usr/share/keyrings" key "google-chrome-key" repo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main"] (download url (<< "~{keyrings}/~{key}") "5dfdccb6f67eea65aeb717f1ef90a81fa80fe77c60f4d3dfdf45c969748069c5") (key-file (<< "~{keyrings}/~{key}")) (file listing :present) (line listing repo :present) (update-) (package "google-chrome-stable" :present)))
16760
(ns re-cipes.chrome "Google chrome" (:require [re-cipes.access :refer (permissions)] [clojure.core.strint :refer (<<)] [re-cog.resources.file :refer (file line)] [re-cog.resources.package :refer (package key-file update-)] [re-cog.resources.user :refer (group-add)] [re-cog.resources.download :refer (download)] [re-cog.common.recipe :refer (require-recipe)])) (require-recipe) (def-inline {:depends #'re-cipes.access/permissions} install "Install google chrome" [] (let [sources "/etc/apt/sources.list.d" listing (<< "~{sources}/google-chrome.list") url "https://dl-ssl.google.com/linux/linux_signing_key.pub" keyrings "/usr/share/keyrings" key "<KEY>" repo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main"] (download url (<< "~{keyrings}/~{key}") "<KEY>") (key-file (<< "~{keyrings}/~{key}")) (file listing :present) (line listing repo :present) (update-) (package "google-chrome-stable" :present)))
true
(ns re-cipes.chrome "Google chrome" (:require [re-cipes.access :refer (permissions)] [clojure.core.strint :refer (<<)] [re-cog.resources.file :refer (file line)] [re-cog.resources.package :refer (package key-file update-)] [re-cog.resources.user :refer (group-add)] [re-cog.resources.download :refer (download)] [re-cog.common.recipe :refer (require-recipe)])) (require-recipe) (def-inline {:depends #'re-cipes.access/permissions} install "Install google chrome" [] (let [sources "/etc/apt/sources.list.d" listing (<< "~{sources}/google-chrome.list") url "https://dl-ssl.google.com/linux/linux_signing_key.pub" keyrings "/usr/share/keyrings" key "PI:KEY:<KEY>END_PI" repo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main"] (download url (<< "~{keyrings}/~{key}") "PI:KEY:<KEY>END_PI") (key-file (<< "~{keyrings}/~{key}")) (file listing :present) (line listing repo :present) (update-) (package "google-chrome-stable" :present)))
[ { "context": ";; Copyright (c) Stuart Sierra, 2012. All rights reserved. The use and\n;; distri", "end": 30, "score": 0.9998846054077148, "start": 17, "tag": "NAME", "value": "Stuart Sierra" }, { "context": "or any other, from this software.\n\n(ns ^{:author \"Stuart Sierra\"\n :doc \"Parse Clojure namespace (ns) declara", "end": 493, "score": 0.9998913407325745, "start": 480, "tag": "NAME", "value": "Stuart Sierra" } ]
server/target/clojure/tools/namespace/parse.clj
OctavioBR/healthcheck
0
;; Copyright (c) Stuart Sierra, 2012. 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 ^{:author "Stuart Sierra" :doc "Parse Clojure namespace (ns) declarations and extract dependencies."} clojure.tools.namespace.parse (:require [clojure.set :as set])) (defn- read-clj "Calls clojure.core/read. If reader conditionals are supported (Clojure 1.7) then adds options {:read-cond :allow}." [rdr] (if (resolve 'clojure.core/reader-conditional?) (read {:read-cond :allow} rdr) (read rdr))) (defn comment? "Returns true if form is a (comment ...)" [form] (and (list? form) (= 'comment (first form)))) (defn ns-decl? "Returns true if form is a (ns ...) declaration." [form] (and (list? form) (= 'ns (first form)))) (defn read-ns-decl "Attempts to read a (ns ...) declaration from a java.io.PushbackReader, and returns the unevaluated form. Returns the first top-level ns form found. Returns nil if read fails or if a ns declaration cannot be found. Note that read can execute code (controlled by *read-eval*), and as such should be used only with trusted sources." [rdr] {:pre [(instance? java.io.PushbackReader rdr)]} (try (loop [] (let [form (doto (read-clj rdr) str)] ; str forces errors, see TNS-1 (if (ns-decl? form) form (recur)))) (catch Exception e nil))) ;;; Parsing dependencies (defn- prefix-spec? "Returns true if form represents a libspec prefix list like (prefix name1 name1) or [com.example.prefix [name1 :as name1]]" [form] (and (sequential? form) ; should be a list, but often is not (symbol? (first form)) (not-any? keyword? form) (< 1 (count form)))) ; not a bare vector like [foo] (defn- option-spec? "Returns true if form represents a libspec vector containing optional keyword arguments like [namespace :as alias] or [namespace :refer (x y)] or just [namespace]" [form] (and (sequential? form) ; should be a vector, but often is not (symbol? (first form)) (or (keyword? (second form)) ; vector like [foo :as f] (= 1 (count form))))) ; bare vector like [foo] (defn- deps-from-libspec [prefix form] (cond (prefix-spec? form) (mapcat (fn [f] (deps-from-libspec (symbol (str (when prefix (str prefix ".")) (first form))) f)) (rest form)) (option-spec? form) (deps-from-libspec prefix (first form)) (symbol? form) (list (symbol (str (when prefix (str prefix ".")) form))) (keyword? form) ; Some people write (:require ... :reload-all) nil :else (throw (IllegalArgumentException. (pr-str "Unparsable namespace form:" form))))) (defn- deps-from-ns-form [form] (when (and (sequential? form) ; should be list but sometimes is not (contains? #{:use :require 'use 'require} (first form))) (mapcat #(deps-from-libspec nil %) (rest form)))) (defn deps-from-ns-decl "Given an (ns...) declaration form (unevaluated), returns a set of symbols naming the dependencies of that namespace. Handles :use and :require clauses but not :load." [decl] (set (mapcat deps-from-ns-form decl)))
118565
;; Copyright (c) <NAME>, 2012. 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 ^{:author "<NAME>" :doc "Parse Clojure namespace (ns) declarations and extract dependencies."} clojure.tools.namespace.parse (:require [clojure.set :as set])) (defn- read-clj "Calls clojure.core/read. If reader conditionals are supported (Clojure 1.7) then adds options {:read-cond :allow}." [rdr] (if (resolve 'clojure.core/reader-conditional?) (read {:read-cond :allow} rdr) (read rdr))) (defn comment? "Returns true if form is a (comment ...)" [form] (and (list? form) (= 'comment (first form)))) (defn ns-decl? "Returns true if form is a (ns ...) declaration." [form] (and (list? form) (= 'ns (first form)))) (defn read-ns-decl "Attempts to read a (ns ...) declaration from a java.io.PushbackReader, and returns the unevaluated form. Returns the first top-level ns form found. Returns nil if read fails or if a ns declaration cannot be found. Note that read can execute code (controlled by *read-eval*), and as such should be used only with trusted sources." [rdr] {:pre [(instance? java.io.PushbackReader rdr)]} (try (loop [] (let [form (doto (read-clj rdr) str)] ; str forces errors, see TNS-1 (if (ns-decl? form) form (recur)))) (catch Exception e nil))) ;;; Parsing dependencies (defn- prefix-spec? "Returns true if form represents a libspec prefix list like (prefix name1 name1) or [com.example.prefix [name1 :as name1]]" [form] (and (sequential? form) ; should be a list, but often is not (symbol? (first form)) (not-any? keyword? form) (< 1 (count form)))) ; not a bare vector like [foo] (defn- option-spec? "Returns true if form represents a libspec vector containing optional keyword arguments like [namespace :as alias] or [namespace :refer (x y)] or just [namespace]" [form] (and (sequential? form) ; should be a vector, but often is not (symbol? (first form)) (or (keyword? (second form)) ; vector like [foo :as f] (= 1 (count form))))) ; bare vector like [foo] (defn- deps-from-libspec [prefix form] (cond (prefix-spec? form) (mapcat (fn [f] (deps-from-libspec (symbol (str (when prefix (str prefix ".")) (first form))) f)) (rest form)) (option-spec? form) (deps-from-libspec prefix (first form)) (symbol? form) (list (symbol (str (when prefix (str prefix ".")) form))) (keyword? form) ; Some people write (:require ... :reload-all) nil :else (throw (IllegalArgumentException. (pr-str "Unparsable namespace form:" form))))) (defn- deps-from-ns-form [form] (when (and (sequential? form) ; should be list but sometimes is not (contains? #{:use :require 'use 'require} (first form))) (mapcat #(deps-from-libspec nil %) (rest form)))) (defn deps-from-ns-decl "Given an (ns...) declaration form (unevaluated), returns a set of symbols naming the dependencies of that namespace. Handles :use and :require clauses but not :load." [decl] (set (mapcat deps-from-ns-form decl)))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, 2012. 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 ^{:author "PI:NAME:<NAME>END_PI" :doc "Parse Clojure namespace (ns) declarations and extract dependencies."} clojure.tools.namespace.parse (:require [clojure.set :as set])) (defn- read-clj "Calls clojure.core/read. If reader conditionals are supported (Clojure 1.7) then adds options {:read-cond :allow}." [rdr] (if (resolve 'clojure.core/reader-conditional?) (read {:read-cond :allow} rdr) (read rdr))) (defn comment? "Returns true if form is a (comment ...)" [form] (and (list? form) (= 'comment (first form)))) (defn ns-decl? "Returns true if form is a (ns ...) declaration." [form] (and (list? form) (= 'ns (first form)))) (defn read-ns-decl "Attempts to read a (ns ...) declaration from a java.io.PushbackReader, and returns the unevaluated form. Returns the first top-level ns form found. Returns nil if read fails or if a ns declaration cannot be found. Note that read can execute code (controlled by *read-eval*), and as such should be used only with trusted sources." [rdr] {:pre [(instance? java.io.PushbackReader rdr)]} (try (loop [] (let [form (doto (read-clj rdr) str)] ; str forces errors, see TNS-1 (if (ns-decl? form) form (recur)))) (catch Exception e nil))) ;;; Parsing dependencies (defn- prefix-spec? "Returns true if form represents a libspec prefix list like (prefix name1 name1) or [com.example.prefix [name1 :as name1]]" [form] (and (sequential? form) ; should be a list, but often is not (symbol? (first form)) (not-any? keyword? form) (< 1 (count form)))) ; not a bare vector like [foo] (defn- option-spec? "Returns true if form represents a libspec vector containing optional keyword arguments like [namespace :as alias] or [namespace :refer (x y)] or just [namespace]" [form] (and (sequential? form) ; should be a vector, but often is not (symbol? (first form)) (or (keyword? (second form)) ; vector like [foo :as f] (= 1 (count form))))) ; bare vector like [foo] (defn- deps-from-libspec [prefix form] (cond (prefix-spec? form) (mapcat (fn [f] (deps-from-libspec (symbol (str (when prefix (str prefix ".")) (first form))) f)) (rest form)) (option-spec? form) (deps-from-libspec prefix (first form)) (symbol? form) (list (symbol (str (when prefix (str prefix ".")) form))) (keyword? form) ; Some people write (:require ... :reload-all) nil :else (throw (IllegalArgumentException. (pr-str "Unparsable namespace form:" form))))) (defn- deps-from-ns-form [form] (when (and (sequential? form) ; should be list but sometimes is not (contains? #{:use :require 'use 'require} (first form))) (mapcat #(deps-from-libspec nil %) (rest form)))) (defn deps-from-ns-decl "Given an (ns...) declaration form (unevaluated), returns a set of symbols naming the dependencies of that namespace. Handles :use and :require clauses but not :load." [decl] (set (mapcat deps-from-ns-form decl)))
[ { "context": " (:file recording)\n obj-key (str \"facebook-\" user-id \"/\" (oget file :name))\n bucket ", "end": 918, "score": 0.8418424129486084, "start": 908, "tag": "KEY", "value": "facebook-\"" }, { "context": "ording)\n obj-key (str \"facebook-\" user-id \"/\" (oget file :name))\n bucket (aws/b", "end": 926, "score": 0.6909536719322205, "start": 924, "tag": "KEY", "value": "id" } ]
src/cljs/aws_transcribe_clj/transcribe/fx.cljs
Flexiana/aws-transcribe-clj
1
(ns aws-transcribe-clj.transcribe.fx (:require [cljs.core.async :as a] [oops.core :refer [oget]] [re-frame.core :as rf] [aws-transcribe-clj.aws.sdk :as aws] [aws-transcribe-clj.common :as c] [aws-transcribe-clj.transcribe.fx.audio :as audio] [aws-transcribe-clj.transcribe.fx.transcription-job :as tjob])) (rf/reg-fx ::record-audio! (fn [[params {:keys [on-stop on-error] :as events}]] (let [output (a/chan)] (a/go (audio/record! (assoc params :output output) events) (let [result (a/<! output) event (if (instance? js/Error result) on-error on-stop)] (rf/dispatch (conj event result))))))) (rf/reg-fx ::upload! (fn [[{:keys [recording user-id]} {:keys [bucket-name] :as opts} {:keys [on-success on-error]}]] (let [file (:file recording) obj-key (str "facebook-" user-id "/" (oget file :name)) bucket (aws/bucket-service opts)] (aws/put-object bucket #js{:Key obj-key :ContentType (oget file :type) :Body file} (fn [err _] (if (some? err) (rf/dispatch (conj on-error err)) (rf/dispatch (conj on-success {:recording recording :s3-object {:object-key obj-key :bucket-name bucket-name}})))))))) (rf/reg-fx ::transcribe! (fn [[{:keys [recording user-id] :as context} {:keys [transcripts-bucket] :as opts} {:keys [on-error] :as events}]] (let [{:keys [object-key bucket-name]} (:s3-object recording) transcribe (aws/transcribe-service opts) watcher (a/chan) opts' (assoc opts :aws-transcribe transcribe :watcher watcher)] (a/go (aws/start-transcription-job transcribe #js{:TranscriptionJobName (str user-id "-" (:id recording)) :LanguageCode "en-US" :Media #js{:MediaFileUri (str "s3://" bucket-name "/" object-key)} :OutputBucketName transcripts-bucket} (tjob/start-transcription-job-callback context opts' events)) (let [result (a/<! watcher)] (if (c/js-error? result) (rf/dispatch (conj on-error result)) (tjob/track-transcription-job (assoc context :transcription-job result) opts' events))))))) (rf/reg-fx ::fetch-transcription! (fn [[{:keys [transcription-job]} {:keys [bucket-name] :as opts} {:keys [on-success on-error]}]] (let [bucket (aws/bucket-service opts) op-params #js{:Bucket bucket-name :Key (str (:TranscriptionJobName transcription-job) ".json")}] (aws/get-object bucket op-params (fn [err resp] (if (some? err) (rf/dispatch (conj on-error err)) (rf/dispatch (conj on-success resp))))))))
39496
(ns aws-transcribe-clj.transcribe.fx (:require [cljs.core.async :as a] [oops.core :refer [oget]] [re-frame.core :as rf] [aws-transcribe-clj.aws.sdk :as aws] [aws-transcribe-clj.common :as c] [aws-transcribe-clj.transcribe.fx.audio :as audio] [aws-transcribe-clj.transcribe.fx.transcription-job :as tjob])) (rf/reg-fx ::record-audio! (fn [[params {:keys [on-stop on-error] :as events}]] (let [output (a/chan)] (a/go (audio/record! (assoc params :output output) events) (let [result (a/<! output) event (if (instance? js/Error result) on-error on-stop)] (rf/dispatch (conj event result))))))) (rf/reg-fx ::upload! (fn [[{:keys [recording user-id]} {:keys [bucket-name] :as opts} {:keys [on-success on-error]}]] (let [file (:file recording) obj-key (str "<KEY> user-<KEY> "/" (oget file :name)) bucket (aws/bucket-service opts)] (aws/put-object bucket #js{:Key obj-key :ContentType (oget file :type) :Body file} (fn [err _] (if (some? err) (rf/dispatch (conj on-error err)) (rf/dispatch (conj on-success {:recording recording :s3-object {:object-key obj-key :bucket-name bucket-name}})))))))) (rf/reg-fx ::transcribe! (fn [[{:keys [recording user-id] :as context} {:keys [transcripts-bucket] :as opts} {:keys [on-error] :as events}]] (let [{:keys [object-key bucket-name]} (:s3-object recording) transcribe (aws/transcribe-service opts) watcher (a/chan) opts' (assoc opts :aws-transcribe transcribe :watcher watcher)] (a/go (aws/start-transcription-job transcribe #js{:TranscriptionJobName (str user-id "-" (:id recording)) :LanguageCode "en-US" :Media #js{:MediaFileUri (str "s3://" bucket-name "/" object-key)} :OutputBucketName transcripts-bucket} (tjob/start-transcription-job-callback context opts' events)) (let [result (a/<! watcher)] (if (c/js-error? result) (rf/dispatch (conj on-error result)) (tjob/track-transcription-job (assoc context :transcription-job result) opts' events))))))) (rf/reg-fx ::fetch-transcription! (fn [[{:keys [transcription-job]} {:keys [bucket-name] :as opts} {:keys [on-success on-error]}]] (let [bucket (aws/bucket-service opts) op-params #js{:Bucket bucket-name :Key (str (:TranscriptionJobName transcription-job) ".json")}] (aws/get-object bucket op-params (fn [err resp] (if (some? err) (rf/dispatch (conj on-error err)) (rf/dispatch (conj on-success resp))))))))
true
(ns aws-transcribe-clj.transcribe.fx (:require [cljs.core.async :as a] [oops.core :refer [oget]] [re-frame.core :as rf] [aws-transcribe-clj.aws.sdk :as aws] [aws-transcribe-clj.common :as c] [aws-transcribe-clj.transcribe.fx.audio :as audio] [aws-transcribe-clj.transcribe.fx.transcription-job :as tjob])) (rf/reg-fx ::record-audio! (fn [[params {:keys [on-stop on-error] :as events}]] (let [output (a/chan)] (a/go (audio/record! (assoc params :output output) events) (let [result (a/<! output) event (if (instance? js/Error result) on-error on-stop)] (rf/dispatch (conj event result))))))) (rf/reg-fx ::upload! (fn [[{:keys [recording user-id]} {:keys [bucket-name] :as opts} {:keys [on-success on-error]}]] (let [file (:file recording) obj-key (str "PI:KEY:<KEY>END_PI user-PI:KEY:<KEY>END_PI "/" (oget file :name)) bucket (aws/bucket-service opts)] (aws/put-object bucket #js{:Key obj-key :ContentType (oget file :type) :Body file} (fn [err _] (if (some? err) (rf/dispatch (conj on-error err)) (rf/dispatch (conj on-success {:recording recording :s3-object {:object-key obj-key :bucket-name bucket-name}})))))))) (rf/reg-fx ::transcribe! (fn [[{:keys [recording user-id] :as context} {:keys [transcripts-bucket] :as opts} {:keys [on-error] :as events}]] (let [{:keys [object-key bucket-name]} (:s3-object recording) transcribe (aws/transcribe-service opts) watcher (a/chan) opts' (assoc opts :aws-transcribe transcribe :watcher watcher)] (a/go (aws/start-transcription-job transcribe #js{:TranscriptionJobName (str user-id "-" (:id recording)) :LanguageCode "en-US" :Media #js{:MediaFileUri (str "s3://" bucket-name "/" object-key)} :OutputBucketName transcripts-bucket} (tjob/start-transcription-job-callback context opts' events)) (let [result (a/<! watcher)] (if (c/js-error? result) (rf/dispatch (conj on-error result)) (tjob/track-transcription-job (assoc context :transcription-job result) opts' events))))))) (rf/reg-fx ::fetch-transcription! (fn [[{:keys [transcription-job]} {:keys [bucket-name] :as opts} {:keys [on-success on-error]}]] (let [bucket (aws/bucket-service opts) op-params #js{:Bucket bucket-name :Key (str (:TranscriptionJobName transcription-job) ".json")}] (aws/get-object bucket op-params (fn [err resp] (if (some? err) (rf/dispatch (conj on-error err)) (rf/dispatch (conj on-success resp))))))))
[ { "context": "k combining blocking with CPU-bound tasks.\n;;;\n;;; Eli Bendersky [http://eli.thegreenplace.net]\n;;; This code is i", "end": 76, "score": 0.9981199502944946, "start": 63, "tag": "NAME", "value": "Eli Bendersky" } ]
2017/clojure-blocking-async/src/clojure_blocking_async/combine_cpubound_blocking.clj
mikiec84/code-for-blog
1,199
;;; Benchmark combining blocking with CPU-bound tasks. ;;; ;;; Eli Bendersky [http://eli.thegreenplace.net] ;;; This code is in the public domain. (ns clojure-blocking-async.combine-cpubound-blocking (:require [clojure.core.async :as async])) (defn factorize "Naive factorization function; takes an integer n and returns a vector of factors." [n] (if (< n 2) [] (loop [factors [] n n p 2] (cond (= n 1) factors (= 0 (mod n p)) (recur (conj factors p) (quot n p) p) (>= (* p p) n) (conj factors n) (> p 2) (recur factors n (+ p 2)) :else (recur factors n (+ p 1)))))) (defn receive-n "Receive n items from the given channel and return them as a vector." [c n] (loop [i 0 res []] (if (= i n) res (recur (inc i) (conj res (async/<!! c)))))) ;;; This number takes ~230 msec to factorize. (def mynum (* 1548587 982451653)) (defn launch-go-blocking-and-compute [nblock ncompute] (let [c (async/chan)] (dotimes [i nblock] (async/go (Thread/sleep 250) (async/>! c i))) (dotimes [i ncompute] (async/go (async/>! c (factorize mynum)))) (receive-n c (+ nblock ncompute)))) (defn launch-thread-blocking-and-compute [nblock ncompute] (let [c (async/chan)] (dotimes [i nblock] (async/thread (Thread/sleep 250) (async/>!! c i))) (dotimes [i ncompute] (async/thread (async/>!! c (factorize mynum)))) (receive-n c (+ nblock ncompute)))) ;;; The higher nblock goes, the slower the go-blocks version becomes; the ;;; runtime of the threaded version is proportonal mainly to the number of ;;; computes going in parallel. (def nblock 64) (def ncompute 16) (dotimes [_ 6] (println "go") (time (launch-go-blocking-and-compute nblock ncompute))) (dotimes [_ 6] (println "thread") (time (launch-thread-blocking-and-compute nblock ncompute)))
65854
;;; Benchmark combining blocking with CPU-bound tasks. ;;; ;;; <NAME> [http://eli.thegreenplace.net] ;;; This code is in the public domain. (ns clojure-blocking-async.combine-cpubound-blocking (:require [clojure.core.async :as async])) (defn factorize "Naive factorization function; takes an integer n and returns a vector of factors." [n] (if (< n 2) [] (loop [factors [] n n p 2] (cond (= n 1) factors (= 0 (mod n p)) (recur (conj factors p) (quot n p) p) (>= (* p p) n) (conj factors n) (> p 2) (recur factors n (+ p 2)) :else (recur factors n (+ p 1)))))) (defn receive-n "Receive n items from the given channel and return them as a vector." [c n] (loop [i 0 res []] (if (= i n) res (recur (inc i) (conj res (async/<!! c)))))) ;;; This number takes ~230 msec to factorize. (def mynum (* 1548587 982451653)) (defn launch-go-blocking-and-compute [nblock ncompute] (let [c (async/chan)] (dotimes [i nblock] (async/go (Thread/sleep 250) (async/>! c i))) (dotimes [i ncompute] (async/go (async/>! c (factorize mynum)))) (receive-n c (+ nblock ncompute)))) (defn launch-thread-blocking-and-compute [nblock ncompute] (let [c (async/chan)] (dotimes [i nblock] (async/thread (Thread/sleep 250) (async/>!! c i))) (dotimes [i ncompute] (async/thread (async/>!! c (factorize mynum)))) (receive-n c (+ nblock ncompute)))) ;;; The higher nblock goes, the slower the go-blocks version becomes; the ;;; runtime of the threaded version is proportonal mainly to the number of ;;; computes going in parallel. (def nblock 64) (def ncompute 16) (dotimes [_ 6] (println "go") (time (launch-go-blocking-and-compute nblock ncompute))) (dotimes [_ 6] (println "thread") (time (launch-thread-blocking-and-compute nblock ncompute)))
true
;;; Benchmark combining blocking with CPU-bound tasks. ;;; ;;; PI:NAME:<NAME>END_PI [http://eli.thegreenplace.net] ;;; This code is in the public domain. (ns clojure-blocking-async.combine-cpubound-blocking (:require [clojure.core.async :as async])) (defn factorize "Naive factorization function; takes an integer n and returns a vector of factors." [n] (if (< n 2) [] (loop [factors [] n n p 2] (cond (= n 1) factors (= 0 (mod n p)) (recur (conj factors p) (quot n p) p) (>= (* p p) n) (conj factors n) (> p 2) (recur factors n (+ p 2)) :else (recur factors n (+ p 1)))))) (defn receive-n "Receive n items from the given channel and return them as a vector." [c n] (loop [i 0 res []] (if (= i n) res (recur (inc i) (conj res (async/<!! c)))))) ;;; This number takes ~230 msec to factorize. (def mynum (* 1548587 982451653)) (defn launch-go-blocking-and-compute [nblock ncompute] (let [c (async/chan)] (dotimes [i nblock] (async/go (Thread/sleep 250) (async/>! c i))) (dotimes [i ncompute] (async/go (async/>! c (factorize mynum)))) (receive-n c (+ nblock ncompute)))) (defn launch-thread-blocking-and-compute [nblock ncompute] (let [c (async/chan)] (dotimes [i nblock] (async/thread (Thread/sleep 250) (async/>!! c i))) (dotimes [i ncompute] (async/thread (async/>!! c (factorize mynum)))) (receive-n c (+ nblock ncompute)))) ;;; The higher nblock goes, the slower the go-blocks version becomes; the ;;; runtime of the threaded version is proportonal mainly to the number of ;;; computes going in parallel. (def nblock 64) (def ncompute 16) (dotimes [_ 6] (println "go") (time (launch-go-blocking-and-compute nblock ncompute))) (dotimes [_ 6] (println "thread") (time (launch-thread-blocking-and-compute nblock ncompute)))
[ { "context": "! reconciler PersonList {:people [(make-person 1 \"Tony\")\n ", "end": 6251, "score": 0.9992513656616211, "start": 6247, "tag": "NAME", "value": "Tony" }, { "context": " (make-person 2 \"Sally\")\n ", "end": 6352, "score": 0.999722957611084, "start": 6347, "tag": "NAME", "value": "Sally" }, { "context": " (make-person 3 \"Allen\")\n ", "end": 6453, "score": 0.9995579719543457, "start": 6448, "tag": "NAME", "value": "Allen" }, { "context": " (make-person 4 \"Luna\")]})))\n", "end": 6553, "score": 0.9995465874671936, "start": 6549, "tag": "NAME", "value": "Luna" } ]
src/book/book/queries/union_example_2.cljs
d4hines/fulcro
0
(ns book.queries.union-example-2 (:require [fulcro.client.dom :as dom] [fulcro.client.primitives :as prim :refer [defsc]] [fulcro.client.cards :refer [defcard-fulcro]] [fulcro.client :as fc] [fulcro.client.routing :as r :refer [defrouter]] [fulcro.client.mutations :refer [defmutation]] [book.macros :refer [defexample]] [fulcro.ui.bootstrap3 :as b] [fulcro.ui.elements :as ele] [fulcro.ui.forms :as f])) (defn person-ident "Generate an ident from a person." [id-or-props] (if (map? id-or-props) [:person/by-id (:db/id id-or-props)] [:person/by-id id-or-props])) (declare PersonForm) (defmutation edit-person "Fulcro mutation: Edit the person with the given ID." [{:keys [id]}] (action [{:keys [state] :as env}] (swap! state (fn [s] (-> s ; change the route. This just points the routers via ident changes (r/update-routing-links {:handler :editor :route-params {:id id}}) ; make sure the form has form support installed (f/init-form PersonForm (person-ident id))))))) (defmutation cancel-edit "Fulcro mutation: Cancel an edit." [no-args-needed] (action [{:keys [state] :as env}] (let [ident-of-person-being-edited (r/current-route @state :listform-router)] (swap! state (fn [s] (-> s ; change the route (r/update-routing-links {:handler :people}) ; clear any edits on the person (this is non-recursive) (update-in ident-of-person-being-edited f/reset-entity))))))) (defmutation submit-person "Fulcro mutation: An example of a custom form submit, composing other operations into the submit." [{:keys [form]}] ; form is passed in from UI to close over it. See dev guide for why. (action [{:keys [state]}] (let [ident-of-person-being-edited (r/current-route @state :listform-router)] (swap! state (fn [s] (-> s ; non-recursive. if using subforms see dev guide (update-in ident-of-person-being-edited f/commit-state) (r/update-routing-links {:handler :people}))))))) (defn make-person [id n] {:db/id id :person/name n}) (defsc PersonForm [this {:keys [db/id person/name] :as form-props}] {:ident (fn [] (person-ident form-props)) :query [:db/id :person/name f/form-key f/form-root-key] :protocols [static f/IForm (form-spec [this] [(f/id-field :db/id) (f/text-input :person/name)])]} (b/form-horizontal nil (b/labeled-input {:split 4 :input-generator (fn [_] (f/form-field this form-props :person/name))} "Name:") (b/labeled-input {:split 4 :input-generator (fn [_] (dom/div nil ; the follow-on read of :root/router ensures re-render from the router level (b/button {:onClick #(prim/transact! this `[(cancel-edit {}) :root/router])} "Cancel") (b/button {:onClick #(prim/transact! this `[(submit-person {:form form-props}) :root/router])} "Save")))} ""))) (defsc PersonListItem [this {:keys [db/id person/name] :as props}] {:ident (fn [] (person-ident props)) :query [:db/id :person/name]} ; the follow-on read of :root/router ensures re-render from the router level (dom/li #js {:onClick #(prim/transact! this `[(edit-person {:id ~id}) :root/router])} (dom/a #js {:href "javascript:void(0)"} name))) (def ui-person (prim/factory PersonListItem {:keyfn :db/id})) (def person-list-ident [:person-list/table :singleton]) (defsc PersonList [this {:keys [people]}] {:initial-state (fn [p] {:people []}) :query [{:people (prim/get-query PersonListItem)}] :ident (fn [] person-list-ident)} (dom/div nil (dom/h4 nil "People") (dom/ul nil (map (fn [i] (ui-person i)) people)))) (defrouter PersonListOrForm :listform-router (ident [this props] (if (contains? props :people) person-list-ident (person-ident props))) ; if the router points to a person list entity, render with a PersonList. This is the default route. :person-list/table PersonList ; if the router points to a person entity, render with PersonForm :person/by-id PersonForm) (def ui-person-list-or-form (prim/factory PersonListOrForm)) (defsc Root [this {:keys [ui/react-key root/router] :as props}] {:query [:ui/react-key {:root/router (prim/get-query PersonListOrForm)}] :initial-state (fn [p] (merge ; This data is used by the `update-routing-links` functions to switch routes (union idents on the router's current route) (r/routing-tree ; switch to the person list (r/make-route :people [(r/router-instruction :listform-router person-list-ident)]) ; switch to the given person (id is passed to update-routing-links and become :param/id) (r/make-route :editor [(r/router-instruction :listform-router (person-ident :param/id))])) {:root/router (prim/get-initial-state PersonListOrForm nil)}))} ; embed in iframe so we can use bootstrap css easily (ele/ui-iframe {:frameBorder 0 :height "300px" :width "100%"} (dom/div #js {:key react-key} (dom/style nil ".boxed {border: 1px solid black}") (dom/link #js {:rel "stylesheet" :href "bootstrap-3.3.7/css/bootstrap.min.css"}) (b/container-fluid {} (ui-person-list-or-form router))))) (defexample "Unions as View/Edit Routers" Root "union-example-2" :started-callback (fn [{:keys [reconciler]}] ; simulate a load of people via a simple integration of some tree data (prim/merge-component! reconciler PersonList {:people [(make-person 1 "Tony") (make-person 2 "Sally") (make-person 3 "Allen") (make-person 4 "Luna")]})))
124806
(ns book.queries.union-example-2 (:require [fulcro.client.dom :as dom] [fulcro.client.primitives :as prim :refer [defsc]] [fulcro.client.cards :refer [defcard-fulcro]] [fulcro.client :as fc] [fulcro.client.routing :as r :refer [defrouter]] [fulcro.client.mutations :refer [defmutation]] [book.macros :refer [defexample]] [fulcro.ui.bootstrap3 :as b] [fulcro.ui.elements :as ele] [fulcro.ui.forms :as f])) (defn person-ident "Generate an ident from a person." [id-or-props] (if (map? id-or-props) [:person/by-id (:db/id id-or-props)] [:person/by-id id-or-props])) (declare PersonForm) (defmutation edit-person "Fulcro mutation: Edit the person with the given ID." [{:keys [id]}] (action [{:keys [state] :as env}] (swap! state (fn [s] (-> s ; change the route. This just points the routers via ident changes (r/update-routing-links {:handler :editor :route-params {:id id}}) ; make sure the form has form support installed (f/init-form PersonForm (person-ident id))))))) (defmutation cancel-edit "Fulcro mutation: Cancel an edit." [no-args-needed] (action [{:keys [state] :as env}] (let [ident-of-person-being-edited (r/current-route @state :listform-router)] (swap! state (fn [s] (-> s ; change the route (r/update-routing-links {:handler :people}) ; clear any edits on the person (this is non-recursive) (update-in ident-of-person-being-edited f/reset-entity))))))) (defmutation submit-person "Fulcro mutation: An example of a custom form submit, composing other operations into the submit." [{:keys [form]}] ; form is passed in from UI to close over it. See dev guide for why. (action [{:keys [state]}] (let [ident-of-person-being-edited (r/current-route @state :listform-router)] (swap! state (fn [s] (-> s ; non-recursive. if using subforms see dev guide (update-in ident-of-person-being-edited f/commit-state) (r/update-routing-links {:handler :people}))))))) (defn make-person [id n] {:db/id id :person/name n}) (defsc PersonForm [this {:keys [db/id person/name] :as form-props}] {:ident (fn [] (person-ident form-props)) :query [:db/id :person/name f/form-key f/form-root-key] :protocols [static f/IForm (form-spec [this] [(f/id-field :db/id) (f/text-input :person/name)])]} (b/form-horizontal nil (b/labeled-input {:split 4 :input-generator (fn [_] (f/form-field this form-props :person/name))} "Name:") (b/labeled-input {:split 4 :input-generator (fn [_] (dom/div nil ; the follow-on read of :root/router ensures re-render from the router level (b/button {:onClick #(prim/transact! this `[(cancel-edit {}) :root/router])} "Cancel") (b/button {:onClick #(prim/transact! this `[(submit-person {:form form-props}) :root/router])} "Save")))} ""))) (defsc PersonListItem [this {:keys [db/id person/name] :as props}] {:ident (fn [] (person-ident props)) :query [:db/id :person/name]} ; the follow-on read of :root/router ensures re-render from the router level (dom/li #js {:onClick #(prim/transact! this `[(edit-person {:id ~id}) :root/router])} (dom/a #js {:href "javascript:void(0)"} name))) (def ui-person (prim/factory PersonListItem {:keyfn :db/id})) (def person-list-ident [:person-list/table :singleton]) (defsc PersonList [this {:keys [people]}] {:initial-state (fn [p] {:people []}) :query [{:people (prim/get-query PersonListItem)}] :ident (fn [] person-list-ident)} (dom/div nil (dom/h4 nil "People") (dom/ul nil (map (fn [i] (ui-person i)) people)))) (defrouter PersonListOrForm :listform-router (ident [this props] (if (contains? props :people) person-list-ident (person-ident props))) ; if the router points to a person list entity, render with a PersonList. This is the default route. :person-list/table PersonList ; if the router points to a person entity, render with PersonForm :person/by-id PersonForm) (def ui-person-list-or-form (prim/factory PersonListOrForm)) (defsc Root [this {:keys [ui/react-key root/router] :as props}] {:query [:ui/react-key {:root/router (prim/get-query PersonListOrForm)}] :initial-state (fn [p] (merge ; This data is used by the `update-routing-links` functions to switch routes (union idents on the router's current route) (r/routing-tree ; switch to the person list (r/make-route :people [(r/router-instruction :listform-router person-list-ident)]) ; switch to the given person (id is passed to update-routing-links and become :param/id) (r/make-route :editor [(r/router-instruction :listform-router (person-ident :param/id))])) {:root/router (prim/get-initial-state PersonListOrForm nil)}))} ; embed in iframe so we can use bootstrap css easily (ele/ui-iframe {:frameBorder 0 :height "300px" :width "100%"} (dom/div #js {:key react-key} (dom/style nil ".boxed {border: 1px solid black}") (dom/link #js {:rel "stylesheet" :href "bootstrap-3.3.7/css/bootstrap.min.css"}) (b/container-fluid {} (ui-person-list-or-form router))))) (defexample "Unions as View/Edit Routers" Root "union-example-2" :started-callback (fn [{:keys [reconciler]}] ; simulate a load of people via a simple integration of some tree data (prim/merge-component! reconciler PersonList {:people [(make-person 1 "<NAME>") (make-person 2 "<NAME>") (make-person 3 "<NAME>") (make-person 4 "<NAME>")]})))
true
(ns book.queries.union-example-2 (:require [fulcro.client.dom :as dom] [fulcro.client.primitives :as prim :refer [defsc]] [fulcro.client.cards :refer [defcard-fulcro]] [fulcro.client :as fc] [fulcro.client.routing :as r :refer [defrouter]] [fulcro.client.mutations :refer [defmutation]] [book.macros :refer [defexample]] [fulcro.ui.bootstrap3 :as b] [fulcro.ui.elements :as ele] [fulcro.ui.forms :as f])) (defn person-ident "Generate an ident from a person." [id-or-props] (if (map? id-or-props) [:person/by-id (:db/id id-or-props)] [:person/by-id id-or-props])) (declare PersonForm) (defmutation edit-person "Fulcro mutation: Edit the person with the given ID." [{:keys [id]}] (action [{:keys [state] :as env}] (swap! state (fn [s] (-> s ; change the route. This just points the routers via ident changes (r/update-routing-links {:handler :editor :route-params {:id id}}) ; make sure the form has form support installed (f/init-form PersonForm (person-ident id))))))) (defmutation cancel-edit "Fulcro mutation: Cancel an edit." [no-args-needed] (action [{:keys [state] :as env}] (let [ident-of-person-being-edited (r/current-route @state :listform-router)] (swap! state (fn [s] (-> s ; change the route (r/update-routing-links {:handler :people}) ; clear any edits on the person (this is non-recursive) (update-in ident-of-person-being-edited f/reset-entity))))))) (defmutation submit-person "Fulcro mutation: An example of a custom form submit, composing other operations into the submit." [{:keys [form]}] ; form is passed in from UI to close over it. See dev guide for why. (action [{:keys [state]}] (let [ident-of-person-being-edited (r/current-route @state :listform-router)] (swap! state (fn [s] (-> s ; non-recursive. if using subforms see dev guide (update-in ident-of-person-being-edited f/commit-state) (r/update-routing-links {:handler :people}))))))) (defn make-person [id n] {:db/id id :person/name n}) (defsc PersonForm [this {:keys [db/id person/name] :as form-props}] {:ident (fn [] (person-ident form-props)) :query [:db/id :person/name f/form-key f/form-root-key] :protocols [static f/IForm (form-spec [this] [(f/id-field :db/id) (f/text-input :person/name)])]} (b/form-horizontal nil (b/labeled-input {:split 4 :input-generator (fn [_] (f/form-field this form-props :person/name))} "Name:") (b/labeled-input {:split 4 :input-generator (fn [_] (dom/div nil ; the follow-on read of :root/router ensures re-render from the router level (b/button {:onClick #(prim/transact! this `[(cancel-edit {}) :root/router])} "Cancel") (b/button {:onClick #(prim/transact! this `[(submit-person {:form form-props}) :root/router])} "Save")))} ""))) (defsc PersonListItem [this {:keys [db/id person/name] :as props}] {:ident (fn [] (person-ident props)) :query [:db/id :person/name]} ; the follow-on read of :root/router ensures re-render from the router level (dom/li #js {:onClick #(prim/transact! this `[(edit-person {:id ~id}) :root/router])} (dom/a #js {:href "javascript:void(0)"} name))) (def ui-person (prim/factory PersonListItem {:keyfn :db/id})) (def person-list-ident [:person-list/table :singleton]) (defsc PersonList [this {:keys [people]}] {:initial-state (fn [p] {:people []}) :query [{:people (prim/get-query PersonListItem)}] :ident (fn [] person-list-ident)} (dom/div nil (dom/h4 nil "People") (dom/ul nil (map (fn [i] (ui-person i)) people)))) (defrouter PersonListOrForm :listform-router (ident [this props] (if (contains? props :people) person-list-ident (person-ident props))) ; if the router points to a person list entity, render with a PersonList. This is the default route. :person-list/table PersonList ; if the router points to a person entity, render with PersonForm :person/by-id PersonForm) (def ui-person-list-or-form (prim/factory PersonListOrForm)) (defsc Root [this {:keys [ui/react-key root/router] :as props}] {:query [:ui/react-key {:root/router (prim/get-query PersonListOrForm)}] :initial-state (fn [p] (merge ; This data is used by the `update-routing-links` functions to switch routes (union idents on the router's current route) (r/routing-tree ; switch to the person list (r/make-route :people [(r/router-instruction :listform-router person-list-ident)]) ; switch to the given person (id is passed to update-routing-links and become :param/id) (r/make-route :editor [(r/router-instruction :listform-router (person-ident :param/id))])) {:root/router (prim/get-initial-state PersonListOrForm nil)}))} ; embed in iframe so we can use bootstrap css easily (ele/ui-iframe {:frameBorder 0 :height "300px" :width "100%"} (dom/div #js {:key react-key} (dom/style nil ".boxed {border: 1px solid black}") (dom/link #js {:rel "stylesheet" :href "bootstrap-3.3.7/css/bootstrap.min.css"}) (b/container-fluid {} (ui-person-list-or-form router))))) (defexample "Unions as View/Edit Routers" Root "union-example-2" :started-callback (fn [{:keys [reconciler]}] ; simulate a load of people via a simple integration of some tree data (prim/merge-component! reconciler PersonList {:people [(make-person 1 "PI:NAME:<NAME>END_PI") (make-person 2 "PI:NAME:<NAME>END_PI") (make-person 3 "PI:NAME:<NAME>END_PI") (make-person 4 "PI:NAME:<NAME>END_PI")]})))
[ { "context": ";; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020\n;;\n;; Permission is", "end": 29, "score": 0.9998453259468079, "start": 13, "tag": "NAME", "value": "Fabian Schneider" }, { "context": ";; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020\n;;\n;; Permission is hereby granted, f", "end": 47, "score": 0.9998385310173035, "start": 34, "tag": "NAME", "value": "Gunnar Völkel" } ]
src/traqbio/db/migrate.clj
sysbio-bioinf/iBioTraq
2
;; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020 ;; ;; 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 traqbio.db.migrate (:require [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [traqbio.config :as c] [traqbio.db.init :as init] [traqbio.db.crud :as crud])) (defn table-set [db-conn] (set (jdbc/query db-conn ["SELECT name FROM sqlite_master WHERE type='table'"] {:row-fn (comp keyword :name)}))) (defn table-columns [db-conn, table] (jdbc/query db-conn [(format "PRAGMA table_info(%s)" (name table))] {:row-fn (comp keyword :name), :result-set-fn vec})) (defn db-data [db-conn] (let [tables (table-set db-conn)] (persistent! (reduce (fn [table-data-map, table] (cond-> table-data-map (contains? tables table) (assoc! table (vec (jdbc/query db-conn [(format "SELECT * FROM %s" (name table))]))))) (transient {}) [:project, :projectstep :template :templatestep :customer :projectcustomer :user :usernotification :passwordreset :actionlog])))) (defn db-connection [db-filename] (c/pool (c/database-config db-filename))) (defn export-data [db-filename, export-filename] (let [data (db-data (db-connection db-filename))] (with-open [w (io/writer export-filename)] (binding [*out* w] (prn data))))) (defn export-templates [db-filename, export-filename] (let [templates-vec (do (c/update-db-name db-filename) (reduce (fn [result-vec, {:keys [id]}] (conj result-vec (-> id crud/read-template (select-keys [:name, :description, :templatesteps]) (update-in [:templatesteps] (partial mapv #(select-keys % [:type, :description])))))) [] (crud/read-templates)))] (with-open [w (io/writer export-filename)] (binding [*out* w] (prn templates-vec))))) (defn insert-table-data [db-conn, table-data-map] (reduce-kv (fn [_, table, rows] (let [table-cols (table-columns db-conn, table)] (reduce (fn [_, row-data] (jdbc/insert! db-conn, table, (select-keys row-data table-cols)) nil) nil rows))) nil table-data-map)) (defn customer-in-project? [table-data-map] (let [imported-project-columns (->> table-data-map :project (mapcat keys) set)] (contains? imported-project-columns :customername))) (defn customer-project-id-map [table-data-map] (reduce (fn [m, {:keys [customername, customeremail, id]}] (let [customer (crud/normalize-customer-data {:name customername :email customeremail})] (update-in m [customer] (fnil conj []) id))) {} (:project table-data-map))) (defn create-customers-and-mapping [db-conn, customer-project-map] (let [customers (keys customer-project-map), customer-id-map (zipmap customers (crud/maybe-add-customers db-conn, customers))] (reduce-kv (fn [_, customer, customer-id] (let [projects (get customer-project-map customer)] (doseq [project-id projects] (jdbc/insert! db-conn :projectcustomer {:projectid project-id, :customerid customer-id, :sequence 0}))) nil) nil customer-id-map))) (defn create-customer-table-if-needed [db-conn, table-data-map] (when (customer-in-project? table-data-map) (let [customer-project-map (customer-project-id-map table-data-map)] (jdbc/with-db-transaction [t-conn db-conn] (create-customers-and-mapping t-conn, customer-project-map))))) (defn import-data [db-filename, import-filename] (let [table-data-map (read (java.io.PushbackReader. (io/reader import-filename)))] (init/create-database-if-needed db-filename) (let [db-conn (db-connection db-filename)] (insert-table-data db-conn, table-data-map) (create-customer-table-if-needed db-conn, table-data-map) nil)))
75829
;; Copyright <NAME> and <NAME> © 2014-2020 ;; ;; 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 traqbio.db.migrate (:require [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [traqbio.config :as c] [traqbio.db.init :as init] [traqbio.db.crud :as crud])) (defn table-set [db-conn] (set (jdbc/query db-conn ["SELECT name FROM sqlite_master WHERE type='table'"] {:row-fn (comp keyword :name)}))) (defn table-columns [db-conn, table] (jdbc/query db-conn [(format "PRAGMA table_info(%s)" (name table))] {:row-fn (comp keyword :name), :result-set-fn vec})) (defn db-data [db-conn] (let [tables (table-set db-conn)] (persistent! (reduce (fn [table-data-map, table] (cond-> table-data-map (contains? tables table) (assoc! table (vec (jdbc/query db-conn [(format "SELECT * FROM %s" (name table))]))))) (transient {}) [:project, :projectstep :template :templatestep :customer :projectcustomer :user :usernotification :passwordreset :actionlog])))) (defn db-connection [db-filename] (c/pool (c/database-config db-filename))) (defn export-data [db-filename, export-filename] (let [data (db-data (db-connection db-filename))] (with-open [w (io/writer export-filename)] (binding [*out* w] (prn data))))) (defn export-templates [db-filename, export-filename] (let [templates-vec (do (c/update-db-name db-filename) (reduce (fn [result-vec, {:keys [id]}] (conj result-vec (-> id crud/read-template (select-keys [:name, :description, :templatesteps]) (update-in [:templatesteps] (partial mapv #(select-keys % [:type, :description])))))) [] (crud/read-templates)))] (with-open [w (io/writer export-filename)] (binding [*out* w] (prn templates-vec))))) (defn insert-table-data [db-conn, table-data-map] (reduce-kv (fn [_, table, rows] (let [table-cols (table-columns db-conn, table)] (reduce (fn [_, row-data] (jdbc/insert! db-conn, table, (select-keys row-data table-cols)) nil) nil rows))) nil table-data-map)) (defn customer-in-project? [table-data-map] (let [imported-project-columns (->> table-data-map :project (mapcat keys) set)] (contains? imported-project-columns :customername))) (defn customer-project-id-map [table-data-map] (reduce (fn [m, {:keys [customername, customeremail, id]}] (let [customer (crud/normalize-customer-data {:name customername :email customeremail})] (update-in m [customer] (fnil conj []) id))) {} (:project table-data-map))) (defn create-customers-and-mapping [db-conn, customer-project-map] (let [customers (keys customer-project-map), customer-id-map (zipmap customers (crud/maybe-add-customers db-conn, customers))] (reduce-kv (fn [_, customer, customer-id] (let [projects (get customer-project-map customer)] (doseq [project-id projects] (jdbc/insert! db-conn :projectcustomer {:projectid project-id, :customerid customer-id, :sequence 0}))) nil) nil customer-id-map))) (defn create-customer-table-if-needed [db-conn, table-data-map] (when (customer-in-project? table-data-map) (let [customer-project-map (customer-project-id-map table-data-map)] (jdbc/with-db-transaction [t-conn db-conn] (create-customers-and-mapping t-conn, customer-project-map))))) (defn import-data [db-filename, import-filename] (let [table-data-map (read (java.io.PushbackReader. (io/reader import-filename)))] (init/create-database-if-needed db-filename) (let [db-conn (db-connection db-filename)] (insert-table-data db-conn, table-data-map) (create-customer-table-if-needed db-conn, table-data-map) nil)))
true
;; Copyright PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI © 2014-2020 ;; ;; 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 traqbio.db.migrate (:require [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [traqbio.config :as c] [traqbio.db.init :as init] [traqbio.db.crud :as crud])) (defn table-set [db-conn] (set (jdbc/query db-conn ["SELECT name FROM sqlite_master WHERE type='table'"] {:row-fn (comp keyword :name)}))) (defn table-columns [db-conn, table] (jdbc/query db-conn [(format "PRAGMA table_info(%s)" (name table))] {:row-fn (comp keyword :name), :result-set-fn vec})) (defn db-data [db-conn] (let [tables (table-set db-conn)] (persistent! (reduce (fn [table-data-map, table] (cond-> table-data-map (contains? tables table) (assoc! table (vec (jdbc/query db-conn [(format "SELECT * FROM %s" (name table))]))))) (transient {}) [:project, :projectstep :template :templatestep :customer :projectcustomer :user :usernotification :passwordreset :actionlog])))) (defn db-connection [db-filename] (c/pool (c/database-config db-filename))) (defn export-data [db-filename, export-filename] (let [data (db-data (db-connection db-filename))] (with-open [w (io/writer export-filename)] (binding [*out* w] (prn data))))) (defn export-templates [db-filename, export-filename] (let [templates-vec (do (c/update-db-name db-filename) (reduce (fn [result-vec, {:keys [id]}] (conj result-vec (-> id crud/read-template (select-keys [:name, :description, :templatesteps]) (update-in [:templatesteps] (partial mapv #(select-keys % [:type, :description])))))) [] (crud/read-templates)))] (with-open [w (io/writer export-filename)] (binding [*out* w] (prn templates-vec))))) (defn insert-table-data [db-conn, table-data-map] (reduce-kv (fn [_, table, rows] (let [table-cols (table-columns db-conn, table)] (reduce (fn [_, row-data] (jdbc/insert! db-conn, table, (select-keys row-data table-cols)) nil) nil rows))) nil table-data-map)) (defn customer-in-project? [table-data-map] (let [imported-project-columns (->> table-data-map :project (mapcat keys) set)] (contains? imported-project-columns :customername))) (defn customer-project-id-map [table-data-map] (reduce (fn [m, {:keys [customername, customeremail, id]}] (let [customer (crud/normalize-customer-data {:name customername :email customeremail})] (update-in m [customer] (fnil conj []) id))) {} (:project table-data-map))) (defn create-customers-and-mapping [db-conn, customer-project-map] (let [customers (keys customer-project-map), customer-id-map (zipmap customers (crud/maybe-add-customers db-conn, customers))] (reduce-kv (fn [_, customer, customer-id] (let [projects (get customer-project-map customer)] (doseq [project-id projects] (jdbc/insert! db-conn :projectcustomer {:projectid project-id, :customerid customer-id, :sequence 0}))) nil) nil customer-id-map))) (defn create-customer-table-if-needed [db-conn, table-data-map] (when (customer-in-project? table-data-map) (let [customer-project-map (customer-project-id-map table-data-map)] (jdbc/with-db-transaction [t-conn db-conn] (create-customers-and-mapping t-conn, customer-project-map))))) (defn import-data [db-filename, import-filename] (let [table-data-map (read (java.io.PushbackReader. (io/reader import-filename)))] (init/create-database-if-needed db-filename) (let [db-conn (db-connection db-filename)] (insert-table-data db-conn, table-data-map) (create-customer-table-if-needed db-conn, table-data-map) nil)))
[ { "context": "st.\"\n (let [m1 {\"key\" \"foo\"\n \"key2\" [\"bar\" \"baz\"]}\n m2 {\"key\" [\"cake\" \"salad\"]}]\n ", "end": 597, "score": 0.9658682942390442, "start": 594, "tag": "KEY", "value": "bar" }, { "context": " (let [m1 {\"key\" \"foo\"\n \"key2\" [\"bar\" \"baz\"]}\n m2 {\"key\" [\"cake\" \"salad\"]}]\n (conf", "end": 603, "score": 0.9853397607803345, "start": 600, "tag": "KEY", "value": "baz" }, { "context": " \"key2\" [\"bar\" \"baz\"]}\n m2 {\"key\" [\"cake\" \"salad\"]}]\n (conf-merge m1) => {\"key\" \"foo", "end": 631, "score": 0.5575537085533142, "start": 627, "tag": "KEY", "value": "cake" }, { "context": " \"key2\" [\"bar\" \"baz\"]}\n m2 {\"key\" [\"cake\" \"salad\"]}]\n (conf-merge m1) => {\"key\" \"foo\", \"key2", "end": 639, "score": 0.8761916160583496, "start": 634, "tag": "KEY", "value": "salad" }, { "context": "]\n (conf-merge m1) => {\"key\" \"foo\", \"key2\" \"bar,baz\"}\n (conf-merge m1 m2) => {\"key\" \"cake,salad\", ", "end": 699, "score": 0.9382421374320984, "start": 692, "tag": "KEY", "value": "bar,baz" }, { "context": "ey2\" \"bar,baz\"}\n (conf-merge m1 m2) => {\"key\" \"cake,salad\", \"key2\" \"bar,baz\"}))\n\n(fact \"Stringify tes", "end": 740, "score": 0.9024710059165955, "start": 736, "tag": "KEY", "value": "cake" }, { "context": "\"bar,baz\"}\n (conf-merge m1 m2) => {\"key\" \"cake,salad\", \"key2\" \"bar,baz\"}))\n\n(fact \"Stringify test.\"\n ", "end": 746, "score": 0.9817610383033752, "start": 741, "tag": "KEY", "value": "salad" }, { "context": "conf-merge m1 m2) => {\"key\" \"cake,salad\", \"key2\" \"bar,baz\"}))\n\n(fact \"Stringify test.\"\n (stringify-keys\n ", "end": 764, "score": 0.958275556564331, "start": 757, "tag": "KEY", "value": "bar,baz" } ]
test/cascalog/util_test.clj
Factual/cascalog
1
(ns cascalog.util-test (:use cascalog.util midje.sweet)) (tabular (fact "test-all-pairs" (all-pairs ?input) => ?result) ?input ?result [1] [] [1 2 3] [[1 2] [1 3] [2 3]] [1 :a :a 2] [[1 :a] [1 :a] [1 2] [:a :a] [:a 2] [:a 2]]) (facts "count= tests." (count= [1] []) => false (count= [1] [1] [3]) => true (count= [1 2] [4 3]) => true (not-count= [1] []) => true (not-count= [1 2] [3 4] []) => true (not-count= [1] [1]) => false (not-count= [1 2] [4 3]) => false) (fact "Conf-merging test." (let [m1 {"key" "foo" "key2" ["bar" "baz"]} m2 {"key" ["cake" "salad"]}] (conf-merge m1) => {"key" "foo", "key2" "bar,baz"} (conf-merge m1 m2) => {"key" "cake,salad", "key2" "bar,baz"})) (fact "Stringify test." (stringify-keys {:key "val" "key2" "val2"}) => {"key" "val" "key2" "val2"}) (future-fact "Test that stringify-keys can handle clashes between, say, \"key\" and :key.")
36800
(ns cascalog.util-test (:use cascalog.util midje.sweet)) (tabular (fact "test-all-pairs" (all-pairs ?input) => ?result) ?input ?result [1] [] [1 2 3] [[1 2] [1 3] [2 3]] [1 :a :a 2] [[1 :a] [1 :a] [1 2] [:a :a] [:a 2] [:a 2]]) (facts "count= tests." (count= [1] []) => false (count= [1] [1] [3]) => true (count= [1 2] [4 3]) => true (not-count= [1] []) => true (not-count= [1 2] [3 4] []) => true (not-count= [1] [1]) => false (not-count= [1 2] [4 3]) => false) (fact "Conf-merging test." (let [m1 {"key" "foo" "key2" ["<KEY>" "<KEY>"]} m2 {"key" ["<KEY>" "<KEY>"]}] (conf-merge m1) => {"key" "foo", "key2" "<KEY>"} (conf-merge m1 m2) => {"key" "<KEY>,<KEY>", "key2" "<KEY>"})) (fact "Stringify test." (stringify-keys {:key "val" "key2" "val2"}) => {"key" "val" "key2" "val2"}) (future-fact "Test that stringify-keys can handle clashes between, say, \"key\" and :key.")
true
(ns cascalog.util-test (:use cascalog.util midje.sweet)) (tabular (fact "test-all-pairs" (all-pairs ?input) => ?result) ?input ?result [1] [] [1 2 3] [[1 2] [1 3] [2 3]] [1 :a :a 2] [[1 :a] [1 :a] [1 2] [:a :a] [:a 2] [:a 2]]) (facts "count= tests." (count= [1] []) => false (count= [1] [1] [3]) => true (count= [1 2] [4 3]) => true (not-count= [1] []) => true (not-count= [1 2] [3 4] []) => true (not-count= [1] [1]) => false (not-count= [1 2] [4 3]) => false) (fact "Conf-merging test." (let [m1 {"key" "foo" "key2" ["PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI"]} m2 {"key" ["PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI"]}] (conf-merge m1) => {"key" "foo", "key2" "PI:KEY:<KEY>END_PI"} (conf-merge m1 m2) => {"key" "PI:KEY:<KEY>END_PI,PI:KEY:<KEY>END_PI", "key2" "PI:KEY:<KEY>END_PI"})) (fact "Stringify test." (stringify-keys {:key "val" "key2" "val2"}) => {"key" "val" "key2" "val2"}) (future-fact "Test that stringify-keys can handle clashes between, say, \"key\" and :key.")
[ { "context": " :as vigenere]))\n\n(let\n [ plaintext \"Beware the Jabberwock, my son! The jaws that bite, the claws that catc", "end": 146, "score": 0.5688865184783936, "start": 137, "tag": "NAME", "value": "abberwock" }, { "context": " that bite, the claws that catch!\"\n key \"Vigenere cipher\"\n ciphertext (vigenere/encrypt plaintext key)\n", "end": 230, "score": 0.9976562261581421, "start": 215, "tag": "KEY", "value": "Vigenere cipher" } ]
Task/Vigen-re-cipher/Clojure/vigen-re-cipher-2.clj
mullikine/RosettaCodeData
1
(ns org.rosettacode.clojure.test-vigenere (:require [org.rosettacode.clojure.vigenere :as vigenere])) (let [ plaintext "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" key "Vigenere cipher" ciphertext (vigenere/encrypt plaintext key) recovered (vigenere/decrypt ciphertext key) ] (doall (map (fn [[k v]] (printf "%9s: %s\n" k v)) [ ["Original" plaintext] ["Key" key] ["Encrypted" ciphertext] ["Decrypted" recovered] ])))
87260
(ns org.rosettacode.clojure.test-vigenere (:require [org.rosettacode.clojure.vigenere :as vigenere])) (let [ plaintext "Beware the J<NAME>, my son! The jaws that bite, the claws that catch!" key "<KEY>" ciphertext (vigenere/encrypt plaintext key) recovered (vigenere/decrypt ciphertext key) ] (doall (map (fn [[k v]] (printf "%9s: %s\n" k v)) [ ["Original" plaintext] ["Key" key] ["Encrypted" ciphertext] ["Decrypted" recovered] ])))
true
(ns org.rosettacode.clojure.test-vigenere (:require [org.rosettacode.clojure.vigenere :as vigenere])) (let [ plaintext "Beware the JPI:NAME:<NAME>END_PI, my son! The jaws that bite, the claws that catch!" key "PI:KEY:<KEY>END_PI" ciphertext (vigenere/encrypt plaintext key) recovered (vigenere/decrypt ciphertext key) ] (doall (map (fn [[k v]] (printf "%9s: %s\n" k v)) [ ["Original" plaintext] ["Key" key] ["Encrypted" ciphertext] ["Decrypted" recovered] ])))
[ { "context": "me\n :password encrypted-password})]\n (first found-users)))\n\n", "end": 214, "score": 0.97108393907547, "start": 196, "tag": "PASSWORD", "value": "encrypted-password" } ]
langs/clojure/clojure-in-action/ch02/check-login.clj
danielgrigg/sandbox
1
(defn check-login [username password] (let [encrypted-password (encrypt-string password) found-users (find-records {:login username :password encrypted-password})] (first found-users)))
118824
(defn check-login [username password] (let [encrypted-password (encrypt-string password) found-users (find-records {:login username :password <PASSWORD>})] (first found-users)))
true
(defn check-login [username password] (let [encrypted-password (encrypt-string password) found-users (find-records {:login username :password PI:PASSWORD:<PASSWORD>END_PI})] (first found-users)))
[ { "context": ";; Copyright Copyright © 2017 Colin Smith. MIT License.\n\n(ns algebra.polynomial\n (:import ", "end": 41, "score": 0.9998366832733154, "start": 30, "tag": "NAME", "value": "Colin Smith" } ]
src/algebra/polynomial.clj
littleredcomputer/algebra
6
;; Copyright Copyright © 2017 Colin Smith. MIT License. (ns algebra.polynomial (:import (clojure.lang BigInt Ratio)) (:require [algebra :as a] [clojure.set :as set] [clojure.string :as string])) (def coefficient second) (def exponents first) ;; Monomials ;; ;; We represent a monomial as a vector of integers representing ;; the exponents of the indeterminates over some ring. For example; ;; we would represent x^2 as [2], and xy^2 as [1 2], though the ;; indeterminates have no name. Polynomials are linear combinations ;; of the monomials. When these are formed, it is important that the ;; monomial vectors all contain the same number of slots, so that ;; 3x + 2y^2 would be represented as: 3*[1 0] + 2*[0 2]. (defn ^:private monomial-degree "Compute the degree of a monomial. This is just the sum of the exponents." [m] (reduce + m)) ;; Monomial Orderings ;; ;; These orderings are in the sense of Java: x.compareTo(y), so that ;; this returns >0 if x > y, <0 if x < y, and ==0 if x = y. (defn lex-order "Lex order for monomials considers the power of x, then the power of y, etc." [xs ys] {:pre (= (count xs) (count ys))} (compare xs ys)) (defn graded-lex-order "" [xs ys] {:pre (= (count xs) (count ys))} (let [xd (monomial-degree xs) yd (monomial-degree ys)] (if (= xd yd) (lex-order xs ys) (- xd yd)))) (defn graded-reverse-lex-order "" [xs ys] {:pre (= (count xs) (count ys))} (let [xd (monomial-degree xs) yd (monomial-degree ys)] (if (= xd yd) (compare (vec (rseq ys)) (vec (rseq xs))) (- xd yd)))) (def ^:private monomial-order graded-lex-order) (def ^:private empty-coefficients []) ;; ;; Polynomials ;; (defprotocol IPolynomial (degree [this]) (coef [this exponents]) (evaluate [this args]) (fmap [this S f])) (defrecord Polynomial [ring arity terms] IPolynomial (degree [this] (if (empty? terms) -1 (reduce + (exponents (peek terms))))) (coef [_ exponents] (if-let [s (seq (drop-while #(not= exponents (first %)) terms))] (second (first s)) (a/additive-identity ring))) (evaluate [_ args] (reduce (partial a/add ring) (a/additive-identity ring) (for [[es c] terms] (reduce (partial a/mul ring) c (map #(a/exponentiation-by-squaring ring %1 %2) args es))))) (fmap [_ S f] (->Polynomial S arity (into empty-coefficients (for [[xs c] terms :let [fc (f c)] :when (not (a/additive-identity? S fc))] [xs fc]))))) (defn ^:private polynomial-zero? [^Polynomial p] (empty? (.terms p))) (defn ^:private polynomial-one? "True if p has only a constant term which is equal to the multiplicative identity in its base ring" [^Polynomial p] (let [R (.ring p) xs->c (.terms p)] (when (= (count (.terms p)) 1) (let [[xs c] (first (.terms p))] (and (every? zero? xs) (a/multiplicative-identity? R c)))))) (defn ^:private polynomial-make "Constructs a polynomial with coefficients in `ring` with the given `arity` (number of indeterminates), followed by a sequence of exponent-coefficient pairs. Each exponent should be a vector with length equal to the arity, with non-negative integer exponent values. To make 4 x^2 y + 5 x y^2, an arity 2 polynomial (since it has two variables, x and y), we could write the following for xc-pairs: [[[2 1] 4] [[1 2] 5]]." [ring arity xc-pairs] (->Polynomial ring arity (->> (for [[xs cs] (group-by exponents xc-pairs) :let [sum-cs (reduce #(a/add ring %1 (coefficient %2)) (a/additive-identity ring) cs)] :when (not (a/additive-identity? ring sum-cs))] [xs sum-cs]) (sort-by exponents monomial-order) (into empty-coefficients)))) (defn ^:private lead-term "Return the leading (i.e., highest degree) term of the polynomial p. The return value is [exponents coefficient]." [^Polynomial p] (-> p .terms peek)) (defn coefficients [^Polynomial p] (->> p .terms (map coefficient))) (defn ^:private compatible-ring [^Polynomial p ^Polynomial q] (assert (and (= (.arity p) (.arity q)) (= (.ring p) (.ring q)))) (.ring p)) (defn ^:private compatible-constructor [^Polynomial p ^Polynomial q] (assert (and (= (.arity p) (.arity q)) (= (.ring p) (.ring q)))) (fn [xs->c] (polynomial-make (.ring p) (.arity p) xs->c))) (defn ^:private polynomial-negate [^Polynomial p] (let [R (.ring p)] (fmap p R #(a/negate R %)))) (defn ^:private polynomial-basis [ring arity] (cons (->Polynomial ring arity [[(vec (repeat arity 0)) (a/multiplicative-identity ring)]]) (for [i (range arity)] (->Polynomial ring arity [[(vec (for [j (range arity)] (if (= i j) 1 0))) (a/multiplicative-identity ring)]])))) (defn ^:private compatible [^Polynomial p ^Polynomial q] (and (= (.ring p) (.ring q)) (= (.arity p) (.arity q)))) (defn ^:private merge-term-lists "Merges term lists, both assumed sorted. Terms with same exponents are combined via op, and discarded if the combination is the additive identity in the ring R." [ps qs op R] (loop [ps ps qs qs s empty-coefficients] (cond (empty? ps) (into s qs) (empty? qs) (into s ps) :else (let [[pxs pc] (first ps) [qxs qc] (first qs) o (monomial-order pxs qxs)] (cond (zero? o) (recur (rest ps) (rest qs) (let [sc (op R pc qc)] (if (a/additive-identity? R sc) s (conj s [pxs sc])))) (< o 0) (recur (rest ps) qs (conj s [pxs pc])) :else (recur ps (rest qs) (conj s [qxs qc]))))))) (defn ^:private add "Adds the polynomials p and q" [^Polynomial p ^Polynomial q] {:pre [(instance? Polynomial p) (instance? Polynomial q) (compatible p q)]} (let [R (.ring p)] (->Polynomial R (.arity p) (merge-term-lists (.terms p) (.terms q) a/add R)))) (defn ^:private sub "Adds the polynomials p and q" [p q] (add p (polynomial-negate q))) (defn ^:private scale "Scalar multiply p by c, where c is in the same ring as the coefficients of p" [c ^Polynomial p] {:pre [(instance? Polynomial p) (a/member? (.ring p) c)]} (let [R (.ring p)] (fmap p R #(a/mul R % c)))) (defn ^:private mul "Multiply polynomials p and q, and return the product." [^Polynomial p ^Polynomial q] {:pre [(instance? Polynomial p) (instance? Polynomial q)]} (cond (polynomial-zero? p) p (polynomial-zero? q) q (polynomial-one? p) q (polynomial-one? q) p :else (let [R (.ring p)] ((compatible-constructor p q) (for [[xp cp] (.terms p) [xq cq] (.terms q)] [(mapv + xp xq) (a/mul R cp cq)]))))) (defn ^:private polynomial-order [^Polynomial p ^Polynomial q] {:pre [(instance? Polynomial p) (instance? Polynomial q) (= (.arity p) (.arity q)) (= (.ring p) (.ring q))]} (loop [pterms (rseq (.terms p)) qterms (rseq (.terms q))] (cond (nil? qterms) (if pterms 1 0) (nil? pterms) -1 :else (let [[ep cp] (first pterms) [eq cq] (first qterms)] (let [mo (monomial-order ep eq)] (if (zero? mo) (let [k (compare cp cq)] (if (not= k 0) k (recur (next pterms) (next qterms)))) mo)))))) (defn ^:private divide "Divide polynomial u by v, and return the pair of [quotient, remainder] polynomials. This assumes that the coefficients are drawn from a field, and so support division." [^Polynomial u ^Polynomial v] {:pre [(instance? Polynomial u) (instance? Polynomial v)]} (cond (polynomial-zero? v) (throw (IllegalArgumentException. "internal polynomial division by zero")) (polynomial-zero? u) [u u] (polynomial-one? v) [u (->Polynomial (.ring u) (.arity u) empty-coefficients)] :else (let [ctor (compatible-constructor u v) R (.ring u) [vn-exponents vn-coefficient] (lead-term v) good? (fn [residues] (and (not-empty residues) (every? (complement neg?) residues)))] (loop [quotient (ctor []) remainder u] ;; find a term in the remainder into which the ;; lead term of the divisor can be divided. (let [[r-exponents r-coefficient] (lead-term remainder) residues (mapv - r-exponents vn-exponents)] (if (good? residues) (let [new-coefficient (a/divide R r-coefficient vn-coefficient) new-term (ctor [[residues new-coefficient]])] (recur (add quotient new-term) (sub remainder (mul new-term v)))) [quotient remainder])))))) (defprotocol IPolynomialConstructor (basis [this] "Produces the constant unit polynomial polynomial in the base ring followed by one linear polynomial with unit linear coefficient and zero constant term for each indeterminate.") (make-unary [this dense-coefficients] "In the unary case, makes a polynomial with a dense coefficient list (beginning with the constant term and proceeding with each sequential exponent)") (make [this xc-pairs] "Makes a polynomial given a (sparse) list of `[exponent-vector coefficient]` pairs")) (defprotocol PseudoDivisible (pseudo-divide [this u v])) (defmacro ^:private reify-polynomial-ring "A macro is used because we want to optionally configure a protocol in the reified object, and reify itself is a macro." [R arity & {:keys [euclidean pseudo-divisible]}] `(reify a/Ring (member? [_ p#] (instance? Polynomial p#)) (additive-identity [_] (->Polynomial ~R ~arity [])) (additive-identity? [_ p#] (polynomial-zero? p#)) (multiplicative-identity [_] (->Polynomial ~R ~arity [[(vec (repeat ~arity 0)) (a/multiplicative-identity ~R)]])) (multiplicative-identity? [_ p#] (polynomial-one? p#)) (add [_ p# q#] (add p# q#)) (subtract [_ p# q#] (sub p# q#)) (negate [_ p#] (polynomial-negate p#)) (mul [_ p# q#] (mul p# q#)) ;; the problem is that the right implementation of quorem ;; depends on the base ring? Also, we note that Z[x] is not ;; a Euclidean domain since we can't get a Bézout identity ;; out of gcd(2,x) = 1 using coefficients in Z. ~@(if euclidean `(a/Euclidean (quorem [_ p# q#] (divide p# q#)))) ~@(if pseudo-divisible `(PseudoDivisible (pseudo-divide [_ p# q#] (zippel-pseudo-remainder p# q#)))) a/Ordered (cmp [_ p# q#] (polynomial-order p# q#)) a/Module (scale [_ r# p#] (scale r# p#)) IPolynomialConstructor (basis [_] (polynomial-basis ~R ~arity)) (make-unary [_ dense-coefficients#] (assert (= ~arity 1)) (polynomial-make ~R 1 (map #(vector [%1] %2) (range) dense-coefficients#))) (make [_ xc-pairs#] (polynomial-make ~R ~arity xc-pairs#)) Object (toString [_] (format "%s[%dv]" ~R ~arity)))) (def Zx (reify-polynomial-ring a/Z 1 :pseudo-divisible true)) (defn PolynomialRing [coefficient-ring arity] (if (= arity 1) (reify-polynomial-ring coefficient-ring arity :euclidean true) (reify-polynomial-ring coefficient-ring arity))) (defn zippel-pseudo-remainder "The algorithm PolyPseudoRemainder from Zippel, p.132" [^Polynomial u ^Polynomial v] {:pre [(= (.arity u) (.arity v) 1)]} (let [R (compatible-ring u v) deg-u (degree u) deg-v (degree v) lcv (coefficient (lead-term v)) δ (- deg-u deg-v)] (if (< deg-u deg-v) u (loop [w u] (let [k (- (degree w) deg-v) lcw (coefficient (lead-term w)) w' (sub (scale lcv w) (mul v (->Polynomial R 1 [[[k] lcw]]))) k' (- (degree w') deg-v)] (cond (polynomial-zero? w') w' (< (degree w') deg-v) (scale (a/exponentiation-by-squaring R lcv k) w') (> k (inc δ)) (let [e (- k (inc δ)) lcv**e (a/exponentiation-by-squaring R lcv e)] (recur (scale lcv**e w'))) :else (recur w'))))))) (defn ^:private pseudo-quotient "The pseudo-quotient straight from the definition. Makes no attempt to control coefficient growth." [^Polynomial u ^Polynomial v] ;; annoying: divide wants field divide, so we may want to ;; implement the "custom" pseudo-division here. {:pre [(instance? Polynomial u) (instance? Polynomial v) (not (polynomial-zero? v)) (= (.arity u) (.arity v) 1)]} (let [R (compatible-ring u v) deg-u (degree u) deg-v (degree v) lcv (coefficient (lead-term v)) e (- (inc deg-u) deg-v) lcv**e (a/exponentiation-by-squaring R lcv e)] (divide (scale lcv**e u) v))) (defn classic-pseudo-remainder "The pseudo-remainder straight from the definition. Makes no attempt to control coefficient growth." [u v] (second (pseudo-quotient u v))) (defn ^:private univariate-content [^Polynomial p] {:pre [(= (.arity p) 1)]} (if (polynomial-zero? p) p (a/euclid-gcd-seq (.ring p) (coefficients p)))) (defn univariate-primitive-part [^Polynomial p] {:pre [(= (.arity p) 1)]} (let [R (.ring p) g (univariate-content p)] (fmap p R #(a/exact-quotient R % g)))) (defn subresultant-polynomial-remainder-sequence [^Polynomial u ^Polynomial v] (assert (= (.arity u) (.arity v) 1)) (let [R (compatible-ring u v) one (a/multiplicative-identity R) minus-one (a/negate R one) δ0 (- (degree u) (degree v)) ψ0 (if (even? δ0) minus-one one)] (defn step [prr pr δr ψ β] (let [p (fmap (classic-pseudo-remainder prr pr) R #(a/exact-quotient R % β) ) a (coefficient (lead-term pr)) ψ (if (zero? δr) ψ ; Avoid negative exponent (a/exact-quotient R (a/exponentiation-by-squaring R a δr) (a/exponentiation-by-squaring R ψ (dec δr)))) δ (- (degree pr) (degree p)) β (a/mul R (if (even? δ) minus-one one) (a/mul R (a/exponentiation-by-squaring R ψ δ) a))] (if (polynomial-zero? p) nil (cons p (lazy-seq (step pr p δ ψ β)))))) (lazy-seq (cons u (cons v (if (< δ0 0) (step v u (- δ0) one ψ0) (step u v δ0 one ψ0))))))) (defn univariate-subresultant-gcd [u v] (let [R (compatible-ring u v) prs (if (> (degree u) (degree v)) (subresultant-polynomial-remainder-sequence u v) (subresultant-polynomial-remainder-sequence v u)) g (last prs)] (if (zero? (degree g)) (->Polynomial R 1 (conj empty-coefficients [[0] (a/multiplicative-identity R)])) g))) (defn univariate-euclid-gcd [u v] (if (polynomial-zero? v) u (recur v (univariate-primitive-part (zippel-pseudo-remainder u v))))) (defn pseudo-remainder-sequence [remainder] (fn step [u v] (if (polynomial-zero? v) (list u) (lazy-seq (cons u (step v (remainder u v))))))) (defn ^:private abs [^Polynomial p] (let [R (.ring p)] (if (a/cmp R p (a/additive-identity R)) (polynomial-negate p) p))) (defn partial-derivative "The partial derivative of the polynomial with respect to the i-th indeterminate." [^Polynomial p i] (let [R (.ring p)] (polynomial-make (.ring p) (.arity p) (for [[xs c] (.terms p) :let [xi (xs i)] :when (not= 0 xi)] [(update xs i dec) (a/mul R xi c)])))) (defn partial-derivatives "The sequence of partial derivatives of p with respect to each indeterminate" [^Polynomial p] (for [i (range (.arity p))] (partial-derivative p i))) (def ^:private log2e (/ (Math/log 2))) (defn ^:private log2 [x] (* (Math/log x) log2e)) (def ^:private small-odd-primes [ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 ]) (defn small-primes-modular-univariate-gcd "[GG13] Algorithm 6.38" [u v] (let [R (compatible-ring u v) u (univariate-primitive-part u) v (univariate-primitive-part v) n (degree u) ;; XXX: alg. wants deg f >= deg g >= 1 A (reduce max (map coefficient (concat (:terms u) (:terms v)))) b (a/euclid-gcd R (coefficient (lead-term u)) (coefficient (lead-term v))) k (Math/ceil (+ (* n (log2 (inc n))) (log2 b) (* 2 n (log2 A)))) B (* (Math/sqrt (inc n)) (Math/pow 2 n) A b) l (Math/ceil (log2 (inc (* 2 B)))) L (* 2 k (Math/log k)) ;; step 3: choose a set S of 2l primes, each less than 2k ln k ;; The first part of step 4 drops all primes that divide b from ;; S. We coalesce these operations into one step. ps (take (* 2 l) (filter #(not= 0 (mod b %)) small-odd-primes)) prime-rings (map a/->Zmod ps) ubars (map #(fmap u % (fn [c] (mod c (:n %)))) prime-rings) vbars (map #(fmap v % (fn [c] (mod c (:n %)))) prime-rings) gs (map univariate-euclid-gcd ubars vbars)] [A b k B l L] (println "u" u) (println "v" v) (println "ps" ps) (println "ubars" ubars) (println "vbars" vbars) (println "gs" gs)))
82434
;; Copyright Copyright © 2017 <NAME>. MIT License. (ns algebra.polynomial (:import (clojure.lang BigInt Ratio)) (:require [algebra :as a] [clojure.set :as set] [clojure.string :as string])) (def coefficient second) (def exponents first) ;; Monomials ;; ;; We represent a monomial as a vector of integers representing ;; the exponents of the indeterminates over some ring. For example; ;; we would represent x^2 as [2], and xy^2 as [1 2], though the ;; indeterminates have no name. Polynomials are linear combinations ;; of the monomials. When these are formed, it is important that the ;; monomial vectors all contain the same number of slots, so that ;; 3x + 2y^2 would be represented as: 3*[1 0] + 2*[0 2]. (defn ^:private monomial-degree "Compute the degree of a monomial. This is just the sum of the exponents." [m] (reduce + m)) ;; Monomial Orderings ;; ;; These orderings are in the sense of Java: x.compareTo(y), so that ;; this returns >0 if x > y, <0 if x < y, and ==0 if x = y. (defn lex-order "Lex order for monomials considers the power of x, then the power of y, etc." [xs ys] {:pre (= (count xs) (count ys))} (compare xs ys)) (defn graded-lex-order "" [xs ys] {:pre (= (count xs) (count ys))} (let [xd (monomial-degree xs) yd (monomial-degree ys)] (if (= xd yd) (lex-order xs ys) (- xd yd)))) (defn graded-reverse-lex-order "" [xs ys] {:pre (= (count xs) (count ys))} (let [xd (monomial-degree xs) yd (monomial-degree ys)] (if (= xd yd) (compare (vec (rseq ys)) (vec (rseq xs))) (- xd yd)))) (def ^:private monomial-order graded-lex-order) (def ^:private empty-coefficients []) ;; ;; Polynomials ;; (defprotocol IPolynomial (degree [this]) (coef [this exponents]) (evaluate [this args]) (fmap [this S f])) (defrecord Polynomial [ring arity terms] IPolynomial (degree [this] (if (empty? terms) -1 (reduce + (exponents (peek terms))))) (coef [_ exponents] (if-let [s (seq (drop-while #(not= exponents (first %)) terms))] (second (first s)) (a/additive-identity ring))) (evaluate [_ args] (reduce (partial a/add ring) (a/additive-identity ring) (for [[es c] terms] (reduce (partial a/mul ring) c (map #(a/exponentiation-by-squaring ring %1 %2) args es))))) (fmap [_ S f] (->Polynomial S arity (into empty-coefficients (for [[xs c] terms :let [fc (f c)] :when (not (a/additive-identity? S fc))] [xs fc]))))) (defn ^:private polynomial-zero? [^Polynomial p] (empty? (.terms p))) (defn ^:private polynomial-one? "True if p has only a constant term which is equal to the multiplicative identity in its base ring" [^Polynomial p] (let [R (.ring p) xs->c (.terms p)] (when (= (count (.terms p)) 1) (let [[xs c] (first (.terms p))] (and (every? zero? xs) (a/multiplicative-identity? R c)))))) (defn ^:private polynomial-make "Constructs a polynomial with coefficients in `ring` with the given `arity` (number of indeterminates), followed by a sequence of exponent-coefficient pairs. Each exponent should be a vector with length equal to the arity, with non-negative integer exponent values. To make 4 x^2 y + 5 x y^2, an arity 2 polynomial (since it has two variables, x and y), we could write the following for xc-pairs: [[[2 1] 4] [[1 2] 5]]." [ring arity xc-pairs] (->Polynomial ring arity (->> (for [[xs cs] (group-by exponents xc-pairs) :let [sum-cs (reduce #(a/add ring %1 (coefficient %2)) (a/additive-identity ring) cs)] :when (not (a/additive-identity? ring sum-cs))] [xs sum-cs]) (sort-by exponents monomial-order) (into empty-coefficients)))) (defn ^:private lead-term "Return the leading (i.e., highest degree) term of the polynomial p. The return value is [exponents coefficient]." [^Polynomial p] (-> p .terms peek)) (defn coefficients [^Polynomial p] (->> p .terms (map coefficient))) (defn ^:private compatible-ring [^Polynomial p ^Polynomial q] (assert (and (= (.arity p) (.arity q)) (= (.ring p) (.ring q)))) (.ring p)) (defn ^:private compatible-constructor [^Polynomial p ^Polynomial q] (assert (and (= (.arity p) (.arity q)) (= (.ring p) (.ring q)))) (fn [xs->c] (polynomial-make (.ring p) (.arity p) xs->c))) (defn ^:private polynomial-negate [^Polynomial p] (let [R (.ring p)] (fmap p R #(a/negate R %)))) (defn ^:private polynomial-basis [ring arity] (cons (->Polynomial ring arity [[(vec (repeat arity 0)) (a/multiplicative-identity ring)]]) (for [i (range arity)] (->Polynomial ring arity [[(vec (for [j (range arity)] (if (= i j) 1 0))) (a/multiplicative-identity ring)]])))) (defn ^:private compatible [^Polynomial p ^Polynomial q] (and (= (.ring p) (.ring q)) (= (.arity p) (.arity q)))) (defn ^:private merge-term-lists "Merges term lists, both assumed sorted. Terms with same exponents are combined via op, and discarded if the combination is the additive identity in the ring R." [ps qs op R] (loop [ps ps qs qs s empty-coefficients] (cond (empty? ps) (into s qs) (empty? qs) (into s ps) :else (let [[pxs pc] (first ps) [qxs qc] (first qs) o (monomial-order pxs qxs)] (cond (zero? o) (recur (rest ps) (rest qs) (let [sc (op R pc qc)] (if (a/additive-identity? R sc) s (conj s [pxs sc])))) (< o 0) (recur (rest ps) qs (conj s [pxs pc])) :else (recur ps (rest qs) (conj s [qxs qc]))))))) (defn ^:private add "Adds the polynomials p and q" [^Polynomial p ^Polynomial q] {:pre [(instance? Polynomial p) (instance? Polynomial q) (compatible p q)]} (let [R (.ring p)] (->Polynomial R (.arity p) (merge-term-lists (.terms p) (.terms q) a/add R)))) (defn ^:private sub "Adds the polynomials p and q" [p q] (add p (polynomial-negate q))) (defn ^:private scale "Scalar multiply p by c, where c is in the same ring as the coefficients of p" [c ^Polynomial p] {:pre [(instance? Polynomial p) (a/member? (.ring p) c)]} (let [R (.ring p)] (fmap p R #(a/mul R % c)))) (defn ^:private mul "Multiply polynomials p and q, and return the product." [^Polynomial p ^Polynomial q] {:pre [(instance? Polynomial p) (instance? Polynomial q)]} (cond (polynomial-zero? p) p (polynomial-zero? q) q (polynomial-one? p) q (polynomial-one? q) p :else (let [R (.ring p)] ((compatible-constructor p q) (for [[xp cp] (.terms p) [xq cq] (.terms q)] [(mapv + xp xq) (a/mul R cp cq)]))))) (defn ^:private polynomial-order [^Polynomial p ^Polynomial q] {:pre [(instance? Polynomial p) (instance? Polynomial q) (= (.arity p) (.arity q)) (= (.ring p) (.ring q))]} (loop [pterms (rseq (.terms p)) qterms (rseq (.terms q))] (cond (nil? qterms) (if pterms 1 0) (nil? pterms) -1 :else (let [[ep cp] (first pterms) [eq cq] (first qterms)] (let [mo (monomial-order ep eq)] (if (zero? mo) (let [k (compare cp cq)] (if (not= k 0) k (recur (next pterms) (next qterms)))) mo)))))) (defn ^:private divide "Divide polynomial u by v, and return the pair of [quotient, remainder] polynomials. This assumes that the coefficients are drawn from a field, and so support division." [^Polynomial u ^Polynomial v] {:pre [(instance? Polynomial u) (instance? Polynomial v)]} (cond (polynomial-zero? v) (throw (IllegalArgumentException. "internal polynomial division by zero")) (polynomial-zero? u) [u u] (polynomial-one? v) [u (->Polynomial (.ring u) (.arity u) empty-coefficients)] :else (let [ctor (compatible-constructor u v) R (.ring u) [vn-exponents vn-coefficient] (lead-term v) good? (fn [residues] (and (not-empty residues) (every? (complement neg?) residues)))] (loop [quotient (ctor []) remainder u] ;; find a term in the remainder into which the ;; lead term of the divisor can be divided. (let [[r-exponents r-coefficient] (lead-term remainder) residues (mapv - r-exponents vn-exponents)] (if (good? residues) (let [new-coefficient (a/divide R r-coefficient vn-coefficient) new-term (ctor [[residues new-coefficient]])] (recur (add quotient new-term) (sub remainder (mul new-term v)))) [quotient remainder])))))) (defprotocol IPolynomialConstructor (basis [this] "Produces the constant unit polynomial polynomial in the base ring followed by one linear polynomial with unit linear coefficient and zero constant term for each indeterminate.") (make-unary [this dense-coefficients] "In the unary case, makes a polynomial with a dense coefficient list (beginning with the constant term and proceeding with each sequential exponent)") (make [this xc-pairs] "Makes a polynomial given a (sparse) list of `[exponent-vector coefficient]` pairs")) (defprotocol PseudoDivisible (pseudo-divide [this u v])) (defmacro ^:private reify-polynomial-ring "A macro is used because we want to optionally configure a protocol in the reified object, and reify itself is a macro." [R arity & {:keys [euclidean pseudo-divisible]}] `(reify a/Ring (member? [_ p#] (instance? Polynomial p#)) (additive-identity [_] (->Polynomial ~R ~arity [])) (additive-identity? [_ p#] (polynomial-zero? p#)) (multiplicative-identity [_] (->Polynomial ~R ~arity [[(vec (repeat ~arity 0)) (a/multiplicative-identity ~R)]])) (multiplicative-identity? [_ p#] (polynomial-one? p#)) (add [_ p# q#] (add p# q#)) (subtract [_ p# q#] (sub p# q#)) (negate [_ p#] (polynomial-negate p#)) (mul [_ p# q#] (mul p# q#)) ;; the problem is that the right implementation of quorem ;; depends on the base ring? Also, we note that Z[x] is not ;; a Euclidean domain since we can't get a Bézout identity ;; out of gcd(2,x) = 1 using coefficients in Z. ~@(if euclidean `(a/Euclidean (quorem [_ p# q#] (divide p# q#)))) ~@(if pseudo-divisible `(PseudoDivisible (pseudo-divide [_ p# q#] (zippel-pseudo-remainder p# q#)))) a/Ordered (cmp [_ p# q#] (polynomial-order p# q#)) a/Module (scale [_ r# p#] (scale r# p#)) IPolynomialConstructor (basis [_] (polynomial-basis ~R ~arity)) (make-unary [_ dense-coefficients#] (assert (= ~arity 1)) (polynomial-make ~R 1 (map #(vector [%1] %2) (range) dense-coefficients#))) (make [_ xc-pairs#] (polynomial-make ~R ~arity xc-pairs#)) Object (toString [_] (format "%s[%dv]" ~R ~arity)))) (def Zx (reify-polynomial-ring a/Z 1 :pseudo-divisible true)) (defn PolynomialRing [coefficient-ring arity] (if (= arity 1) (reify-polynomial-ring coefficient-ring arity :euclidean true) (reify-polynomial-ring coefficient-ring arity))) (defn zippel-pseudo-remainder "The algorithm PolyPseudoRemainder from Zippel, p.132" [^Polynomial u ^Polynomial v] {:pre [(= (.arity u) (.arity v) 1)]} (let [R (compatible-ring u v) deg-u (degree u) deg-v (degree v) lcv (coefficient (lead-term v)) δ (- deg-u deg-v)] (if (< deg-u deg-v) u (loop [w u] (let [k (- (degree w) deg-v) lcw (coefficient (lead-term w)) w' (sub (scale lcv w) (mul v (->Polynomial R 1 [[[k] lcw]]))) k' (- (degree w') deg-v)] (cond (polynomial-zero? w') w' (< (degree w') deg-v) (scale (a/exponentiation-by-squaring R lcv k) w') (> k (inc δ)) (let [e (- k (inc δ)) lcv**e (a/exponentiation-by-squaring R lcv e)] (recur (scale lcv**e w'))) :else (recur w'))))))) (defn ^:private pseudo-quotient "The pseudo-quotient straight from the definition. Makes no attempt to control coefficient growth." [^Polynomial u ^Polynomial v] ;; annoying: divide wants field divide, so we may want to ;; implement the "custom" pseudo-division here. {:pre [(instance? Polynomial u) (instance? Polynomial v) (not (polynomial-zero? v)) (= (.arity u) (.arity v) 1)]} (let [R (compatible-ring u v) deg-u (degree u) deg-v (degree v) lcv (coefficient (lead-term v)) e (- (inc deg-u) deg-v) lcv**e (a/exponentiation-by-squaring R lcv e)] (divide (scale lcv**e u) v))) (defn classic-pseudo-remainder "The pseudo-remainder straight from the definition. Makes no attempt to control coefficient growth." [u v] (second (pseudo-quotient u v))) (defn ^:private univariate-content [^Polynomial p] {:pre [(= (.arity p) 1)]} (if (polynomial-zero? p) p (a/euclid-gcd-seq (.ring p) (coefficients p)))) (defn univariate-primitive-part [^Polynomial p] {:pre [(= (.arity p) 1)]} (let [R (.ring p) g (univariate-content p)] (fmap p R #(a/exact-quotient R % g)))) (defn subresultant-polynomial-remainder-sequence [^Polynomial u ^Polynomial v] (assert (= (.arity u) (.arity v) 1)) (let [R (compatible-ring u v) one (a/multiplicative-identity R) minus-one (a/negate R one) δ0 (- (degree u) (degree v)) ψ0 (if (even? δ0) minus-one one)] (defn step [prr pr δr ψ β] (let [p (fmap (classic-pseudo-remainder prr pr) R #(a/exact-quotient R % β) ) a (coefficient (lead-term pr)) ψ (if (zero? δr) ψ ; Avoid negative exponent (a/exact-quotient R (a/exponentiation-by-squaring R a δr) (a/exponentiation-by-squaring R ψ (dec δr)))) δ (- (degree pr) (degree p)) β (a/mul R (if (even? δ) minus-one one) (a/mul R (a/exponentiation-by-squaring R ψ δ) a))] (if (polynomial-zero? p) nil (cons p (lazy-seq (step pr p δ ψ β)))))) (lazy-seq (cons u (cons v (if (< δ0 0) (step v u (- δ0) one ψ0) (step u v δ0 one ψ0))))))) (defn univariate-subresultant-gcd [u v] (let [R (compatible-ring u v) prs (if (> (degree u) (degree v)) (subresultant-polynomial-remainder-sequence u v) (subresultant-polynomial-remainder-sequence v u)) g (last prs)] (if (zero? (degree g)) (->Polynomial R 1 (conj empty-coefficients [[0] (a/multiplicative-identity R)])) g))) (defn univariate-euclid-gcd [u v] (if (polynomial-zero? v) u (recur v (univariate-primitive-part (zippel-pseudo-remainder u v))))) (defn pseudo-remainder-sequence [remainder] (fn step [u v] (if (polynomial-zero? v) (list u) (lazy-seq (cons u (step v (remainder u v))))))) (defn ^:private abs [^Polynomial p] (let [R (.ring p)] (if (a/cmp R p (a/additive-identity R)) (polynomial-negate p) p))) (defn partial-derivative "The partial derivative of the polynomial with respect to the i-th indeterminate." [^Polynomial p i] (let [R (.ring p)] (polynomial-make (.ring p) (.arity p) (for [[xs c] (.terms p) :let [xi (xs i)] :when (not= 0 xi)] [(update xs i dec) (a/mul R xi c)])))) (defn partial-derivatives "The sequence of partial derivatives of p with respect to each indeterminate" [^Polynomial p] (for [i (range (.arity p))] (partial-derivative p i))) (def ^:private log2e (/ (Math/log 2))) (defn ^:private log2 [x] (* (Math/log x) log2e)) (def ^:private small-odd-primes [ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 ]) (defn small-primes-modular-univariate-gcd "[GG13] Algorithm 6.38" [u v] (let [R (compatible-ring u v) u (univariate-primitive-part u) v (univariate-primitive-part v) n (degree u) ;; XXX: alg. wants deg f >= deg g >= 1 A (reduce max (map coefficient (concat (:terms u) (:terms v)))) b (a/euclid-gcd R (coefficient (lead-term u)) (coefficient (lead-term v))) k (Math/ceil (+ (* n (log2 (inc n))) (log2 b) (* 2 n (log2 A)))) B (* (Math/sqrt (inc n)) (Math/pow 2 n) A b) l (Math/ceil (log2 (inc (* 2 B)))) L (* 2 k (Math/log k)) ;; step 3: choose a set S of 2l primes, each less than 2k ln k ;; The first part of step 4 drops all primes that divide b from ;; S. We coalesce these operations into one step. ps (take (* 2 l) (filter #(not= 0 (mod b %)) small-odd-primes)) prime-rings (map a/->Zmod ps) ubars (map #(fmap u % (fn [c] (mod c (:n %)))) prime-rings) vbars (map #(fmap v % (fn [c] (mod c (:n %)))) prime-rings) gs (map univariate-euclid-gcd ubars vbars)] [A b k B l L] (println "u" u) (println "v" v) (println "ps" ps) (println "ubars" ubars) (println "vbars" vbars) (println "gs" gs)))
true
;; Copyright Copyright © 2017 PI:NAME:<NAME>END_PI. MIT License. (ns algebra.polynomial (:import (clojure.lang BigInt Ratio)) (:require [algebra :as a] [clojure.set :as set] [clojure.string :as string])) (def coefficient second) (def exponents first) ;; Monomials ;; ;; We represent a monomial as a vector of integers representing ;; the exponents of the indeterminates over some ring. For example; ;; we would represent x^2 as [2], and xy^2 as [1 2], though the ;; indeterminates have no name. Polynomials are linear combinations ;; of the monomials. When these are formed, it is important that the ;; monomial vectors all contain the same number of slots, so that ;; 3x + 2y^2 would be represented as: 3*[1 0] + 2*[0 2]. (defn ^:private monomial-degree "Compute the degree of a monomial. This is just the sum of the exponents." [m] (reduce + m)) ;; Monomial Orderings ;; ;; These orderings are in the sense of Java: x.compareTo(y), so that ;; this returns >0 if x > y, <0 if x < y, and ==0 if x = y. (defn lex-order "Lex order for monomials considers the power of x, then the power of y, etc." [xs ys] {:pre (= (count xs) (count ys))} (compare xs ys)) (defn graded-lex-order "" [xs ys] {:pre (= (count xs) (count ys))} (let [xd (monomial-degree xs) yd (monomial-degree ys)] (if (= xd yd) (lex-order xs ys) (- xd yd)))) (defn graded-reverse-lex-order "" [xs ys] {:pre (= (count xs) (count ys))} (let [xd (monomial-degree xs) yd (monomial-degree ys)] (if (= xd yd) (compare (vec (rseq ys)) (vec (rseq xs))) (- xd yd)))) (def ^:private monomial-order graded-lex-order) (def ^:private empty-coefficients []) ;; ;; Polynomials ;; (defprotocol IPolynomial (degree [this]) (coef [this exponents]) (evaluate [this args]) (fmap [this S f])) (defrecord Polynomial [ring arity terms] IPolynomial (degree [this] (if (empty? terms) -1 (reduce + (exponents (peek terms))))) (coef [_ exponents] (if-let [s (seq (drop-while #(not= exponents (first %)) terms))] (second (first s)) (a/additive-identity ring))) (evaluate [_ args] (reduce (partial a/add ring) (a/additive-identity ring) (for [[es c] terms] (reduce (partial a/mul ring) c (map #(a/exponentiation-by-squaring ring %1 %2) args es))))) (fmap [_ S f] (->Polynomial S arity (into empty-coefficients (for [[xs c] terms :let [fc (f c)] :when (not (a/additive-identity? S fc))] [xs fc]))))) (defn ^:private polynomial-zero? [^Polynomial p] (empty? (.terms p))) (defn ^:private polynomial-one? "True if p has only a constant term which is equal to the multiplicative identity in its base ring" [^Polynomial p] (let [R (.ring p) xs->c (.terms p)] (when (= (count (.terms p)) 1) (let [[xs c] (first (.terms p))] (and (every? zero? xs) (a/multiplicative-identity? R c)))))) (defn ^:private polynomial-make "Constructs a polynomial with coefficients in `ring` with the given `arity` (number of indeterminates), followed by a sequence of exponent-coefficient pairs. Each exponent should be a vector with length equal to the arity, with non-negative integer exponent values. To make 4 x^2 y + 5 x y^2, an arity 2 polynomial (since it has two variables, x and y), we could write the following for xc-pairs: [[[2 1] 4] [[1 2] 5]]." [ring arity xc-pairs] (->Polynomial ring arity (->> (for [[xs cs] (group-by exponents xc-pairs) :let [sum-cs (reduce #(a/add ring %1 (coefficient %2)) (a/additive-identity ring) cs)] :when (not (a/additive-identity? ring sum-cs))] [xs sum-cs]) (sort-by exponents monomial-order) (into empty-coefficients)))) (defn ^:private lead-term "Return the leading (i.e., highest degree) term of the polynomial p. The return value is [exponents coefficient]." [^Polynomial p] (-> p .terms peek)) (defn coefficients [^Polynomial p] (->> p .terms (map coefficient))) (defn ^:private compatible-ring [^Polynomial p ^Polynomial q] (assert (and (= (.arity p) (.arity q)) (= (.ring p) (.ring q)))) (.ring p)) (defn ^:private compatible-constructor [^Polynomial p ^Polynomial q] (assert (and (= (.arity p) (.arity q)) (= (.ring p) (.ring q)))) (fn [xs->c] (polynomial-make (.ring p) (.arity p) xs->c))) (defn ^:private polynomial-negate [^Polynomial p] (let [R (.ring p)] (fmap p R #(a/negate R %)))) (defn ^:private polynomial-basis [ring arity] (cons (->Polynomial ring arity [[(vec (repeat arity 0)) (a/multiplicative-identity ring)]]) (for [i (range arity)] (->Polynomial ring arity [[(vec (for [j (range arity)] (if (= i j) 1 0))) (a/multiplicative-identity ring)]])))) (defn ^:private compatible [^Polynomial p ^Polynomial q] (and (= (.ring p) (.ring q)) (= (.arity p) (.arity q)))) (defn ^:private merge-term-lists "Merges term lists, both assumed sorted. Terms with same exponents are combined via op, and discarded if the combination is the additive identity in the ring R." [ps qs op R] (loop [ps ps qs qs s empty-coefficients] (cond (empty? ps) (into s qs) (empty? qs) (into s ps) :else (let [[pxs pc] (first ps) [qxs qc] (first qs) o (monomial-order pxs qxs)] (cond (zero? o) (recur (rest ps) (rest qs) (let [sc (op R pc qc)] (if (a/additive-identity? R sc) s (conj s [pxs sc])))) (< o 0) (recur (rest ps) qs (conj s [pxs pc])) :else (recur ps (rest qs) (conj s [qxs qc]))))))) (defn ^:private add "Adds the polynomials p and q" [^Polynomial p ^Polynomial q] {:pre [(instance? Polynomial p) (instance? Polynomial q) (compatible p q)]} (let [R (.ring p)] (->Polynomial R (.arity p) (merge-term-lists (.terms p) (.terms q) a/add R)))) (defn ^:private sub "Adds the polynomials p and q" [p q] (add p (polynomial-negate q))) (defn ^:private scale "Scalar multiply p by c, where c is in the same ring as the coefficients of p" [c ^Polynomial p] {:pre [(instance? Polynomial p) (a/member? (.ring p) c)]} (let [R (.ring p)] (fmap p R #(a/mul R % c)))) (defn ^:private mul "Multiply polynomials p and q, and return the product." [^Polynomial p ^Polynomial q] {:pre [(instance? Polynomial p) (instance? Polynomial q)]} (cond (polynomial-zero? p) p (polynomial-zero? q) q (polynomial-one? p) q (polynomial-one? q) p :else (let [R (.ring p)] ((compatible-constructor p q) (for [[xp cp] (.terms p) [xq cq] (.terms q)] [(mapv + xp xq) (a/mul R cp cq)]))))) (defn ^:private polynomial-order [^Polynomial p ^Polynomial q] {:pre [(instance? Polynomial p) (instance? Polynomial q) (= (.arity p) (.arity q)) (= (.ring p) (.ring q))]} (loop [pterms (rseq (.terms p)) qterms (rseq (.terms q))] (cond (nil? qterms) (if pterms 1 0) (nil? pterms) -1 :else (let [[ep cp] (first pterms) [eq cq] (first qterms)] (let [mo (monomial-order ep eq)] (if (zero? mo) (let [k (compare cp cq)] (if (not= k 0) k (recur (next pterms) (next qterms)))) mo)))))) (defn ^:private divide "Divide polynomial u by v, and return the pair of [quotient, remainder] polynomials. This assumes that the coefficients are drawn from a field, and so support division." [^Polynomial u ^Polynomial v] {:pre [(instance? Polynomial u) (instance? Polynomial v)]} (cond (polynomial-zero? v) (throw (IllegalArgumentException. "internal polynomial division by zero")) (polynomial-zero? u) [u u] (polynomial-one? v) [u (->Polynomial (.ring u) (.arity u) empty-coefficients)] :else (let [ctor (compatible-constructor u v) R (.ring u) [vn-exponents vn-coefficient] (lead-term v) good? (fn [residues] (and (not-empty residues) (every? (complement neg?) residues)))] (loop [quotient (ctor []) remainder u] ;; find a term in the remainder into which the ;; lead term of the divisor can be divided. (let [[r-exponents r-coefficient] (lead-term remainder) residues (mapv - r-exponents vn-exponents)] (if (good? residues) (let [new-coefficient (a/divide R r-coefficient vn-coefficient) new-term (ctor [[residues new-coefficient]])] (recur (add quotient new-term) (sub remainder (mul new-term v)))) [quotient remainder])))))) (defprotocol IPolynomialConstructor (basis [this] "Produces the constant unit polynomial polynomial in the base ring followed by one linear polynomial with unit linear coefficient and zero constant term for each indeterminate.") (make-unary [this dense-coefficients] "In the unary case, makes a polynomial with a dense coefficient list (beginning with the constant term and proceeding with each sequential exponent)") (make [this xc-pairs] "Makes a polynomial given a (sparse) list of `[exponent-vector coefficient]` pairs")) (defprotocol PseudoDivisible (pseudo-divide [this u v])) (defmacro ^:private reify-polynomial-ring "A macro is used because we want to optionally configure a protocol in the reified object, and reify itself is a macro." [R arity & {:keys [euclidean pseudo-divisible]}] `(reify a/Ring (member? [_ p#] (instance? Polynomial p#)) (additive-identity [_] (->Polynomial ~R ~arity [])) (additive-identity? [_ p#] (polynomial-zero? p#)) (multiplicative-identity [_] (->Polynomial ~R ~arity [[(vec (repeat ~arity 0)) (a/multiplicative-identity ~R)]])) (multiplicative-identity? [_ p#] (polynomial-one? p#)) (add [_ p# q#] (add p# q#)) (subtract [_ p# q#] (sub p# q#)) (negate [_ p#] (polynomial-negate p#)) (mul [_ p# q#] (mul p# q#)) ;; the problem is that the right implementation of quorem ;; depends on the base ring? Also, we note that Z[x] is not ;; a Euclidean domain since we can't get a Bézout identity ;; out of gcd(2,x) = 1 using coefficients in Z. ~@(if euclidean `(a/Euclidean (quorem [_ p# q#] (divide p# q#)))) ~@(if pseudo-divisible `(PseudoDivisible (pseudo-divide [_ p# q#] (zippel-pseudo-remainder p# q#)))) a/Ordered (cmp [_ p# q#] (polynomial-order p# q#)) a/Module (scale [_ r# p#] (scale r# p#)) IPolynomialConstructor (basis [_] (polynomial-basis ~R ~arity)) (make-unary [_ dense-coefficients#] (assert (= ~arity 1)) (polynomial-make ~R 1 (map #(vector [%1] %2) (range) dense-coefficients#))) (make [_ xc-pairs#] (polynomial-make ~R ~arity xc-pairs#)) Object (toString [_] (format "%s[%dv]" ~R ~arity)))) (def Zx (reify-polynomial-ring a/Z 1 :pseudo-divisible true)) (defn PolynomialRing [coefficient-ring arity] (if (= arity 1) (reify-polynomial-ring coefficient-ring arity :euclidean true) (reify-polynomial-ring coefficient-ring arity))) (defn zippel-pseudo-remainder "The algorithm PolyPseudoRemainder from Zippel, p.132" [^Polynomial u ^Polynomial v] {:pre [(= (.arity u) (.arity v) 1)]} (let [R (compatible-ring u v) deg-u (degree u) deg-v (degree v) lcv (coefficient (lead-term v)) δ (- deg-u deg-v)] (if (< deg-u deg-v) u (loop [w u] (let [k (- (degree w) deg-v) lcw (coefficient (lead-term w)) w' (sub (scale lcv w) (mul v (->Polynomial R 1 [[[k] lcw]]))) k' (- (degree w') deg-v)] (cond (polynomial-zero? w') w' (< (degree w') deg-v) (scale (a/exponentiation-by-squaring R lcv k) w') (> k (inc δ)) (let [e (- k (inc δ)) lcv**e (a/exponentiation-by-squaring R lcv e)] (recur (scale lcv**e w'))) :else (recur w'))))))) (defn ^:private pseudo-quotient "The pseudo-quotient straight from the definition. Makes no attempt to control coefficient growth." [^Polynomial u ^Polynomial v] ;; annoying: divide wants field divide, so we may want to ;; implement the "custom" pseudo-division here. {:pre [(instance? Polynomial u) (instance? Polynomial v) (not (polynomial-zero? v)) (= (.arity u) (.arity v) 1)]} (let [R (compatible-ring u v) deg-u (degree u) deg-v (degree v) lcv (coefficient (lead-term v)) e (- (inc deg-u) deg-v) lcv**e (a/exponentiation-by-squaring R lcv e)] (divide (scale lcv**e u) v))) (defn classic-pseudo-remainder "The pseudo-remainder straight from the definition. Makes no attempt to control coefficient growth." [u v] (second (pseudo-quotient u v))) (defn ^:private univariate-content [^Polynomial p] {:pre [(= (.arity p) 1)]} (if (polynomial-zero? p) p (a/euclid-gcd-seq (.ring p) (coefficients p)))) (defn univariate-primitive-part [^Polynomial p] {:pre [(= (.arity p) 1)]} (let [R (.ring p) g (univariate-content p)] (fmap p R #(a/exact-quotient R % g)))) (defn subresultant-polynomial-remainder-sequence [^Polynomial u ^Polynomial v] (assert (= (.arity u) (.arity v) 1)) (let [R (compatible-ring u v) one (a/multiplicative-identity R) minus-one (a/negate R one) δ0 (- (degree u) (degree v)) ψ0 (if (even? δ0) minus-one one)] (defn step [prr pr δr ψ β] (let [p (fmap (classic-pseudo-remainder prr pr) R #(a/exact-quotient R % β) ) a (coefficient (lead-term pr)) ψ (if (zero? δr) ψ ; Avoid negative exponent (a/exact-quotient R (a/exponentiation-by-squaring R a δr) (a/exponentiation-by-squaring R ψ (dec δr)))) δ (- (degree pr) (degree p)) β (a/mul R (if (even? δ) minus-one one) (a/mul R (a/exponentiation-by-squaring R ψ δ) a))] (if (polynomial-zero? p) nil (cons p (lazy-seq (step pr p δ ψ β)))))) (lazy-seq (cons u (cons v (if (< δ0 0) (step v u (- δ0) one ψ0) (step u v δ0 one ψ0))))))) (defn univariate-subresultant-gcd [u v] (let [R (compatible-ring u v) prs (if (> (degree u) (degree v)) (subresultant-polynomial-remainder-sequence u v) (subresultant-polynomial-remainder-sequence v u)) g (last prs)] (if (zero? (degree g)) (->Polynomial R 1 (conj empty-coefficients [[0] (a/multiplicative-identity R)])) g))) (defn univariate-euclid-gcd [u v] (if (polynomial-zero? v) u (recur v (univariate-primitive-part (zippel-pseudo-remainder u v))))) (defn pseudo-remainder-sequence [remainder] (fn step [u v] (if (polynomial-zero? v) (list u) (lazy-seq (cons u (step v (remainder u v))))))) (defn ^:private abs [^Polynomial p] (let [R (.ring p)] (if (a/cmp R p (a/additive-identity R)) (polynomial-negate p) p))) (defn partial-derivative "The partial derivative of the polynomial with respect to the i-th indeterminate." [^Polynomial p i] (let [R (.ring p)] (polynomial-make (.ring p) (.arity p) (for [[xs c] (.terms p) :let [xi (xs i)] :when (not= 0 xi)] [(update xs i dec) (a/mul R xi c)])))) (defn partial-derivatives "The sequence of partial derivatives of p with respect to each indeterminate" [^Polynomial p] (for [i (range (.arity p))] (partial-derivative p i))) (def ^:private log2e (/ (Math/log 2))) (defn ^:private log2 [x] (* (Math/log x) log2e)) (def ^:private small-odd-primes [ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 ]) (defn small-primes-modular-univariate-gcd "[GG13] Algorithm 6.38" [u v] (let [R (compatible-ring u v) u (univariate-primitive-part u) v (univariate-primitive-part v) n (degree u) ;; XXX: alg. wants deg f >= deg g >= 1 A (reduce max (map coefficient (concat (:terms u) (:terms v)))) b (a/euclid-gcd R (coefficient (lead-term u)) (coefficient (lead-term v))) k (Math/ceil (+ (* n (log2 (inc n))) (log2 b) (* 2 n (log2 A)))) B (* (Math/sqrt (inc n)) (Math/pow 2 n) A b) l (Math/ceil (log2 (inc (* 2 B)))) L (* 2 k (Math/log k)) ;; step 3: choose a set S of 2l primes, each less than 2k ln k ;; The first part of step 4 drops all primes that divide b from ;; S. We coalesce these operations into one step. ps (take (* 2 l) (filter #(not= 0 (mod b %)) small-odd-primes)) prime-rings (map a/->Zmod ps) ubars (map #(fmap u % (fn [c] (mod c (:n %)))) prime-rings) vbars (map #(fmap v % (fn [c] (mod c (:n %)))) prime-rings) gs (map univariate-euclid-gcd ubars vbars)] [A b k B l L] (println "u" u) (println "v" v) (println "ps" ps) (println "ubars" ubars) (println "vbars" vbars) (println "gs" gs)))
[ { "context": "db :as rf-db])\n (swap! rf-db/app-db assoc :name \"Some name\")\n (deref rf-db/app-db))\n", "end": 1028, "score": 0.9068663120269775, "start": 1019, "tag": "NAME", "value": "Some name" } ]
src/medbook/ui/events.cljs
abogoyavlensky/medbook
0
(ns medbook.ui.events (:require [re-frame.core :as re-frame] [reitit.frontend.controllers :as reitit-controllers] [reitit.frontend.easy :as reitit-easy] [medbook.ui.db :as db])) (re-frame/reg-event-db ::initialize-db (fn [_ _] db/default-db)) (re-frame/reg-event-db ::navigate (fn [db [_ new-match]] (let [old-match (:current-page db) controllers (reitit-controllers/apply-controllers (:controllers old-match) new-match)] (assoc db :current-page (assoc new-match :controllers controllers))))) (re-frame/reg-fx :fx/push-state (fn [{:keys [route]}] (reitit-easy/push-state route))) (re-frame/reg-event-db ::clear-info-message (fn [db [_ _]] (assoc db :info-message nil))) (re-frame/reg-event-db ::clear-error-message (fn [db [_ _]] (assoc db :error-message nil))) ;; Inspect app-db state (comment (require '[re-frame.db :as rf-db]) (swap! rf-db/app-db assoc :name "Some name") (deref rf-db/app-db))
42190
(ns medbook.ui.events (:require [re-frame.core :as re-frame] [reitit.frontend.controllers :as reitit-controllers] [reitit.frontend.easy :as reitit-easy] [medbook.ui.db :as db])) (re-frame/reg-event-db ::initialize-db (fn [_ _] db/default-db)) (re-frame/reg-event-db ::navigate (fn [db [_ new-match]] (let [old-match (:current-page db) controllers (reitit-controllers/apply-controllers (:controllers old-match) new-match)] (assoc db :current-page (assoc new-match :controllers controllers))))) (re-frame/reg-fx :fx/push-state (fn [{:keys [route]}] (reitit-easy/push-state route))) (re-frame/reg-event-db ::clear-info-message (fn [db [_ _]] (assoc db :info-message nil))) (re-frame/reg-event-db ::clear-error-message (fn [db [_ _]] (assoc db :error-message nil))) ;; Inspect app-db state (comment (require '[re-frame.db :as rf-db]) (swap! rf-db/app-db assoc :name "<NAME>") (deref rf-db/app-db))
true
(ns medbook.ui.events (:require [re-frame.core :as re-frame] [reitit.frontend.controllers :as reitit-controllers] [reitit.frontend.easy :as reitit-easy] [medbook.ui.db :as db])) (re-frame/reg-event-db ::initialize-db (fn [_ _] db/default-db)) (re-frame/reg-event-db ::navigate (fn [db [_ new-match]] (let [old-match (:current-page db) controllers (reitit-controllers/apply-controllers (:controllers old-match) new-match)] (assoc db :current-page (assoc new-match :controllers controllers))))) (re-frame/reg-fx :fx/push-state (fn [{:keys [route]}] (reitit-easy/push-state route))) (re-frame/reg-event-db ::clear-info-message (fn [db [_ _]] (assoc db :info-message nil))) (re-frame/reg-event-db ::clear-error-message (fn [db [_ _]] (assoc db :error-message nil))) ;; Inspect app-db state (comment (require '[re-frame.db :as rf-db]) (swap! rf-db/app-db assoc :name "PI:NAME:<NAME>END_PI") (deref rf-db/app-db))
[ { "context": "-key (format \"./test-resources/ssl/private_keys/%s.pem\" certname)\n ca-cert \"./test-resources/", "end": 1546, "score": 0.6863986849784851, "start": 1543, "tag": "KEY", "value": "pem" } ]
test/utils/puppetlabs/pcp/testutils/client.clj
rileynewton/pcp-broker
6
(ns puppetlabs.pcp.testutils.client (:require [clojure.test :refer :all] [puppetlabs.pcp.broker.message :as message] [clojure.core.async :as async :refer [timeout alts!! chan >!! <!! put!]] [http.async.client :as http] [puppetlabs.pcp.message-v1 :as m1] [puppetlabs.pcp.message-v2 :as m2] [puppetlabs.ssl-utils.core :as ssl-utils])) ;; A simple websockets client with some assertions - for non-testing uses use pcp-client. (defprotocol WsClient (close [_]) (sendbytes! [_ bytes]) (send! [_ message]) (recv! [_] [_ timeout] "Returns nil on timeout, [code reason] on close, message/Message on message") (connected? [_])) (defrecord ChanClient [http-client ws-client message-channel] WsClient (close [_] (async/close! message-channel) (.close ws-client) (.close http-client)) (sendbytes! [_ bytes] (http/send ws-client :byte bytes)) (send! [_ message] (let [version (if (:_chunks message) :v1 :v2)] (if (= version :v1) (http/send ws-client :byte (m1/encode message)) (http/send ws-client :text (m2/encode message))))) (recv! [this] (recv! this (* 10 5 1000))) (recv! [_ timeout-ms] (let [[message channel] (alts!! [message-channel (timeout timeout-ms)])] message)) (connected? [_] (.isOpen ws-client))) (defn http-client-with-cert [certname] (let [cert (format "./test-resources/ssl/certs/%s.pem" certname) private-key (format "./test-resources/ssl/private_keys/%s.pem" certname) ca-cert "./test-resources/ssl/ca/ca_crt.pem" ssl-context (ssl-utils/pems->ssl-context cert private-key ca-cert)] (http/create-client :ssl-context ssl-context))) (defn make-message ([options] (make-message "v2.0" options)) ([version options] (let [msg (m2/make-message options)] (if (= version "v1.0") (message/v2->v1 msg) msg)))) (defn get-data ([message] (get-data message "v2.0")) ([message version] (if (= version "v1.0") (m1/get-json-data message) (m2/get-data message)))) (defn make-association-request [uri version] (make-message version {:message_type "http://puppetlabs.com/associate_request" :target "pcp:///server" :sender uri})) (defn connect "Makes a client for testing" [& {:keys [certname type uri version modify-association check-association force-association modify-association-encoding] :or {modify-association identity modify-association-encoding identity check-association true force-association false type "agent" version "v2.0"}}] (let [uri (or uri (str "pcp://" certname "/" type)) association-request (modify-association (make-association-request uri version)) client (http-client-with-cert certname) message-chan (chan) ws (if (= "v1.0" version) (http/websocket client (str "wss://localhost:58142/pcp/" version "/") :open (fn [ws] (http/send ws :byte (modify-association-encoding (m1/encode association-request)))) :error (fn [ws e] (throw (Exception. e))) :byte (fn [ws msg] (put! message-chan (m1/decode msg))) :close (fn [ws code reason] (put! message-chan [code reason]))) (http/websocket client (str "wss://localhost:58142/pcp/" version "/" type) :open (fn [ws] (when force-association (http/send ws :text (modify-association-encoding (m2/encode association-request))))) :error (fn [ws e] (throw (Exception. e))) :text (fn [ws msg] (put! message-chan (m2/decode msg))) :close (fn [ws code reason] (put! message-chan [code reason])))) wrapper (when ws (ChanClient. client ws message-chan))] ;; session association messages are normally only used in PCP v1 (when (and wrapper (or (= "v1.0" version) force-association) check-association) (let [response (recv! wrapper)] (is (= "http://puppetlabs.com/associate_response" (:message_type response))) (is (= (case version "v1.0" nil (:id association-request)) (:in_reply_to response))) (is (= {:id (:id association-request) :success true} (case version "v1.0" (m1/get-json-data response) (m2/get-data response)))))) wrapper))
25839
(ns puppetlabs.pcp.testutils.client (:require [clojure.test :refer :all] [puppetlabs.pcp.broker.message :as message] [clojure.core.async :as async :refer [timeout alts!! chan >!! <!! put!]] [http.async.client :as http] [puppetlabs.pcp.message-v1 :as m1] [puppetlabs.pcp.message-v2 :as m2] [puppetlabs.ssl-utils.core :as ssl-utils])) ;; A simple websockets client with some assertions - for non-testing uses use pcp-client. (defprotocol WsClient (close [_]) (sendbytes! [_ bytes]) (send! [_ message]) (recv! [_] [_ timeout] "Returns nil on timeout, [code reason] on close, message/Message on message") (connected? [_])) (defrecord ChanClient [http-client ws-client message-channel] WsClient (close [_] (async/close! message-channel) (.close ws-client) (.close http-client)) (sendbytes! [_ bytes] (http/send ws-client :byte bytes)) (send! [_ message] (let [version (if (:_chunks message) :v1 :v2)] (if (= version :v1) (http/send ws-client :byte (m1/encode message)) (http/send ws-client :text (m2/encode message))))) (recv! [this] (recv! this (* 10 5 1000))) (recv! [_ timeout-ms] (let [[message channel] (alts!! [message-channel (timeout timeout-ms)])] message)) (connected? [_] (.isOpen ws-client))) (defn http-client-with-cert [certname] (let [cert (format "./test-resources/ssl/certs/%s.pem" certname) private-key (format "./test-resources/ssl/private_keys/%s.<KEY>" certname) ca-cert "./test-resources/ssl/ca/ca_crt.pem" ssl-context (ssl-utils/pems->ssl-context cert private-key ca-cert)] (http/create-client :ssl-context ssl-context))) (defn make-message ([options] (make-message "v2.0" options)) ([version options] (let [msg (m2/make-message options)] (if (= version "v1.0") (message/v2->v1 msg) msg)))) (defn get-data ([message] (get-data message "v2.0")) ([message version] (if (= version "v1.0") (m1/get-json-data message) (m2/get-data message)))) (defn make-association-request [uri version] (make-message version {:message_type "http://puppetlabs.com/associate_request" :target "pcp:///server" :sender uri})) (defn connect "Makes a client for testing" [& {:keys [certname type uri version modify-association check-association force-association modify-association-encoding] :or {modify-association identity modify-association-encoding identity check-association true force-association false type "agent" version "v2.0"}}] (let [uri (or uri (str "pcp://" certname "/" type)) association-request (modify-association (make-association-request uri version)) client (http-client-with-cert certname) message-chan (chan) ws (if (= "v1.0" version) (http/websocket client (str "wss://localhost:58142/pcp/" version "/") :open (fn [ws] (http/send ws :byte (modify-association-encoding (m1/encode association-request)))) :error (fn [ws e] (throw (Exception. e))) :byte (fn [ws msg] (put! message-chan (m1/decode msg))) :close (fn [ws code reason] (put! message-chan [code reason]))) (http/websocket client (str "wss://localhost:58142/pcp/" version "/" type) :open (fn [ws] (when force-association (http/send ws :text (modify-association-encoding (m2/encode association-request))))) :error (fn [ws e] (throw (Exception. e))) :text (fn [ws msg] (put! message-chan (m2/decode msg))) :close (fn [ws code reason] (put! message-chan [code reason])))) wrapper (when ws (ChanClient. client ws message-chan))] ;; session association messages are normally only used in PCP v1 (when (and wrapper (or (= "v1.0" version) force-association) check-association) (let [response (recv! wrapper)] (is (= "http://puppetlabs.com/associate_response" (:message_type response))) (is (= (case version "v1.0" nil (:id association-request)) (:in_reply_to response))) (is (= {:id (:id association-request) :success true} (case version "v1.0" (m1/get-json-data response) (m2/get-data response)))))) wrapper))
true
(ns puppetlabs.pcp.testutils.client (:require [clojure.test :refer :all] [puppetlabs.pcp.broker.message :as message] [clojure.core.async :as async :refer [timeout alts!! chan >!! <!! put!]] [http.async.client :as http] [puppetlabs.pcp.message-v1 :as m1] [puppetlabs.pcp.message-v2 :as m2] [puppetlabs.ssl-utils.core :as ssl-utils])) ;; A simple websockets client with some assertions - for non-testing uses use pcp-client. (defprotocol WsClient (close [_]) (sendbytes! [_ bytes]) (send! [_ message]) (recv! [_] [_ timeout] "Returns nil on timeout, [code reason] on close, message/Message on message") (connected? [_])) (defrecord ChanClient [http-client ws-client message-channel] WsClient (close [_] (async/close! message-channel) (.close ws-client) (.close http-client)) (sendbytes! [_ bytes] (http/send ws-client :byte bytes)) (send! [_ message] (let [version (if (:_chunks message) :v1 :v2)] (if (= version :v1) (http/send ws-client :byte (m1/encode message)) (http/send ws-client :text (m2/encode message))))) (recv! [this] (recv! this (* 10 5 1000))) (recv! [_ timeout-ms] (let [[message channel] (alts!! [message-channel (timeout timeout-ms)])] message)) (connected? [_] (.isOpen ws-client))) (defn http-client-with-cert [certname] (let [cert (format "./test-resources/ssl/certs/%s.pem" certname) private-key (format "./test-resources/ssl/private_keys/%s.PI:KEY:<KEY>END_PI" certname) ca-cert "./test-resources/ssl/ca/ca_crt.pem" ssl-context (ssl-utils/pems->ssl-context cert private-key ca-cert)] (http/create-client :ssl-context ssl-context))) (defn make-message ([options] (make-message "v2.0" options)) ([version options] (let [msg (m2/make-message options)] (if (= version "v1.0") (message/v2->v1 msg) msg)))) (defn get-data ([message] (get-data message "v2.0")) ([message version] (if (= version "v1.0") (m1/get-json-data message) (m2/get-data message)))) (defn make-association-request [uri version] (make-message version {:message_type "http://puppetlabs.com/associate_request" :target "pcp:///server" :sender uri})) (defn connect "Makes a client for testing" [& {:keys [certname type uri version modify-association check-association force-association modify-association-encoding] :or {modify-association identity modify-association-encoding identity check-association true force-association false type "agent" version "v2.0"}}] (let [uri (or uri (str "pcp://" certname "/" type)) association-request (modify-association (make-association-request uri version)) client (http-client-with-cert certname) message-chan (chan) ws (if (= "v1.0" version) (http/websocket client (str "wss://localhost:58142/pcp/" version "/") :open (fn [ws] (http/send ws :byte (modify-association-encoding (m1/encode association-request)))) :error (fn [ws e] (throw (Exception. e))) :byte (fn [ws msg] (put! message-chan (m1/decode msg))) :close (fn [ws code reason] (put! message-chan [code reason]))) (http/websocket client (str "wss://localhost:58142/pcp/" version "/" type) :open (fn [ws] (when force-association (http/send ws :text (modify-association-encoding (m2/encode association-request))))) :error (fn [ws e] (throw (Exception. e))) :text (fn [ws msg] (put! message-chan (m2/decode msg))) :close (fn [ws code reason] (put! message-chan [code reason])))) wrapper (when ws (ChanClient. client ws message-chan))] ;; session association messages are normally only used in PCP v1 (when (and wrapper (or (= "v1.0" version) force-association) check-association) (let [response (recv! wrapper)] (is (= "http://puppetlabs.com/associate_response" (:message_type response))) (is (= (case version "v1.0" nil (:id association-request)) (:in_reply_to response))) (is (= {:id (:id association-request) :success true} (case version "v1.0" (m1/get-json-data response) (m2/get-data response)))))) wrapper))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 30, "score": 0.999846339225769, "start": 19, "tag": "NAME", "value": "Rich Hickey" }, { "context": "ice, or any other, from this software.\n\n;; Author: Tassilo Horn\n\n(ns clojure.test-clojure.reducers\n (:require [c", "end": 488, "score": 0.9998849630355835, "start": 476, "tag": "NAME", "value": "Tassilo Horn" } ]
Clojure/clojure/test_clojure/reducers.clj
AydarLukmanov/ArcadiaGodot
123
; 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: Tassilo Horn (ns clojure.test-clojure.reducers (:require [clojure.core.reducers :as r] [clojure.test.generative :refer (defspec)] [clojure.data.generators :as gen]) (:use clojure.test)) (defmacro defequivtest ;; f is the core fn, r is the reducers equivalent, rt is the reducible -> ;; coll transformer [name [f r rt] fns] `(deftest ~name (let [c# (range -100 1000)] (doseq [fn# ~fns] (is (= (~f fn# c#) (~rt (~r fn# c#)))))))) (defequivtest test-map [map r/map #(into [] %)] [inc dec #(Math/Sqrt (Math/Abs %))]) ;;; Math/sqrt Math/abs (defequivtest test-mapcat [mapcat r/mapcat #(into [] %)] [(fn [x] [x]) (fn [x] [x (inc x)]) (fn [x] [x (inc x) x])]) (deftest test-mapcat-obeys-reduced (is (= [1 "0" 2 "1" 3] (->> (concat (range 100) (lazy-seq (throw (Exception. "Too eager")))) (r/mapcat (juxt inc str)) (r/take 5) (into []))))) (defequivtest test-reduce [reduce r/reduce identity] [+' *']) (defequivtest test-filter [filter r/filter #(into [] %)] [even? odd? #(< 200 %) identity]) (deftest test-sorted-maps (let [m (into (sorted-map) '{1 a, 2 b, 3 c, 4 d})] (is (= "1a2b3c4d" (reduce-kv str "" m)) "Sorted maps should reduce-kv in sorted order") (is (= 1 (reduce-kv (fn [acc k v] (reduced (+ acc k))) 0 m)) "Sorted maps should stop reduction when asked"))) (deftest test-nil (is (= {:k :v} (reduce-kv assoc {:k :v} nil))) (is (= 0 (r/fold + nil)))) (defn gen-num [] (gen/uniform 0 2000)) (defn reduced-at-probe [m p] (reduce-kv (fn [_ k v] (when (== p k) (reduced :foo))) nil m)) (defspec reduced-always-returns (fn [probe to-end] (let [len (+ probe to-end 1) nums (range len) m (zipmap nums nums)] (reduced-at-probe m probe))) [^{:tag `gen-num} probe ^{:tag `gen-num} to-end] (assert (= :foo %))) (deftest test-fold-runtime-exception (is (thrown? System.Exception ;;; IndexOutOfBoundsException - this would be an AggregateException in 4.0, something else in 3.5 (let [test-map-count 1234 k-fail (rand-int test-map-count)] (r/fold (fn ([]) ([ret [k v]]) ([ret k v] (when (= k k-fail) (throw (IndexOutOfRangeException.))))) ;;; IndexOutOfBoundsException (zipmap (range test-map-count) (repeat :dummy))))))) #_(deftest test-closed-over-clearing ;;; Temporarily disable to speed up testing -- SEE CLJCLR-96 ;; this will throw OutOfMemory without proper reference clearing (is (number? (reduce + 0 (r/map identity (range 1e8))))))
72737
; 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> (ns clojure.test-clojure.reducers (:require [clojure.core.reducers :as r] [clojure.test.generative :refer (defspec)] [clojure.data.generators :as gen]) (:use clojure.test)) (defmacro defequivtest ;; f is the core fn, r is the reducers equivalent, rt is the reducible -> ;; coll transformer [name [f r rt] fns] `(deftest ~name (let [c# (range -100 1000)] (doseq [fn# ~fns] (is (= (~f fn# c#) (~rt (~r fn# c#)))))))) (defequivtest test-map [map r/map #(into [] %)] [inc dec #(Math/Sqrt (Math/Abs %))]) ;;; Math/sqrt Math/abs (defequivtest test-mapcat [mapcat r/mapcat #(into [] %)] [(fn [x] [x]) (fn [x] [x (inc x)]) (fn [x] [x (inc x) x])]) (deftest test-mapcat-obeys-reduced (is (= [1 "0" 2 "1" 3] (->> (concat (range 100) (lazy-seq (throw (Exception. "Too eager")))) (r/mapcat (juxt inc str)) (r/take 5) (into []))))) (defequivtest test-reduce [reduce r/reduce identity] [+' *']) (defequivtest test-filter [filter r/filter #(into [] %)] [even? odd? #(< 200 %) identity]) (deftest test-sorted-maps (let [m (into (sorted-map) '{1 a, 2 b, 3 c, 4 d})] (is (= "1a2b3c4d" (reduce-kv str "" m)) "Sorted maps should reduce-kv in sorted order") (is (= 1 (reduce-kv (fn [acc k v] (reduced (+ acc k))) 0 m)) "Sorted maps should stop reduction when asked"))) (deftest test-nil (is (= {:k :v} (reduce-kv assoc {:k :v} nil))) (is (= 0 (r/fold + nil)))) (defn gen-num [] (gen/uniform 0 2000)) (defn reduced-at-probe [m p] (reduce-kv (fn [_ k v] (when (== p k) (reduced :foo))) nil m)) (defspec reduced-always-returns (fn [probe to-end] (let [len (+ probe to-end 1) nums (range len) m (zipmap nums nums)] (reduced-at-probe m probe))) [^{:tag `gen-num} probe ^{:tag `gen-num} to-end] (assert (= :foo %))) (deftest test-fold-runtime-exception (is (thrown? System.Exception ;;; IndexOutOfBoundsException - this would be an AggregateException in 4.0, something else in 3.5 (let [test-map-count 1234 k-fail (rand-int test-map-count)] (r/fold (fn ([]) ([ret [k v]]) ([ret k v] (when (= k k-fail) (throw (IndexOutOfRangeException.))))) ;;; IndexOutOfBoundsException (zipmap (range test-map-count) (repeat :dummy))))))) #_(deftest test-closed-over-clearing ;;; Temporarily disable to speed up testing -- SEE CLJCLR-96 ;; this will throw OutOfMemory without proper reference clearing (is (number? (reduce + 0 (r/map identity (range 1e8))))))
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. ;; Author: PI:NAME:<NAME>END_PI (ns clojure.test-clojure.reducers (:require [clojure.core.reducers :as r] [clojure.test.generative :refer (defspec)] [clojure.data.generators :as gen]) (:use clojure.test)) (defmacro defequivtest ;; f is the core fn, r is the reducers equivalent, rt is the reducible -> ;; coll transformer [name [f r rt] fns] `(deftest ~name (let [c# (range -100 1000)] (doseq [fn# ~fns] (is (= (~f fn# c#) (~rt (~r fn# c#)))))))) (defequivtest test-map [map r/map #(into [] %)] [inc dec #(Math/Sqrt (Math/Abs %))]) ;;; Math/sqrt Math/abs (defequivtest test-mapcat [mapcat r/mapcat #(into [] %)] [(fn [x] [x]) (fn [x] [x (inc x)]) (fn [x] [x (inc x) x])]) (deftest test-mapcat-obeys-reduced (is (= [1 "0" 2 "1" 3] (->> (concat (range 100) (lazy-seq (throw (Exception. "Too eager")))) (r/mapcat (juxt inc str)) (r/take 5) (into []))))) (defequivtest test-reduce [reduce r/reduce identity] [+' *']) (defequivtest test-filter [filter r/filter #(into [] %)] [even? odd? #(< 200 %) identity]) (deftest test-sorted-maps (let [m (into (sorted-map) '{1 a, 2 b, 3 c, 4 d})] (is (= "1a2b3c4d" (reduce-kv str "" m)) "Sorted maps should reduce-kv in sorted order") (is (= 1 (reduce-kv (fn [acc k v] (reduced (+ acc k))) 0 m)) "Sorted maps should stop reduction when asked"))) (deftest test-nil (is (= {:k :v} (reduce-kv assoc {:k :v} nil))) (is (= 0 (r/fold + nil)))) (defn gen-num [] (gen/uniform 0 2000)) (defn reduced-at-probe [m p] (reduce-kv (fn [_ k v] (when (== p k) (reduced :foo))) nil m)) (defspec reduced-always-returns (fn [probe to-end] (let [len (+ probe to-end 1) nums (range len) m (zipmap nums nums)] (reduced-at-probe m probe))) [^{:tag `gen-num} probe ^{:tag `gen-num} to-end] (assert (= :foo %))) (deftest test-fold-runtime-exception (is (thrown? System.Exception ;;; IndexOutOfBoundsException - this would be an AggregateException in 4.0, something else in 3.5 (let [test-map-count 1234 k-fail (rand-int test-map-count)] (r/fold (fn ([]) ([ret [k v]]) ([ret k v] (when (= k k-fail) (throw (IndexOutOfRangeException.))))) ;;; IndexOutOfBoundsException (zipmap (range test-map-count) (repeat :dummy))))))) #_(deftest test-closed-over-clearing ;;; Temporarily disable to speed up testing -- SEE CLJCLR-96 ;; this will throw OutOfMemory without proper reference clearing (is (number? (reduce + 0 (r/map identity (range 1e8))))))
[ { "context": "ion was provided\n on the clojure mailing list by Alistair Roche.)\"\n [& {:keys [req req-un opt opt-un] :as args}]", "end": 1350, "score": 0.9998852610588074, "start": 1336, "tag": "NAME", "value": "Alistair Roche" } ]
code/src/sixsq/nuvla/server/util/spec.cljc
nuvla/server
6
(ns sixsq.nuvla.server.util.spec "Utilities that provide common spec definition patterns that aren't supported directly by the core spec functions and macros." (:require [clojure.set :as set] [clojure.spec.alpha :as s] [spec-tools.impl :as impl] [spec-tools.json-schema :as jsc] [spec-tools.parse :as st-parse] [spec-tools.visitor :as visitor])) (def ^:private all-ascii-chars (map str (map char (range 0 256)))) (defn regex-chars "Provides a list of ASCII characters that satisfy the regex pattern." [pattern] (set (filter #(re-matches pattern %) all-ascii-chars))) (defn merge-kw-lists "Merges two lists (or seqs) of namespaced keywords. The results will be a sorted vector with duplicates removed." [kws1 kws2] (vec (sort (set/union (set kws1) (set kws2))))) (defn merge-keys-specs "Merges the given clojure.spec/keys specs provided as a list of maps. All the arguments are eval'ed and must evaluate to map constants." [map-specs] (->> map-specs (map eval) (apply merge-with merge-kw-lists))) (defmacro only-keys "Creates a closed map definition where only the defined keys are permitted. The arguments must be literals, using the same function signature as clojure.spec/keys. (This implementation was provided on the clojure mailing list by Alistair Roche.)" [& {:keys [req req-un opt opt-un] :as args}] `(s/merge (s/keys ~@(apply concat (vec args))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?))) (defmacro only-keys-maps "Creates a closed map definition from one or more maps that contain key specifications as for clojure.spec/keys. All of the arguments are eval'ed, so they may be vars containing the definition(s). All of the arguments must evaluate to compile-time map constants." [& map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/keys ~@(apply concat (vec map-spec))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?)))) (defmacro constrained-map "Creates an open map spec using the supplied keys specs with the additional constraint that all unspecified entries must match the given key and value specs. The keys specs will be evaluated." [key-spec value-spec & map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/every (s/or :attrs (s/tuple ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?) :link (s/tuple ~key-spec ~value-spec))) (s/keys ~@(apply concat (vec map-spec)))))) ;; ;; spec parsing patches ;; (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys form options)) (defn transform-form [[spec-name & keys-specs]] (->> keys-specs (merge-keys-specs) (apply concat) (cons spec-name))) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys (transform-form form) options)) (defn transform-as-every [[spec-name key-spec value-spec & _]] [[spec-name key-spec value-spec]]) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/every (transform-as-every form) options)) ;; ;; patches for spec walking via visitor ;; (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys [spec accept options] (let [keys (impl/extract-keys (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/only-keys spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [spec accept options] (let [keys (impl/extract-keys (transform-form (impl/extract-form spec)))] (accept 'sixsq.nuvla.server.util.spec/only-keys-maps spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/constrained-map [spec accept options] (let [[_ inner-spec] (transform-as-every (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/constrained-map spec [(visitor/visit inner-spec accept options)] options))) ;; accept-spec monkey patches (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (jsc/accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_ spec children _] (let [{:keys [req req-un opt opt-un]} (impl/parse-keys (transform-form (impl/extract-form spec))) names-un (map name (concat req-un opt-un)) names (map impl/qualified-name (concat req opt)) required (map impl/qualified-name req) required-un (map name req-un) all-required (not-empty (concat required required-un))] (#'jsc/maybe-with-title (merge {:type "object" :properties (zipmap (concat names names-un) children)} (when all-required {:required (vec all-required)})) spec nil))) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_ spec children _] (#'jsc/maybe-with-title {:type "object", :additionalProperties (impl/unwrap children)} spec nil)) ;; ;; patch transform of spec into ES mapping ;; (defn- spec-dispatch [dispatch _ _ _] dispatch) (defmulti accept-spec spec-dispatch :default ::default) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg))
27207
(ns sixsq.nuvla.server.util.spec "Utilities that provide common spec definition patterns that aren't supported directly by the core spec functions and macros." (:require [clojure.set :as set] [clojure.spec.alpha :as s] [spec-tools.impl :as impl] [spec-tools.json-schema :as jsc] [spec-tools.parse :as st-parse] [spec-tools.visitor :as visitor])) (def ^:private all-ascii-chars (map str (map char (range 0 256)))) (defn regex-chars "Provides a list of ASCII characters that satisfy the regex pattern." [pattern] (set (filter #(re-matches pattern %) all-ascii-chars))) (defn merge-kw-lists "Merges two lists (or seqs) of namespaced keywords. The results will be a sorted vector with duplicates removed." [kws1 kws2] (vec (sort (set/union (set kws1) (set kws2))))) (defn merge-keys-specs "Merges the given clojure.spec/keys specs provided as a list of maps. All the arguments are eval'ed and must evaluate to map constants." [map-specs] (->> map-specs (map eval) (apply merge-with merge-kw-lists))) (defmacro only-keys "Creates a closed map definition where only the defined keys are permitted. The arguments must be literals, using the same function signature as clojure.spec/keys. (This implementation was provided on the clojure mailing list by <NAME>.)" [& {:keys [req req-un opt opt-un] :as args}] `(s/merge (s/keys ~@(apply concat (vec args))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?))) (defmacro only-keys-maps "Creates a closed map definition from one or more maps that contain key specifications as for clojure.spec/keys. All of the arguments are eval'ed, so they may be vars containing the definition(s). All of the arguments must evaluate to compile-time map constants." [& map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/keys ~@(apply concat (vec map-spec))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?)))) (defmacro constrained-map "Creates an open map spec using the supplied keys specs with the additional constraint that all unspecified entries must match the given key and value specs. The keys specs will be evaluated." [key-spec value-spec & map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/every (s/or :attrs (s/tuple ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?) :link (s/tuple ~key-spec ~value-spec))) (s/keys ~@(apply concat (vec map-spec)))))) ;; ;; spec parsing patches ;; (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys form options)) (defn transform-form [[spec-name & keys-specs]] (->> keys-specs (merge-keys-specs) (apply concat) (cons spec-name))) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys (transform-form form) options)) (defn transform-as-every [[spec-name key-spec value-spec & _]] [[spec-name key-spec value-spec]]) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/every (transform-as-every form) options)) ;; ;; patches for spec walking via visitor ;; (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys [spec accept options] (let [keys (impl/extract-keys (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/only-keys spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [spec accept options] (let [keys (impl/extract-keys (transform-form (impl/extract-form spec)))] (accept 'sixsq.nuvla.server.util.spec/only-keys-maps spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/constrained-map [spec accept options] (let [[_ inner-spec] (transform-as-every (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/constrained-map spec [(visitor/visit inner-spec accept options)] options))) ;; accept-spec monkey patches (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (jsc/accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_ spec children _] (let [{:keys [req req-un opt opt-un]} (impl/parse-keys (transform-form (impl/extract-form spec))) names-un (map name (concat req-un opt-un)) names (map impl/qualified-name (concat req opt)) required (map impl/qualified-name req) required-un (map name req-un) all-required (not-empty (concat required required-un))] (#'jsc/maybe-with-title (merge {:type "object" :properties (zipmap (concat names names-un) children)} (when all-required {:required (vec all-required)})) spec nil))) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_ spec children _] (#'jsc/maybe-with-title {:type "object", :additionalProperties (impl/unwrap children)} spec nil)) ;; ;; patch transform of spec into ES mapping ;; (defn- spec-dispatch [dispatch _ _ _] dispatch) (defmulti accept-spec spec-dispatch :default ::default) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg))
true
(ns sixsq.nuvla.server.util.spec "Utilities that provide common spec definition patterns that aren't supported directly by the core spec functions and macros." (:require [clojure.set :as set] [clojure.spec.alpha :as s] [spec-tools.impl :as impl] [spec-tools.json-schema :as jsc] [spec-tools.parse :as st-parse] [spec-tools.visitor :as visitor])) (def ^:private all-ascii-chars (map str (map char (range 0 256)))) (defn regex-chars "Provides a list of ASCII characters that satisfy the regex pattern." [pattern] (set (filter #(re-matches pattern %) all-ascii-chars))) (defn merge-kw-lists "Merges two lists (or seqs) of namespaced keywords. The results will be a sorted vector with duplicates removed." [kws1 kws2] (vec (sort (set/union (set kws1) (set kws2))))) (defn merge-keys-specs "Merges the given clojure.spec/keys specs provided as a list of maps. All the arguments are eval'ed and must evaluate to map constants." [map-specs] (->> map-specs (map eval) (apply merge-with merge-kw-lists))) (defmacro only-keys "Creates a closed map definition where only the defined keys are permitted. The arguments must be literals, using the same function signature as clojure.spec/keys. (This implementation was provided on the clojure mailing list by PI:NAME:<NAME>END_PI.)" [& {:keys [req req-un opt opt-un] :as args}] `(s/merge (s/keys ~@(apply concat (vec args))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?))) (defmacro only-keys-maps "Creates a closed map definition from one or more maps that contain key specifications as for clojure.spec/keys. All of the arguments are eval'ed, so they may be vars containing the definition(s). All of the arguments must evaluate to compile-time map constants." [& map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/keys ~@(apply concat (vec map-spec))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?)))) (defmacro constrained-map "Creates an open map spec using the supplied keys specs with the additional constraint that all unspecified entries must match the given key and value specs. The keys specs will be evaluated." [key-spec value-spec & map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/every (s/or :attrs (s/tuple ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?) :link (s/tuple ~key-spec ~value-spec))) (s/keys ~@(apply concat (vec map-spec)))))) ;; ;; spec parsing patches ;; (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys form options)) (defn transform-form [[spec-name & keys-specs]] (->> keys-specs (merge-keys-specs) (apply concat) (cons spec-name))) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys (transform-form form) options)) (defn transform-as-every [[spec-name key-spec value-spec & _]] [[spec-name key-spec value-spec]]) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/every (transform-as-every form) options)) ;; ;; patches for spec walking via visitor ;; (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys [spec accept options] (let [keys (impl/extract-keys (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/only-keys spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [spec accept options] (let [keys (impl/extract-keys (transform-form (impl/extract-form spec)))] (accept 'sixsq.nuvla.server.util.spec/only-keys-maps spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/constrained-map [spec accept options] (let [[_ inner-spec] (transform-as-every (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/constrained-map spec [(visitor/visit inner-spec accept options)] options))) ;; accept-spec monkey patches (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (jsc/accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_ spec children _] (let [{:keys [req req-un opt opt-un]} (impl/parse-keys (transform-form (impl/extract-form spec))) names-un (map name (concat req-un opt-un)) names (map impl/qualified-name (concat req opt)) required (map impl/qualified-name req) required-un (map name req-un) all-required (not-empty (concat required required-un))] (#'jsc/maybe-with-title (merge {:type "object" :properties (zipmap (concat names names-un) children)} (when all-required {:required (vec all-required)})) spec nil))) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_ spec children _] (#'jsc/maybe-with-title {:type "object", :additionalProperties (impl/unwrap children)} spec nil)) ;; ;; patch transform of spec into ES mapping ;; (defn- spec-dispatch [dispatch _ _ _] dispatch) (defmulti accept-spec spec-dispatch :default ::default) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg))
[ { "context": "akes-blood-hunts? false, :has-pulse? true :name \"Paula\"}\n 1 {:makes-blood-hunts? false, :has-pulse? tr", "end": 120, "score": 0.999504566192627, "start": 115, "tag": "NAME", "value": "Paula" }, { "context": "akes-blood-hunts? false, :has-pulse? true :name \"Priscila\"}\n 2 {:makes-blood-hunts? true, :has-pulse? fa", "end": 189, "score": 0.9996364712715149, "start": 181, "tag": "NAME", "value": "Priscila" }, { "context": "akes-blood-hunts? true, :has-pulse? false :name \"Dracula\"}\n 3 {:makes-blood-hunts? true, :has-pulse? tr", "end": 257, "score": 0.9993517398834229, "start": 250, "tag": "NAME", "value": "Dracula" }, { "context": "akes-blood-hunts? true, :has-pulse? true :name \"Mickey Mouse\"}\n 4 {:makes-blood-hunts? true, :has-pulse? fa", "end": 330, "score": 0.99920254945755, "start": 318, "tag": "NAME", "value": "Mickey Mouse" }, { "context": "akes-blood-hunts? true, :has-pulse? false :name \"Lady Sith\"}\n 5 {:makes-blood-hunts? false, :has-pulse? f", "end": 400, "score": 0.9996969699859619, "start": 391, "tag": "NAME", "value": "Lady Sith" }, { "context": "kes-blood-hunts? false, :has-pulse? false :name \"Darth Vader\"}\n 6 {:makes-blood-hunts? true, :has-pulse? fa", "end": 473, "score": 0.9995759129524231, "start": 462, "tag": "NAME", "value": "Darth Vader" }, { "context": "akes-blood-hunts? true, :has-pulse? false :name \"Bloodpool\"}})\n\n(defn vampire-details\n [rg]\n (get vampire-", "end": 543, "score": 0.9903560876846313, "start": 534, "tag": "NAME", "value": "Bloodpool" } ]
vampires/src/vampires/core.clj
naomijub/Noobing
0
(ns vampires.core (:gen-class)) (def vampire-database {0 {:makes-blood-hunts? false, :has-pulse? true :name "Paula"} 1 {:makes-blood-hunts? false, :has-pulse? true :name "Priscila"} 2 {:makes-blood-hunts? true, :has-pulse? false :name "Dracula"} 3 {:makes-blood-hunts? true, :has-pulse? true :name "Mickey Mouse"} 4 {:makes-blood-hunts? true, :has-pulse? false :name "Lady Sith"} 5 {:makes-blood-hunts? false, :has-pulse? false :name "Darth Vader"} 6 {:makes-blood-hunts? true, :has-pulse? false :name "Bloodpool"}}) (defn vampire-details [rg] (get vampire-database rg)) (defn vampire? [person] (and (:makes-blood-hunts? person) (not (:has-pulse? person)) person)) (defn find-vampires [rg] (filter vampire? (map vampire-details rg))) (defn -main [& args] (def vamp-keys (keys vampire-database)) (println (find-vampires vamp-keys)))
108745
(ns vampires.core (:gen-class)) (def vampire-database {0 {:makes-blood-hunts? false, :has-pulse? true :name "<NAME>"} 1 {:makes-blood-hunts? false, :has-pulse? true :name "<NAME>"} 2 {:makes-blood-hunts? true, :has-pulse? false :name "<NAME>"} 3 {:makes-blood-hunts? true, :has-pulse? true :name "<NAME>"} 4 {:makes-blood-hunts? true, :has-pulse? false :name "<NAME>"} 5 {:makes-blood-hunts? false, :has-pulse? false :name "<NAME>"} 6 {:makes-blood-hunts? true, :has-pulse? false :name "<NAME>"}}) (defn vampire-details [rg] (get vampire-database rg)) (defn vampire? [person] (and (:makes-blood-hunts? person) (not (:has-pulse? person)) person)) (defn find-vampires [rg] (filter vampire? (map vampire-details rg))) (defn -main [& args] (def vamp-keys (keys vampire-database)) (println (find-vampires vamp-keys)))
true
(ns vampires.core (:gen-class)) (def vampire-database {0 {:makes-blood-hunts? false, :has-pulse? true :name "PI:NAME:<NAME>END_PI"} 1 {:makes-blood-hunts? false, :has-pulse? true :name "PI:NAME:<NAME>END_PI"} 2 {:makes-blood-hunts? true, :has-pulse? false :name "PI:NAME:<NAME>END_PI"} 3 {:makes-blood-hunts? true, :has-pulse? true :name "PI:NAME:<NAME>END_PI"} 4 {:makes-blood-hunts? true, :has-pulse? false :name "PI:NAME:<NAME>END_PI"} 5 {:makes-blood-hunts? false, :has-pulse? false :name "PI:NAME:<NAME>END_PI"} 6 {:makes-blood-hunts? true, :has-pulse? false :name "PI:NAME:<NAME>END_PI"}}) (defn vampire-details [rg] (get vampire-database rg)) (defn vampire? [person] (and (:makes-blood-hunts? person) (not (:has-pulse? person)) person)) (defn find-vampires [rg] (filter vampire? (map vampire-details rg))) (defn -main [& args] (def vamp-keys (keys vampire-database)) (println (find-vampires vamp-keys)))
[ { "context": "a.scroll)\n\n;; Copied from https://gist.github.com/jasich/21ab25db923e85e1252bed13cf65f0d8\n;; Copyright Jas", "end": 77, "score": 0.9992944002151489, "start": 71, "tag": "USERNAME", "value": "jasich" }, { "context": "sich/21ab25db923e85e1252bed13cf65f0d8\n;; Copyright Jason Sich\n\n(defn cur-doc-top []\n (+ (.. js/document -body ", "end": 134, "score": 0.9998735189437866, "start": 124, "tag": "NAME", "value": "Jason Sich" } ]
src/example/ymir/alpha/scroll.cljs
jonasemueller/ymir
1
(ns example.ymir.alpha.scroll) ;; Copied from https://gist.github.com/jasich/21ab25db923e85e1252bed13cf65f0d8 ;; Copyright Jason Sich (defn cur-doc-top [] (+ (.. js/document -body -scrollTop) (.. js/document -documentElement -scrollTop))) (defn element-top [elem top] (if (.-offsetParent elem) (let [client-top (or (.-clientTop elem) 0) offset-top (.-offsetTop elem)] (+ top client-top offset-top (element-top (.-offsetParent elem) top))) top)) (defn to-id ([elem-id] (to-id elem-id 500 15)) ([elem-id speed moving-frequency] (let [elem (.getElementById js/document elem-id) hop-count (/ speed moving-frequency) doc-top (cur-doc-top) gap (/ (- (element-top elem 0) doc-top) hop-count)] (doseq [i (range 1 (inc hop-count))] (let [hop-top-pos (* gap i) move-to (+ hop-top-pos doc-top) timeout (* moving-frequency i)] (.setTimeout js/window (fn [] (.scrollTo js/window 0 move-to)) timeout)))))) (defn jump-to-top [] (.scrollTo js/window 0 0))
743
(ns example.ymir.alpha.scroll) ;; Copied from https://gist.github.com/jasich/21ab25db923e85e1252bed13cf65f0d8 ;; Copyright <NAME> (defn cur-doc-top [] (+ (.. js/document -body -scrollTop) (.. js/document -documentElement -scrollTop))) (defn element-top [elem top] (if (.-offsetParent elem) (let [client-top (or (.-clientTop elem) 0) offset-top (.-offsetTop elem)] (+ top client-top offset-top (element-top (.-offsetParent elem) top))) top)) (defn to-id ([elem-id] (to-id elem-id 500 15)) ([elem-id speed moving-frequency] (let [elem (.getElementById js/document elem-id) hop-count (/ speed moving-frequency) doc-top (cur-doc-top) gap (/ (- (element-top elem 0) doc-top) hop-count)] (doseq [i (range 1 (inc hop-count))] (let [hop-top-pos (* gap i) move-to (+ hop-top-pos doc-top) timeout (* moving-frequency i)] (.setTimeout js/window (fn [] (.scrollTo js/window 0 move-to)) timeout)))))) (defn jump-to-top [] (.scrollTo js/window 0 0))
true
(ns example.ymir.alpha.scroll) ;; Copied from https://gist.github.com/jasich/21ab25db923e85e1252bed13cf65f0d8 ;; Copyright PI:NAME:<NAME>END_PI (defn cur-doc-top [] (+ (.. js/document -body -scrollTop) (.. js/document -documentElement -scrollTop))) (defn element-top [elem top] (if (.-offsetParent elem) (let [client-top (or (.-clientTop elem) 0) offset-top (.-offsetTop elem)] (+ top client-top offset-top (element-top (.-offsetParent elem) top))) top)) (defn to-id ([elem-id] (to-id elem-id 500 15)) ([elem-id speed moving-frequency] (let [elem (.getElementById js/document elem-id) hop-count (/ speed moving-frequency) doc-top (cur-doc-top) gap (/ (- (element-top elem 0) doc-top) hop-count)] (doseq [i (range 1 (inc hop-count))] (let [hop-top-pos (* gap i) move-to (+ hop-top-pos doc-top) timeout (* moving-frequency i)] (.setTimeout js/window (fn [] (.scrollTo js/window 0 move-to)) timeout)))))) (defn jump-to-top [] (.scrollTo js/window 0 0))
[ { "context": "user user\n :password password}}))\n\n(defn- make-replication-param\n [{:keys [net", "end": 744, "score": 0.9982033967971802, "start": 736, "tag": "PASSWORD", "value": "password" }, { "context": "rd]\n :or {port 9042 user \"cassandra\" password \"cassandra\"}}]\n (let [cluster (get-cluster host port user p", "end": 3512, "score": 0.9995836019515991, "start": 3503, "tag": "PASSWORD", "value": "cassandra" } ]
tools/scalar-schema/src/scalar_schema/cassandra.clj
y-taka-23/scalardb
0
(ns scalar-schema.cassandra (:require [clojure.tools.logging :as log] [scalar-schema.common :as common] [scalar-schema.protocols :as proto] [qbits.alia :as alia] [qbits.hayt :refer [->raw]] [qbits.hayt.dsl.clause :as clause] [qbits.hayt.dsl.statement :as statement])) (def ^:private compaction-strategies {"STCS" :SizeTieredCompactionStrategy "LCS" :LeveledCompactionStrategy "TWCS" :TimeWindowCompactionStrategy}) (defn- get-cluster [host port user password] (alia/cluster {:contact-points [host] :port port :jmx-reporting? false :credentials {:user user :password password}})) (defn- make-replication-param [{:keys [network-strategy replication-factor] :or {network-strategy "SimpleStrategy"}}] (condp = network-strategy "SimpleStrategy" {"class" "SimpleStrategy" "replication_factor" replication-factor} "NetworkTopologyStrategy" {"class" "NetworkTopologyStrategy" "dc1" replication-factor} ;; TODO: other DCs (throw (ex-info "Unknown topology strategy is specified." {:network-strategy network-strategy})))) (defn- create-database [session database options] (alia/execute session (statement/create-keyspace (keyword database) (clause/if-exists false) (clause/with {:replication (make-replication-param options)})))) (defn- key-set->vec [key-set] (reduce (fn [v k] (conj v (keyword k))) [] key-set)) (defn- make-key-array [schema] (into (conj [] (key-set->vec (:partition-key schema))) (key-set->vec (:clustering-key schema)))) (defn- make-column-definitions [schema] (-> (reduce-kv (fn [m c t] (assoc m (keyword c) (keyword t))) {} (:columns schema)) (assoc :primary-key (make-key-array schema)))) (defn create-table [session schema options] (let [keyspace (keyword (:database schema)) table (keyword (:table schema)) cs (compaction-strategies (:compaction-strategy schema "STCS"))] (create-database session (:database schema) options) (alia/execute session (->raw (statement/use-keyspace keyspace))) (alia/execute session (->raw (statement/create-table table (clause/if-exists false) (clause/column-definitions (make-column-definitions schema)) (clause/with {:compaction {:class cs}})))) (doseq [index (:secondary-index schema)] (alia/execute session (->raw (statement/create-index table index (clause/index-name (str (name table) \_ common/INDEX_NAME_PREFIX \_ index)) (clause/if-exists false))))))) (defn- delete-table [session schema] (alia/execute session (->raw (statement/drop-keyspace (:database schema) (clause/if-exists true))))) (defn make-cassandra-operator [{:keys [host port user password] :or {port 9042 user "cassandra" password "cassandra"}}] (let [cluster (get-cluster host port user password) session (alia/connect cluster)] (reify proto/IOperator (create-table [_ schema opts] (create-table session schema opts)) (delete-table [_ schema _] (delete-table session schema)) (close [_ _] (alia/shutdown session) (alia/shutdown cluster)))))
17050
(ns scalar-schema.cassandra (:require [clojure.tools.logging :as log] [scalar-schema.common :as common] [scalar-schema.protocols :as proto] [qbits.alia :as alia] [qbits.hayt :refer [->raw]] [qbits.hayt.dsl.clause :as clause] [qbits.hayt.dsl.statement :as statement])) (def ^:private compaction-strategies {"STCS" :SizeTieredCompactionStrategy "LCS" :LeveledCompactionStrategy "TWCS" :TimeWindowCompactionStrategy}) (defn- get-cluster [host port user password] (alia/cluster {:contact-points [host] :port port :jmx-reporting? false :credentials {:user user :password <PASSWORD>}})) (defn- make-replication-param [{:keys [network-strategy replication-factor] :or {network-strategy "SimpleStrategy"}}] (condp = network-strategy "SimpleStrategy" {"class" "SimpleStrategy" "replication_factor" replication-factor} "NetworkTopologyStrategy" {"class" "NetworkTopologyStrategy" "dc1" replication-factor} ;; TODO: other DCs (throw (ex-info "Unknown topology strategy is specified." {:network-strategy network-strategy})))) (defn- create-database [session database options] (alia/execute session (statement/create-keyspace (keyword database) (clause/if-exists false) (clause/with {:replication (make-replication-param options)})))) (defn- key-set->vec [key-set] (reduce (fn [v k] (conj v (keyword k))) [] key-set)) (defn- make-key-array [schema] (into (conj [] (key-set->vec (:partition-key schema))) (key-set->vec (:clustering-key schema)))) (defn- make-column-definitions [schema] (-> (reduce-kv (fn [m c t] (assoc m (keyword c) (keyword t))) {} (:columns schema)) (assoc :primary-key (make-key-array schema)))) (defn create-table [session schema options] (let [keyspace (keyword (:database schema)) table (keyword (:table schema)) cs (compaction-strategies (:compaction-strategy schema "STCS"))] (create-database session (:database schema) options) (alia/execute session (->raw (statement/use-keyspace keyspace))) (alia/execute session (->raw (statement/create-table table (clause/if-exists false) (clause/column-definitions (make-column-definitions schema)) (clause/with {:compaction {:class cs}})))) (doseq [index (:secondary-index schema)] (alia/execute session (->raw (statement/create-index table index (clause/index-name (str (name table) \_ common/INDEX_NAME_PREFIX \_ index)) (clause/if-exists false))))))) (defn- delete-table [session schema] (alia/execute session (->raw (statement/drop-keyspace (:database schema) (clause/if-exists true))))) (defn make-cassandra-operator [{:keys [host port user password] :or {port 9042 user "cassandra" password "<PASSWORD>"}}] (let [cluster (get-cluster host port user password) session (alia/connect cluster)] (reify proto/IOperator (create-table [_ schema opts] (create-table session schema opts)) (delete-table [_ schema _] (delete-table session schema)) (close [_ _] (alia/shutdown session) (alia/shutdown cluster)))))
true
(ns scalar-schema.cassandra (:require [clojure.tools.logging :as log] [scalar-schema.common :as common] [scalar-schema.protocols :as proto] [qbits.alia :as alia] [qbits.hayt :refer [->raw]] [qbits.hayt.dsl.clause :as clause] [qbits.hayt.dsl.statement :as statement])) (def ^:private compaction-strategies {"STCS" :SizeTieredCompactionStrategy "LCS" :LeveledCompactionStrategy "TWCS" :TimeWindowCompactionStrategy}) (defn- get-cluster [host port user password] (alia/cluster {:contact-points [host] :port port :jmx-reporting? false :credentials {:user user :password PI:PASSWORD:<PASSWORD>END_PI}})) (defn- make-replication-param [{:keys [network-strategy replication-factor] :or {network-strategy "SimpleStrategy"}}] (condp = network-strategy "SimpleStrategy" {"class" "SimpleStrategy" "replication_factor" replication-factor} "NetworkTopologyStrategy" {"class" "NetworkTopologyStrategy" "dc1" replication-factor} ;; TODO: other DCs (throw (ex-info "Unknown topology strategy is specified." {:network-strategy network-strategy})))) (defn- create-database [session database options] (alia/execute session (statement/create-keyspace (keyword database) (clause/if-exists false) (clause/with {:replication (make-replication-param options)})))) (defn- key-set->vec [key-set] (reduce (fn [v k] (conj v (keyword k))) [] key-set)) (defn- make-key-array [schema] (into (conj [] (key-set->vec (:partition-key schema))) (key-set->vec (:clustering-key schema)))) (defn- make-column-definitions [schema] (-> (reduce-kv (fn [m c t] (assoc m (keyword c) (keyword t))) {} (:columns schema)) (assoc :primary-key (make-key-array schema)))) (defn create-table [session schema options] (let [keyspace (keyword (:database schema)) table (keyword (:table schema)) cs (compaction-strategies (:compaction-strategy schema "STCS"))] (create-database session (:database schema) options) (alia/execute session (->raw (statement/use-keyspace keyspace))) (alia/execute session (->raw (statement/create-table table (clause/if-exists false) (clause/column-definitions (make-column-definitions schema)) (clause/with {:compaction {:class cs}})))) (doseq [index (:secondary-index schema)] (alia/execute session (->raw (statement/create-index table index (clause/index-name (str (name table) \_ common/INDEX_NAME_PREFIX \_ index)) (clause/if-exists false))))))) (defn- delete-table [session schema] (alia/execute session (->raw (statement/drop-keyspace (:database schema) (clause/if-exists true))))) (defn make-cassandra-operator [{:keys [host port user password] :or {port 9042 user "cassandra" password "PI:PASSWORD:<PASSWORD>END_PI"}}] (let [cluster (get-cluster host port user password) session (alia/connect cluster)] (reify proto/IOperator (create-table [_ schema opts] (create-table session schema opts)) (delete-table [_ schema _] (delete-table session schema)) (close [_ _] (alia/shutdown session) (alia/shutdown cluster)))))
[ { "context": "y EdDSAPublicKey)))\n\n;; From RFC8037\n(def key \"{\\\"kty\\\":\\\"OKP\\\",\\\"crv\\\":\\\"Ed25519\\\",\n\\\"d\\\":\\\"nWGxne_9WmC6hEr", "end": 412, "score": 0.9961647987365723, "start": 404, "tag": "KEY", "value": "kty\\\":\\\"" }, { "context": "ublicKey)))\n\n;; From RFC8037\n(def key \"{\\\"kty\\\":\\\"OKP\\\",\\\"crv\\\":\\\"Ed25519\\\",\n\\\"d\\\":\\\"nWGxne_9WmC6hEr0kuwsxERJxWl7Mmk", "end": 428, "score": 0.9970450401306152, "start": 412, "tag": "KEY", "value": "OKP\\\",\\\"crv\\\":\\\"" }, { "context": "From RFC8037\n(def key \"{\\\"kty\\\":\\\"OKP\\\",\\\"crv\\\":\\\"Ed25519\\\",\n\\\"d\\\":\\\"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf", "end": 438, "score": 0.9961862564086914, "start": 428, "tag": "KEY", "value": "Ed25519\\\"," }, { "context": "(def key \"{\\\"kty\\\":\\\"OKP\\\",\\\"crv\\\":\\\"Ed25519\\\",\n\\\"d\\\":\\\"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\\\",\n\\\"x", "end": 447, "score": 0.9117826223373413, "start": 441, "tag": "KEY", "value": "d\\\":\\\"" }, { "context": "ey \"{\\\"kty\\\":\\\"OKP\\\",\\\"crv\\\":\\\"Ed25519\\\",\n\\\"d\\\":\\\"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\\\",\n\\\"x\\\":\\\"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHU", "end": 493, "score": 0.9991055130958557, "start": 447, "tag": "KEY", "value": "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\\\"," }, { "context": "\"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\\\",\n\\\"x\\\":\\\"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\\\"}\")\n\n", "end": 502, "score": 0.9623253345489502, "start": 496, "tag": "KEY", "value": "x\\\":\\\"" }, { "context": "e_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\\\",\n\\\"x\\\":\\\"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\\\"}\")\n\n(deftest parse-key\n (let [jwk (jwk/parse-str", "end": 547, "score": 0.9996811151504517, "start": 502, "tag": "KEY", "value": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\\\"" }, { "context": "lic))\n\n (testing \"key roundtrip\"\n (is (= \"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\")\n (-> (.getSeed private)\n ", "end": 978, "score": 0.9997162222862244, "start": 935, "tag": "KEY", "value": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo" }, { "context": " (codecs/bytes->str)))\n\n (is (= \"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\")\n ", "end": 1100, "score": 0.6361249089241028, "start": 1098, "tag": "KEY", "value": "WG" }, { "context": " (codecs/bytes->str)))\n\n (is (= \"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\")\n ", "end": 1103, "score": 0.8768938183784485, "start": 1101, "tag": "KEY", "value": "ne" }, { "context": " (codecs/bytes->str)))\n\n (is (= \"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\")\n (-> ", "end": 1107, "score": 0.6647934913635254, "start": 1105, "tag": "KEY", "value": "Wm" }, { "context": "decs/bytes->str)))\n\n (is (= \"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\")\n (-> (.getAbyte", "end": 1117, "score": 0.6257960796356201, "start": 1113, "tag": "KEY", "value": "kuws" }, { "context": "key)\n ;; Example from RFC\n payload \"eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc\"\n {:keys [public private]} (jwk/jwk->keypa", "end": 1779, "score": 0.9997620582580566, "start": 1723, "tag": "KEY", "value": "eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc" }, { "context": " :key private})]\n (is (= \"hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg\"\n (codecs/bytes->str (b64/encode signat", "end": 2037, "score": 0.9997303485870361, "start": 1951, "tag": "KEY", "value": "hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg" }, { "context": " :key private})]\n\n (is (= \"eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg\"\n token))))\n", "end": 2666, "score": 0.999771773815155, "start": 2538, "tag": "KEY", "value": "eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g" } ]
test/buddy/contrib/eddsa_test.clj
shilder/buddy-sign-eddsa
0
(ns buddy.contrib.eddsa-test (:require [clojure.test :refer :all] [buddy.contrib.jwk :as jwk] [buddy.contrib.eddsa] [buddy.core.codecs.base64 :as b64] [buddy.core.codecs :as codecs] [buddy.core.dsa :as dsa] [buddy.sign.jws :as jws]) (:import (net.i2p.crypto.eddsa EdDSAPrivateKey EdDSAPublicKey))) ;; From RFC8037 (def key "{\"kty\":\"OKP\",\"crv\":\"Ed25519\", \"d\":\"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\", \"x\":\"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\"}") (deftest parse-key (let [jwk (jwk/parse-string key)] (is (= "Ed25519" (:crv jwk))))) (deftest key-conversion (let [jwk (jwk/parse-string key) pair (jwk/jwk->keypair jwk) public (:public pair) private (:private pair)] (is (instance? EdDSAPrivateKey private)) (is (instance? EdDSAPublicKey public)) (testing "key roundtrip" (is (= "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo") (-> (.getSeed private) (b64/encode true) (codecs/bytes->str))) (is (= "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A") (-> (.getAbyte public) (b64/encode true) (codecs/bytes->str)))))) (deftest thumbprint-test (let [jwk (jwk/parse-string key) th (jwk/thumbprint jwk)] (is (= "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k" (-> th (b64/encode true) (codecs/bytes->str)))) (is (= "90facafea9b1556698540f70c0117a22ea37bd5cf3ed3c47093c1707282b4b89" (codecs/bytes->hex th))))) (deftest dsa-signing-verification-test (let [jwk (jwk/parse-string key) ;; Example from RFC payload "eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc" {:keys [public private]} (jwk/jwk->keypair jwk) signature (dsa/sign payload {:alg :eddsa :key private})] (is (= "hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg" (codecs/bytes->str (b64/encode signature true)))) (is (dsa/verify payload signature {:alg :eddsa :key public})))) (deftest jws-signing-and-verification-test (let [jwk (jwk/parse-string key) ;; Example from RFC payload "Example of Ed25519 signing" {:keys [public private]} (jwk/jwk->keypair jwk) token (jws/sign payload private {:alg :eddsa :key private})] (is (= "eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg" token))))
80068
(ns buddy.contrib.eddsa-test (:require [clojure.test :refer :all] [buddy.contrib.jwk :as jwk] [buddy.contrib.eddsa] [buddy.core.codecs.base64 :as b64] [buddy.core.codecs :as codecs] [buddy.core.dsa :as dsa] [buddy.sign.jws :as jws]) (:import (net.i2p.crypto.eddsa EdDSAPrivateKey EdDSAPublicKey))) ;; From RFC8037 (def key "{\"<KEY> <KEY> <KEY> \"<KEY> <KEY> \"<KEY> <KEY>}") (deftest parse-key (let [jwk (jwk/parse-string key)] (is (= "Ed25519" (:crv jwk))))) (deftest key-conversion (let [jwk (jwk/parse-string key) pair (jwk/jwk->keypair jwk) public (:public pair) private (:private pair)] (is (instance? EdDSAPrivateKey private)) (is (instance? EdDSAPublicKey public)) (testing "key roundtrip" (is (= "<KEY>") (-> (.getSeed private) (b64/encode true) (codecs/bytes->str))) (is (= "n<KEY>x<KEY>_9<KEY>C6hEr0<KEY>xERJxWl7MmkZcDusAxyuf2A") (-> (.getAbyte public) (b64/encode true) (codecs/bytes->str)))))) (deftest thumbprint-test (let [jwk (jwk/parse-string key) th (jwk/thumbprint jwk)] (is (= "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k" (-> th (b64/encode true) (codecs/bytes->str)))) (is (= "90facafea9b1556698540f70c0117a22ea37bd5cf3ed3c47093c1707282b4b89" (codecs/bytes->hex th))))) (deftest dsa-signing-verification-test (let [jwk (jwk/parse-string key) ;; Example from RFC payload "<KEY>" {:keys [public private]} (jwk/jwk->keypair jwk) signature (dsa/sign payload {:alg :eddsa :key private})] (is (= "<KEY>" (codecs/bytes->str (b64/encode signature true)))) (is (dsa/verify payload signature {:alg :eddsa :key public})))) (deftest jws-signing-and-verification-test (let [jwk (jwk/parse-string key) ;; Example from RFC payload "Example of Ed25519 signing" {:keys [public private]} (jwk/jwk->keypair jwk) token (jws/sign payload private {:alg :eddsa :key private})] (is (= "<KEY>7sVvpAr_MuM0KAg" token))))
true
(ns buddy.contrib.eddsa-test (:require [clojure.test :refer :all] [buddy.contrib.jwk :as jwk] [buddy.contrib.eddsa] [buddy.core.codecs.base64 :as b64] [buddy.core.codecs :as codecs] [buddy.core.dsa :as dsa] [buddy.sign.jws :as jws]) (:import (net.i2p.crypto.eddsa EdDSAPrivateKey EdDSAPublicKey))) ;; From RFC8037 (def key "{\"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 \"PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI}") (deftest parse-key (let [jwk (jwk/parse-string key)] (is (= "Ed25519" (:crv jwk))))) (deftest key-conversion (let [jwk (jwk/parse-string key) pair (jwk/jwk->keypair jwk) public (:public pair) private (:private pair)] (is (instance? EdDSAPrivateKey private)) (is (instance? EdDSAPublicKey public)) (testing "key roundtrip" (is (= "PI:KEY:<KEY>END_PI") (-> (.getSeed private) (b64/encode true) (codecs/bytes->str))) (is (= "nPI:KEY:<KEY>END_PIxPI:KEY:<KEY>END_PI_9PI:KEY:<KEY>END_PIC6hEr0PI:KEY:<KEY>END_PIxERJxWl7MmkZcDusAxyuf2A") (-> (.getAbyte public) (b64/encode true) (codecs/bytes->str)))))) (deftest thumbprint-test (let [jwk (jwk/parse-string key) th (jwk/thumbprint jwk)] (is (= "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k" (-> th (b64/encode true) (codecs/bytes->str)))) (is (= "90facafea9b1556698540f70c0117a22ea37bd5cf3ed3c47093c1707282b4b89" (codecs/bytes->hex th))))) (deftest dsa-signing-verification-test (let [jwk (jwk/parse-string key) ;; Example from RFC payload "PI:KEY:<KEY>END_PI" {:keys [public private]} (jwk/jwk->keypair jwk) signature (dsa/sign payload {:alg :eddsa :key private})] (is (= "PI:KEY:<KEY>END_PI" (codecs/bytes->str (b64/encode signature true)))) (is (dsa/verify payload signature {:alg :eddsa :key public})))) (deftest jws-signing-and-verification-test (let [jwk (jwk/parse-string key) ;; Example from RFC payload "Example of Ed25519 signing" {:keys [public private]} (jwk/jwk->keypair jwk) token (jws/sign payload private {:alg :eddsa :key private})] (is (= "PI:KEY:<KEY>END_PI7sVvpAr_MuM0KAg" token))))
[ { "context": ";;;\n;;; Copyright 2020 David Edwards\n;;;\n;;; Licensed under the Apache License, Versio", "end": 36, "score": 0.9997665882110596, "start": 23, "tag": "NAME", "value": "David Edwards" } ]
src/rpn/compiler.clj
davidledwards/rpn-clojure
1
;;; ;;; Copyright 2020 David Edwards ;;; ;;; 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 rpn.compiler "RPN compiler." (:require [rpn.token :as token]) (:require [rpn.lexer :as lexer]) (:require [rpn.parser :as parser]) (:require [rpn.ast :as ast]) (:require [rpn.generator :as gen]) (:require [rpn.optimizer :as opt]) (:require [rpn.code :as code]) (:require [rpn.input :as input])) (defn -main [& args] (try (let [in (input/input *in*) arg (first args)] (cond (= arg "-h") (do (println "usage: rpnc [options]") (println " Compile expression from stdin and emit instructions to stdout.") (println " -t tokenize only") (println " -p parse only") (println " -o optimize")) (= arg "-t") (doseq [t (lexer/lexer in)] (println (token/canonical t))) (= arg "-p") (println (ast/typeset (parser/parser (lexer/lexer in)))) (= arg "-o") (doseq [c (opt/optimizer (gen/generator (parser/parser (lexer/lexer in))))] (println (code/instruction c))) (nil? arg) (doseq [c (gen/generator (parser/parser (lexer/lexer in)))] (println (code/instruction c))) :else (println (str arg ": unrecognized option")))) (catch Exception e (println (.getMessage e)))))
36617
;;; ;;; Copyright 2020 <NAME> ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.compiler "RPN compiler." (:require [rpn.token :as token]) (:require [rpn.lexer :as lexer]) (:require [rpn.parser :as parser]) (:require [rpn.ast :as ast]) (:require [rpn.generator :as gen]) (:require [rpn.optimizer :as opt]) (:require [rpn.code :as code]) (:require [rpn.input :as input])) (defn -main [& args] (try (let [in (input/input *in*) arg (first args)] (cond (= arg "-h") (do (println "usage: rpnc [options]") (println " Compile expression from stdin and emit instructions to stdout.") (println " -t tokenize only") (println " -p parse only") (println " -o optimize")) (= arg "-t") (doseq [t (lexer/lexer in)] (println (token/canonical t))) (= arg "-p") (println (ast/typeset (parser/parser (lexer/lexer in)))) (= arg "-o") (doseq [c (opt/optimizer (gen/generator (parser/parser (lexer/lexer in))))] (println (code/instruction c))) (nil? arg) (doseq [c (gen/generator (parser/parser (lexer/lexer in)))] (println (code/instruction c))) :else (println (str arg ": unrecognized option")))) (catch Exception e (println (.getMessage e)))))
true
;;; ;;; Copyright 2020 PI:NAME:<NAME>END_PI ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.compiler "RPN compiler." (:require [rpn.token :as token]) (:require [rpn.lexer :as lexer]) (:require [rpn.parser :as parser]) (:require [rpn.ast :as ast]) (:require [rpn.generator :as gen]) (:require [rpn.optimizer :as opt]) (:require [rpn.code :as code]) (:require [rpn.input :as input])) (defn -main [& args] (try (let [in (input/input *in*) arg (first args)] (cond (= arg "-h") (do (println "usage: rpnc [options]") (println " Compile expression from stdin and emit instructions to stdout.") (println " -t tokenize only") (println " -p parse only") (println " -o optimize")) (= arg "-t") (doseq [t (lexer/lexer in)] (println (token/canonical t))) (= arg "-p") (println (ast/typeset (parser/parser (lexer/lexer in)))) (= arg "-o") (doseq [c (opt/optimizer (gen/generator (parser/parser (lexer/lexer in))))] (println (code/instruction c))) (nil? arg) (doseq [c (gen/generator (parser/parser (lexer/lexer in)))] (println (code/instruction c))) :else (println (str arg ": unrecognized option")))) (catch Exception e (println (.getMessage e)))))
[ { "context": "(fact \"search new entries\"\n (let [entry-key \"9999\"\n entry-doc \"latest entry\"\n ", "end": 2303, "score": 0.9748064875602722, "start": 2299, "tag": "KEY", "value": "9999" }, { "context": "(fact \"search new entries\"\n (let [entry-key \"9999\"\n entry-doc \"latest entry\"]\n (t", "end": 3409, "score": 0.9993027448654175, "start": 3405, "tag": "KEY", "value": "9999" }, { "context": "(fact \"search new entries\"\n (let [entry-key \"9999\"\n entry-doc \"latest entry\"\n ", "end": 5434, "score": 0.994178831577301, "start": 5430, "tag": "KEY", "value": "9999" }, { "context": "(fact \"search new entries\"\n (let [entry-key \"9999\"\n entry-doc \"最新のエントリ\"\n sear", "end": 6783, "score": 0.9858578443527222, "start": 6779, "tag": "KEY", "value": "9999" }, { "context": "(fact \"search new entries\"\n (let [entry-key \"9999\"\n entry-doc \"latest entry\"\n ", "end": 8147, "score": 0.9990098476409912, "start": 8143, "tag": "KEY", "value": "9999" }, { "context": "(fact \"search new entries\"\n (let [entry-key \"9999\"\n entry-doc \"最新のエントリ\"\n sear", "end": 9571, "score": 0.997976541519165, "start": 9567, "tag": "KEY", "value": "9999" }, { "context": "(fact \"search new entries\"\n (let [entry-key \"9999\"\n entry-doc \"最新のエントリ\"\n sear", "end": 10792, "score": 0.9931285977363586, "start": 10788, "tag": "KEY", "value": "9999" }, { "context": "(fact \"search new entries\"\n (let [entry-key \"9999\"\n entry-doc \"最新のエントリ\"]\n (t-comm", "end": 11971, "score": 0.9979888796806335, "start": 11967, "tag": "KEY", "value": "9999" }, { "context": "arch (en)\"\n (t-common/phrase-search-entries \"Heo\" 10) => (t-common/results-is-valid? 0)))\n (with-", "end": 13904, "score": 0.8235554695129395, "start": 13901, "tag": "NAME", "value": "Heo" }, { "context": "mmon/add-entry! \"dummy\" \"\")\n (let [entry-key 55\n entry-doc (str entry-key)]\n (t", "end": 17467, "score": 0.9920858144760132, "start": 17465, "tag": "KEY", "value": "55" }, { "context": "mmon/results-is-valid? 0))\n (let [entry-key (java.util.UUID/randomUUID)\n entry-doc (str entry-key)]\n (", "end": 18626, "score": 0.9921740293502808, "start": 18601, "tag": "KEY", "value": "java.util.UUID/randomUUID" }, { "context": "re\"\n (core/add! @t-common/test-store [{:key \"123\", :doc \"abc\"}] [:key :doc]) => nil?\n (core/a", "end": 23484, "score": 0.852504551410675, "start": 23481, "tag": "KEY", "value": "123" }, { "context": "il?\n (core/add! @t-common/test-store [{:key \"456\", :doc \"def\"}] [:key :doc]\n (anal", "end": 23570, "score": 0.9219220280647278, "start": 23567, "tag": "KEY", "value": "456" }, { "context": "rd-analyzer))]\n (core/add! writer [{:key \"123\", :doc \"abc\"}] [:key :doc]) => nil?\n (core", "end": 23812, "score": 0.8587308526039124, "start": 23810, "tag": "KEY", "value": "23" }, { "context": " :doc]) => nil?\n (core/add! writer [{:key \"456\", :doc \"def\"}] [:key :doc]\n (an", "end": 23886, "score": 0.9408808350563049, "start": 23883, "tag": "KEY", "value": "456" } ]
test/clucie/t_core.clj
federkasten/clucie
62
(ns clucie.t-core (:require [midje.sweet :refer :all] [clucie.core :as core] [clucie.analysis :as analysis] [clucie.store :as store] [clucie.t-common :as t-common] [clucie.t-fixture :as t-fixture]) (:import [java.util UUID] [org.apache.lucene.queryparser.flexible.standard StandardQueryParser])) (defmacro run-testset! [testset-symbol] (let [testset (eval testset-symbol) label (str (:testname testset) " : " (:testdesc testset)) tests (map (fn [[query result]] `(fact ~(str ": query = " query) (try (set (map :key (~'search-fn @t-common/test-store [{:doc ~query}] 10 @t-common/doc-analyzer))) ;; for check exception (catch Throwable e# (type e#))) => ~result)) (seq (:query+result testset)))] `(let [testset# ~testset-symbol ~'search-fn (:search-fn testset#)] (t-common/prepare! (:analyzer testset#) nil (:dataset testset#)) (facts ~label ~@tests) (t-common/finish!)))) (facts "keyword analyzer with wildcard search" (with-state-changes [(before :facts (t-common/prepare! t-common/keyword-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-3 10) => (t-common/results-is-valid? 0) (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0]))) (fact "search new entries" (let [entry-key "9999" entry-doc "latest entry" search-query "*est ent*"] (t-common/wildcard-search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/wildcard-search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "standard analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-en-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/search-entries t-fixture/entries-en-1-search-2 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-en-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/search-entries t-fixture/entries-en-1-search-4 10) => (t-common/results-is-valid? 0)) (fact "search new entries" (let [entry-key "9999" entry-doc "latest entry"] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "built analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/built-analyzer nil t-fixture/entries-unnormalized-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-unnormalized-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-unnormalized-1 [0 0])) (t-common/search-entries t-fixture/entries-unnormalized-1-search-2 10) => (t-common/results-is-valid? 2 (get-in t-fixture/entries-unnormalized-1 [1 0])) (t-common/search-entries t-fixture/entries-unnormalized-1-search-2 10) => (t-common/results-is-valid? 2 (get-in t-fixture/entries-unnormalized-1 [2 0]))))) (facts "ngram analyzer (en)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries "A" 10) => empty? (t-common/search-entries t-fixture/entries-en-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/search-entries t-fixture/entries-en-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/search-entries t-fixture/entries-en-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/search-entries t-fixture/entries-en-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/search-entries t-fixture/entries-en-1-search-5 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [2 0]))) (fact "search new entries" (let [entry-key "9999" entry-doc "latest entry" search-query "est ent"] (t-common/search-entries search-query 10) => (t-common/results-is-valid? 1) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries search-query 10) => (t-common/results-is-valid? 2 entry-key))))) (facts "ngram analyzer (ja)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries "あ" 10) => empty? (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [1 0]))) (fact "search new entries" (let [entry-key "9999" entry-doc "最新のエントリ" search-query "新のエン"] (t-common/search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "ngram analyzer with phrase search (en)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/phrase-search-entries "A" 10) => empty? (t-common/phrase-search-entries t-fixture/entries-en-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-5 10) => (t-common/results-is-valid? 0)) (fact "search new entries" (let [entry-key "9999" entry-doc "latest entry" search-query "est ent"] (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "ngram analyzer with phrase search (ja)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/phrase-search-entries "あ" 10) => empty? (t-common/phrase-search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [1 0]))) (fact "search new entries" (let [entry-key "9999" entry-doc "最新のエントリ" search-query "新のエン"] (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "cjk analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/cjk-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1)) (fact "search new entries" (let [entry-key "9999" entry-doc "最新のエントリ" search-query "新のエン"] (t-common/search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "kuromoji analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/kuromoji-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 0)) (fact "search new entries" (let [entry-key "9999" entry-doc "最新のエントリ"] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "with stop-words" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer t-fixture/stop-words-en) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "standard analyzer" (t-common/search-entries "Heo" 10) => (t-common/results-is-valid? 0))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-en) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer (en)" (t-common/search-entries "Heo" 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-ja) nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer (ja)" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-en) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer with phrase search (en)" (t-common/phrase-search-entries "Heo" 10) => (t-common/results-is-valid? 0))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-ja) nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer with phrase search (ja)" (t-common/phrase-search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (t-common/prepare! (analysis/cjk-analyzer t-fixture/stop-words-ja) nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "cjk analyzer" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (let [ana (analysis/kuromoji-analyzer nil :search t-fixture/stop-words-ja #{})] (t-common/prepare! ana nil t-fixture/entries-ja-1))) (after :facts (t-common/finish!))] (fact "kuromoji analyzer" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 0)))) (facts "modify exists entries" (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "update" (let [[k doc] (first t-fixture/entries-en-1) new-doc "zzz"] (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! k new-doc) => nil (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 1 k))) (fact "delete" (let [[k doc] (first t-fixture/entries-en-1)] (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) (t-common/delete-entry! k) => nil (t-common/search-entries doc 10) => (t-common/results-is-valid? 0))))) (facts "search utilities" (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer)) (after :facts (t-common/finish!))] (fact "use non-string keys" (t-common/add-entry! "dummy" "") (let [entry-key 55 entry-doc (str entry-key)] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key "") => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 (str entry-key)) (t-common/delete-entry! entry-key) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0)) (let [entry-key :test entry-doc (name entry-key)] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key "") => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 (name entry-key)) (t-common/delete-entry! entry-key) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0)) (let [entry-key (java.util.UUID/randomUUID) entry-doc (str entry-key)] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key "") => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 (str entry-key)) (t-common/delete-entry! entry-key) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0))) (fact "with pagination" (let [doc-prefix "with pagination"] (dotimes [i 105] (let [index (+ i 50000) doc (str doc-prefix index)] (t-common/add-entry! (str index) doc))) (t-common/search-entries doc-prefix 100 0 10) => (t-common/results-is-valid? 10) (t-common/search-entries doc-prefix 19 1 10) => (t-common/results-is-valid? 9) (t-common/search-entries doc-prefix 200 10 10) => (t-common/results-is-valid? 5) (t-common/search-entries doc-prefix 200 0 200) => (t-common/results-is-valid? 105) (t-common/search-entries doc-prefix 200 200 200) => (t-common/results-is-valid? 0) (t-common/search-entries doc-prefix 5 200 5) => (t-common/results-is-valid? 0) (t-common/search-entries doc-prefix 8 0 200) => (t-common/results-is-valid? 8))))) (run-testset! t-fixture/testset-kw-s) (run-testset! t-fixture/testset-kw-w) (run-testset! t-fixture/testset-kw-q) (run-testset! t-fixture/testset-std-s) (run-testset! t-fixture/testset-std-p) (run-testset! t-fixture/testset-std-q) (run-testset! t-fixture/testset-cjk-s) (run-testset! t-fixture/testset-cjk-p) (run-testset! t-fixture/testset-cjk-q) (run-testset! t-fixture/testset-kuro-s) (run-testset! t-fixture/testset-kuro-p) (run-testset! t-fixture/testset-kuro-q) (run-testset! t-fixture/testset-ngram-s) (run-testset! t-fixture/testset-ngram-p) (run-testset! t-fixture/testset-ngram-q) (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (letfn [(parse-query [^String s] (.parse (StandardQueryParser. t-common/standard-analyzer) s "doc"))] (fact "raw query search" (core/search @t-common/test-store (parse-query "doc:20130819") 10) => (t-common/results-is-valid? 1) (core/search @t-common/test-store (parse-query "Hello Tokyo") 10) => (t-common/results-is-valid? 2) (core/search @t-common/test-store (parse-query "Hello AND Tokyo") 10) => (t-common/results-is-valid? 0)))) (facts "abnormal usage" (with-state-changes [(before :facts (t-common/prepare! nil nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "manipulate with default analyzer" (let [[k doc] (first t-fixture/entries-en-1) new-doc "newer"] (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) (core/update! @t-common/test-store {:key k, :doc new-doc} [:key :doc] :key k) (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 1 k) (core/delete! @t-common/test-store :key k) (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 0))) (fact "without index" (let [k "new-key" doc "this_is_new_entry"] (core/add! @t-common/test-store [{:key k, :doc doc}] []) (t-common/search-entries doc 10) => (t-common/results-is-valid? 0))))) (let [tmp-store-path (t-common/get-tmp-dir) k "123" doc "abc"] (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer tmp-store-path)) (after :facts (t-common/finish! tmp-store-path))] (fact "disk store" (t-common/add-entry! "dummy" "") (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! k doc) => nil (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) ;; Switch to another session (store/close! @t-common/test-store) (reset! t-common/test-store (store/disk-store tmp-store-path)) (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k)))) (facts "add!" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (core/add! @t-common/test-store [{:key "123", :doc "abc"}] [:key :doc]) => nil? (core/add! @t-common/test-store [{:key "456", :doc "def"}] [:key :doc] (analysis/standard-analyzer)) => nil?) (fact "with writer" (with-open [writer (store/store-writer @t-common/test-store (analysis/standard-analyzer))] (core/add! writer [{:key "123", :doc "abc"}] [:key :doc]) => nil? (core/add! writer [{:key "456", :doc "def"}] [:key :doc] (analysis/standard-analyzer)) => (throws clojure.lang.ArityException))))) (facts "update!" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (core/update! @t-common/test-store {:key "2", :doc "Hello world"} [:key :doc] :key "2") => nil? (core/update! @t-common/test-store {:key "3", :doc "Osaka station"} [:key :doc] :key "3" (analysis/standard-analyzer)) => nil?) (fact "with writer" (with-open [writer (store/store-writer @t-common/test-store (analysis/standard-analyzer))] (core/update! writer {:key "2", :doc "Hello world"} [:key :doc] :key "2") => nil? (core/update! writer {:key "3", :doc "Osaka station"} [:key :doc] :key "3" (analysis/standard-analyzer)) => (throws clojure.lang.ArityException))))) (facts "delete!" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (core/delete! @t-common/test-store :key "1") => nil? (core/delete! @t-common/test-store :key "2" (analysis/standard-analyzer)) => nil?) (fact "with writer" (with-open [writer (store/store-writer @t-common/test-store (analysis/standard-analyzer))] (core/delete! writer :key "1") => nil? (core/delete! writer :key "2" (analysis/standard-analyzer)) => (throws clojure.lang.ArityException))))) (facts "search*" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (#'core/search* :query @t-common/test-store [{:doc t-fixture/entries-en-1-search-1}] 10 (analysis/standard-analyzer) 0 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0]))) (fact "with reader" (with-open [reader (store/store-reader @t-common/test-store)] (#'core/search* :query reader [{:doc t-fixture/entries-en-1-search-1}] 10 (analysis/standard-analyzer) 0 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0]))))))
50596
(ns clucie.t-core (:require [midje.sweet :refer :all] [clucie.core :as core] [clucie.analysis :as analysis] [clucie.store :as store] [clucie.t-common :as t-common] [clucie.t-fixture :as t-fixture]) (:import [java.util UUID] [org.apache.lucene.queryparser.flexible.standard StandardQueryParser])) (defmacro run-testset! [testset-symbol] (let [testset (eval testset-symbol) label (str (:testname testset) " : " (:testdesc testset)) tests (map (fn [[query result]] `(fact ~(str ": query = " query) (try (set (map :key (~'search-fn @t-common/test-store [{:doc ~query}] 10 @t-common/doc-analyzer))) ;; for check exception (catch Throwable e# (type e#))) => ~result)) (seq (:query+result testset)))] `(let [testset# ~testset-symbol ~'search-fn (:search-fn testset#)] (t-common/prepare! (:analyzer testset#) nil (:dataset testset#)) (facts ~label ~@tests) (t-common/finish!)))) (facts "keyword analyzer with wildcard search" (with-state-changes [(before :facts (t-common/prepare! t-common/keyword-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-3 10) => (t-common/results-is-valid? 0) (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0]))) (fact "search new entries" (let [entry-key "<KEY>" entry-doc "latest entry" search-query "*est ent*"] (t-common/wildcard-search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/wildcard-search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "standard analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-en-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/search-entries t-fixture/entries-en-1-search-2 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-en-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/search-entries t-fixture/entries-en-1-search-4 10) => (t-common/results-is-valid? 0)) (fact "search new entries" (let [entry-key "<KEY>" entry-doc "latest entry"] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "built analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/built-analyzer nil t-fixture/entries-unnormalized-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-unnormalized-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-unnormalized-1 [0 0])) (t-common/search-entries t-fixture/entries-unnormalized-1-search-2 10) => (t-common/results-is-valid? 2 (get-in t-fixture/entries-unnormalized-1 [1 0])) (t-common/search-entries t-fixture/entries-unnormalized-1-search-2 10) => (t-common/results-is-valid? 2 (get-in t-fixture/entries-unnormalized-1 [2 0]))))) (facts "ngram analyzer (en)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries "A" 10) => empty? (t-common/search-entries t-fixture/entries-en-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/search-entries t-fixture/entries-en-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/search-entries t-fixture/entries-en-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/search-entries t-fixture/entries-en-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/search-entries t-fixture/entries-en-1-search-5 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [2 0]))) (fact "search new entries" (let [entry-key "<KEY>" entry-doc "latest entry" search-query "est ent"] (t-common/search-entries search-query 10) => (t-common/results-is-valid? 1) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries search-query 10) => (t-common/results-is-valid? 2 entry-key))))) (facts "ngram analyzer (ja)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries "あ" 10) => empty? (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [1 0]))) (fact "search new entries" (let [entry-key "<KEY>" entry-doc "最新のエントリ" search-query "新のエン"] (t-common/search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "ngram analyzer with phrase search (en)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/phrase-search-entries "A" 10) => empty? (t-common/phrase-search-entries t-fixture/entries-en-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-5 10) => (t-common/results-is-valid? 0)) (fact "search new entries" (let [entry-key "<KEY>" entry-doc "latest entry" search-query "est ent"] (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "ngram analyzer with phrase search (ja)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/phrase-search-entries "あ" 10) => empty? (t-common/phrase-search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [1 0]))) (fact "search new entries" (let [entry-key "<KEY>" entry-doc "最新のエントリ" search-query "新のエン"] (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "cjk analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/cjk-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1)) (fact "search new entries" (let [entry-key "<KEY>" entry-doc "最新のエントリ" search-query "新のエン"] (t-common/search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "kuromoji analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/kuromoji-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 0)) (fact "search new entries" (let [entry-key "<KEY>" entry-doc "最新のエントリ"] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "with stop-words" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer t-fixture/stop-words-en) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "standard analyzer" (t-common/search-entries "Heo" 10) => (t-common/results-is-valid? 0))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-en) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer (en)" (t-common/search-entries "Heo" 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-ja) nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer (ja)" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-en) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer with phrase search (en)" (t-common/phrase-search-entries "<NAME>" 10) => (t-common/results-is-valid? 0))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-ja) nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer with phrase search (ja)" (t-common/phrase-search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (t-common/prepare! (analysis/cjk-analyzer t-fixture/stop-words-ja) nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "cjk analyzer" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (let [ana (analysis/kuromoji-analyzer nil :search t-fixture/stop-words-ja #{})] (t-common/prepare! ana nil t-fixture/entries-ja-1))) (after :facts (t-common/finish!))] (fact "kuromoji analyzer" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 0)))) (facts "modify exists entries" (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "update" (let [[k doc] (first t-fixture/entries-en-1) new-doc "zzz"] (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! k new-doc) => nil (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 1 k))) (fact "delete" (let [[k doc] (first t-fixture/entries-en-1)] (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) (t-common/delete-entry! k) => nil (t-common/search-entries doc 10) => (t-common/results-is-valid? 0))))) (facts "search utilities" (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer)) (after :facts (t-common/finish!))] (fact "use non-string keys" (t-common/add-entry! "dummy" "") (let [entry-key <KEY> entry-doc (str entry-key)] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key "") => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 (str entry-key)) (t-common/delete-entry! entry-key) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0)) (let [entry-key :test entry-doc (name entry-key)] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key "") => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 (name entry-key)) (t-common/delete-entry! entry-key) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0)) (let [entry-key (<KEY>) entry-doc (str entry-key)] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key "") => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 (str entry-key)) (t-common/delete-entry! entry-key) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0))) (fact "with pagination" (let [doc-prefix "with pagination"] (dotimes [i 105] (let [index (+ i 50000) doc (str doc-prefix index)] (t-common/add-entry! (str index) doc))) (t-common/search-entries doc-prefix 100 0 10) => (t-common/results-is-valid? 10) (t-common/search-entries doc-prefix 19 1 10) => (t-common/results-is-valid? 9) (t-common/search-entries doc-prefix 200 10 10) => (t-common/results-is-valid? 5) (t-common/search-entries doc-prefix 200 0 200) => (t-common/results-is-valid? 105) (t-common/search-entries doc-prefix 200 200 200) => (t-common/results-is-valid? 0) (t-common/search-entries doc-prefix 5 200 5) => (t-common/results-is-valid? 0) (t-common/search-entries doc-prefix 8 0 200) => (t-common/results-is-valid? 8))))) (run-testset! t-fixture/testset-kw-s) (run-testset! t-fixture/testset-kw-w) (run-testset! t-fixture/testset-kw-q) (run-testset! t-fixture/testset-std-s) (run-testset! t-fixture/testset-std-p) (run-testset! t-fixture/testset-std-q) (run-testset! t-fixture/testset-cjk-s) (run-testset! t-fixture/testset-cjk-p) (run-testset! t-fixture/testset-cjk-q) (run-testset! t-fixture/testset-kuro-s) (run-testset! t-fixture/testset-kuro-p) (run-testset! t-fixture/testset-kuro-q) (run-testset! t-fixture/testset-ngram-s) (run-testset! t-fixture/testset-ngram-p) (run-testset! t-fixture/testset-ngram-q) (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (letfn [(parse-query [^String s] (.parse (StandardQueryParser. t-common/standard-analyzer) s "doc"))] (fact "raw query search" (core/search @t-common/test-store (parse-query "doc:20130819") 10) => (t-common/results-is-valid? 1) (core/search @t-common/test-store (parse-query "Hello Tokyo") 10) => (t-common/results-is-valid? 2) (core/search @t-common/test-store (parse-query "Hello AND Tokyo") 10) => (t-common/results-is-valid? 0)))) (facts "abnormal usage" (with-state-changes [(before :facts (t-common/prepare! nil nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "manipulate with default analyzer" (let [[k doc] (first t-fixture/entries-en-1) new-doc "newer"] (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) (core/update! @t-common/test-store {:key k, :doc new-doc} [:key :doc] :key k) (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 1 k) (core/delete! @t-common/test-store :key k) (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 0))) (fact "without index" (let [k "new-key" doc "this_is_new_entry"] (core/add! @t-common/test-store [{:key k, :doc doc}] []) (t-common/search-entries doc 10) => (t-common/results-is-valid? 0))))) (let [tmp-store-path (t-common/get-tmp-dir) k "123" doc "abc"] (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer tmp-store-path)) (after :facts (t-common/finish! tmp-store-path))] (fact "disk store" (t-common/add-entry! "dummy" "") (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! k doc) => nil (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) ;; Switch to another session (store/close! @t-common/test-store) (reset! t-common/test-store (store/disk-store tmp-store-path)) (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k)))) (facts "add!" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (core/add! @t-common/test-store [{:key "<KEY>", :doc "abc"}] [:key :doc]) => nil? (core/add! @t-common/test-store [{:key "<KEY>", :doc "def"}] [:key :doc] (analysis/standard-analyzer)) => nil?) (fact "with writer" (with-open [writer (store/store-writer @t-common/test-store (analysis/standard-analyzer))] (core/add! writer [{:key "1<KEY>", :doc "abc"}] [:key :doc]) => nil? (core/add! writer [{:key "<KEY>", :doc "def"}] [:key :doc] (analysis/standard-analyzer)) => (throws clojure.lang.ArityException))))) (facts "update!" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (core/update! @t-common/test-store {:key "2", :doc "Hello world"} [:key :doc] :key "2") => nil? (core/update! @t-common/test-store {:key "3", :doc "Osaka station"} [:key :doc] :key "3" (analysis/standard-analyzer)) => nil?) (fact "with writer" (with-open [writer (store/store-writer @t-common/test-store (analysis/standard-analyzer))] (core/update! writer {:key "2", :doc "Hello world"} [:key :doc] :key "2") => nil? (core/update! writer {:key "3", :doc "Osaka station"} [:key :doc] :key "3" (analysis/standard-analyzer)) => (throws clojure.lang.ArityException))))) (facts "delete!" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (core/delete! @t-common/test-store :key "1") => nil? (core/delete! @t-common/test-store :key "2" (analysis/standard-analyzer)) => nil?) (fact "with writer" (with-open [writer (store/store-writer @t-common/test-store (analysis/standard-analyzer))] (core/delete! writer :key "1") => nil? (core/delete! writer :key "2" (analysis/standard-analyzer)) => (throws clojure.lang.ArityException))))) (facts "search*" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (#'core/search* :query @t-common/test-store [{:doc t-fixture/entries-en-1-search-1}] 10 (analysis/standard-analyzer) 0 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0]))) (fact "with reader" (with-open [reader (store/store-reader @t-common/test-store)] (#'core/search* :query reader [{:doc t-fixture/entries-en-1-search-1}] 10 (analysis/standard-analyzer) 0 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0]))))))
true
(ns clucie.t-core (:require [midje.sweet :refer :all] [clucie.core :as core] [clucie.analysis :as analysis] [clucie.store :as store] [clucie.t-common :as t-common] [clucie.t-fixture :as t-fixture]) (:import [java.util UUID] [org.apache.lucene.queryparser.flexible.standard StandardQueryParser])) (defmacro run-testset! [testset-symbol] (let [testset (eval testset-symbol) label (str (:testname testset) " : " (:testdesc testset)) tests (map (fn [[query result]] `(fact ~(str ": query = " query) (try (set (map :key (~'search-fn @t-common/test-store [{:doc ~query}] 10 @t-common/doc-analyzer))) ;; for check exception (catch Throwable e# (type e#))) => ~result)) (seq (:query+result testset)))] `(let [testset# ~testset-symbol ~'search-fn (:search-fn testset#)] (t-common/prepare! (:analyzer testset#) nil (:dataset testset#)) (facts ~label ~@tests) (t-common/finish!)))) (facts "keyword analyzer with wildcard search" (with-state-changes [(before :facts (t-common/prepare! t-common/keyword-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-3 10) => (t-common/results-is-valid? 0) (t-common/wildcard-search-entries t-fixture/entries-en-1-search-wildcard-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0]))) (fact "search new entries" (let [entry-key "PI:KEY:<KEY>END_PI" entry-doc "latest entry" search-query "*est ent*"] (t-common/wildcard-search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/wildcard-search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "standard analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-en-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/search-entries t-fixture/entries-en-1-search-2 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-en-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/search-entries t-fixture/entries-en-1-search-4 10) => (t-common/results-is-valid? 0)) (fact "search new entries" (let [entry-key "PI:KEY:<KEY>END_PI" entry-doc "latest entry"] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "built analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/built-analyzer nil t-fixture/entries-unnormalized-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-unnormalized-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-unnormalized-1 [0 0])) (t-common/search-entries t-fixture/entries-unnormalized-1-search-2 10) => (t-common/results-is-valid? 2 (get-in t-fixture/entries-unnormalized-1 [1 0])) (t-common/search-entries t-fixture/entries-unnormalized-1-search-2 10) => (t-common/results-is-valid? 2 (get-in t-fixture/entries-unnormalized-1 [2 0]))))) (facts "ngram analyzer (en)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries "A" 10) => empty? (t-common/search-entries t-fixture/entries-en-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/search-entries t-fixture/entries-en-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/search-entries t-fixture/entries-en-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/search-entries t-fixture/entries-en-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/search-entries t-fixture/entries-en-1-search-5 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [2 0]))) (fact "search new entries" (let [entry-key "PI:KEY:<KEY>END_PI" entry-doc "latest entry" search-query "est ent"] (t-common/search-entries search-query 10) => (t-common/results-is-valid? 1) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries search-query 10) => (t-common/results-is-valid? 2 entry-key))))) (facts "ngram analyzer (ja)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries "あ" 10) => empty? (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [1 0]))) (fact "search new entries" (let [entry-key "PI:KEY:<KEY>END_PI" entry-doc "最新のエントリ" search-query "新のエン"] (t-common/search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "ngram analyzer with phrase search (en)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/phrase-search-entries "A" 10) => empty? (t-common/phrase-search-entries t-fixture/entries-en-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [1 0])) (t-common/phrase-search-entries t-fixture/entries-en-1-search-5 10) => (t-common/results-is-valid? 0)) (fact "search new entries" (let [entry-key "PI:KEY:<KEY>END_PI" entry-doc "latest entry" search-query "est ent"] (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "ngram analyzer with phrase search (ja)" (with-state-changes [(before :facts (t-common/prepare! t-common/ngram-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/phrase-search-entries "あ" 10) => empty? (t-common/phrase-search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [1 0]))) (fact "search new entries" (let [entry-key "PI:KEY:<KEY>END_PI" entry-doc "最新のエントリ" search-query "新のエン"] (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/phrase-search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "cjk analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/cjk-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1)) (fact "search new entries" (let [entry-key "PI:KEY:<KEY>END_PI" entry-doc "最新のエントリ" search-query "新のエン"] (t-common/search-entries search-query 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries search-query 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "kuromoji analyzer" (with-state-changes [(before :facts (t-common/prepare! t-common/kuromoji-analyzer nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "search exists entries" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-ja-1 [2 0])) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 0)) (fact "search new entries" (let [entry-key "PI:KEY:<KEY>END_PI" entry-doc "最新のエントリ"] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 entry-key))))) (facts "with stop-words" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer t-fixture/stop-words-en) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "standard analyzer" (t-common/search-entries "Heo" 10) => (t-common/results-is-valid? 0))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-en) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer (en)" (t-common/search-entries "Heo" 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-ja) nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer (ja)" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-en) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer with phrase search (en)" (t-common/phrase-search-entries "PI:NAME:<NAME>END_PI" 10) => (t-common/results-is-valid? 0))) (with-state-changes [(before :facts (t-common/prepare! (analysis/ngram-analyzer 2 8 t-fixture/stop-words-ja) nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "ngram analyzer with phrase search (ja)" (t-common/phrase-search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/phrase-search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (t-common/prepare! (analysis/cjk-analyzer t-fixture/stop-words-ja) nil t-fixture/entries-ja-1)) (after :facts (t-common/finish!))] (fact "cjk analyzer" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 1))) (with-state-changes [(before :facts (let [ana (analysis/kuromoji-analyzer nil :search t-fixture/stop-words-ja #{})] (t-common/prepare! ana nil t-fixture/entries-ja-1))) (after :facts (t-common/finish!))] (fact "kuromoji analyzer" (t-common/search-entries t-fixture/entries-ja-1-search-1 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-2 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-3 10) => (t-common/results-is-valid? 0) (t-common/search-entries t-fixture/entries-ja-1-search-4 10) => (t-common/results-is-valid? 1) (t-common/search-entries t-fixture/entries-ja-1-search-5 10) => (t-common/results-is-valid? 0)))) (facts "modify exists entries" (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "update" (let [[k doc] (first t-fixture/entries-en-1) new-doc "zzz"] (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! k new-doc) => nil (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 1 k))) (fact "delete" (let [[k doc] (first t-fixture/entries-en-1)] (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) (t-common/delete-entry! k) => nil (t-common/search-entries doc 10) => (t-common/results-is-valid? 0))))) (facts "search utilities" (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer)) (after :facts (t-common/finish!))] (fact "use non-string keys" (t-common/add-entry! "dummy" "") (let [entry-key PI:KEY:<KEY>END_PI entry-doc (str entry-key)] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key "") => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 (str entry-key)) (t-common/delete-entry! entry-key) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0)) (let [entry-key :test entry-doc (name entry-key)] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key "") => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 (name entry-key)) (t-common/delete-entry! entry-key) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0)) (let [entry-key (PI:KEY:<KEY>END_PI) entry-doc (str entry-key)] (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! entry-key "") => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0) (t-common/update-entry! entry-key entry-doc) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 1 (str entry-key)) (t-common/delete-entry! entry-key) => nil (t-common/search-entries entry-doc 10) => (t-common/results-is-valid? 0))) (fact "with pagination" (let [doc-prefix "with pagination"] (dotimes [i 105] (let [index (+ i 50000) doc (str doc-prefix index)] (t-common/add-entry! (str index) doc))) (t-common/search-entries doc-prefix 100 0 10) => (t-common/results-is-valid? 10) (t-common/search-entries doc-prefix 19 1 10) => (t-common/results-is-valid? 9) (t-common/search-entries doc-prefix 200 10 10) => (t-common/results-is-valid? 5) (t-common/search-entries doc-prefix 200 0 200) => (t-common/results-is-valid? 105) (t-common/search-entries doc-prefix 200 200 200) => (t-common/results-is-valid? 0) (t-common/search-entries doc-prefix 5 200 5) => (t-common/results-is-valid? 0) (t-common/search-entries doc-prefix 8 0 200) => (t-common/results-is-valid? 8))))) (run-testset! t-fixture/testset-kw-s) (run-testset! t-fixture/testset-kw-w) (run-testset! t-fixture/testset-kw-q) (run-testset! t-fixture/testset-std-s) (run-testset! t-fixture/testset-std-p) (run-testset! t-fixture/testset-std-q) (run-testset! t-fixture/testset-cjk-s) (run-testset! t-fixture/testset-cjk-p) (run-testset! t-fixture/testset-cjk-q) (run-testset! t-fixture/testset-kuro-s) (run-testset! t-fixture/testset-kuro-p) (run-testset! t-fixture/testset-kuro-q) (run-testset! t-fixture/testset-ngram-s) (run-testset! t-fixture/testset-ngram-p) (run-testset! t-fixture/testset-ngram-q) (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (letfn [(parse-query [^String s] (.parse (StandardQueryParser. t-common/standard-analyzer) s "doc"))] (fact "raw query search" (core/search @t-common/test-store (parse-query "doc:20130819") 10) => (t-common/results-is-valid? 1) (core/search @t-common/test-store (parse-query "Hello Tokyo") 10) => (t-common/results-is-valid? 2) (core/search @t-common/test-store (parse-query "Hello AND Tokyo") 10) => (t-common/results-is-valid? 0)))) (facts "abnormal usage" (with-state-changes [(before :facts (t-common/prepare! nil nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "manipulate with default analyzer" (let [[k doc] (first t-fixture/entries-en-1) new-doc "newer"] (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) (core/update! @t-common/test-store {:key k, :doc new-doc} [:key :doc] :key k) (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 1 k) (core/delete! @t-common/test-store :key k) (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/search-entries new-doc 10) => (t-common/results-is-valid? 0))) (fact "without index" (let [k "new-key" doc "this_is_new_entry"] (core/add! @t-common/test-store [{:key k, :doc doc}] []) (t-common/search-entries doc 10) => (t-common/results-is-valid? 0))))) (let [tmp-store-path (t-common/get-tmp-dir) k "123" doc "abc"] (with-state-changes [(before :facts (t-common/prepare! t-common/standard-analyzer tmp-store-path)) (after :facts (t-common/finish! tmp-store-path))] (fact "disk store" (t-common/add-entry! "dummy" "") (t-common/search-entries doc 10) => (t-common/results-is-valid? 0) (t-common/add-entry! k doc) => nil (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k) ;; Switch to another session (store/close! @t-common/test-store) (reset! t-common/test-store (store/disk-store tmp-store-path)) (t-common/search-entries doc 10) => (t-common/results-is-valid? 1 k)))) (facts "add!" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (core/add! @t-common/test-store [{:key "PI:KEY:<KEY>END_PI", :doc "abc"}] [:key :doc]) => nil? (core/add! @t-common/test-store [{:key "PI:KEY:<KEY>END_PI", :doc "def"}] [:key :doc] (analysis/standard-analyzer)) => nil?) (fact "with writer" (with-open [writer (store/store-writer @t-common/test-store (analysis/standard-analyzer))] (core/add! writer [{:key "1PI:KEY:<KEY>END_PI", :doc "abc"}] [:key :doc]) => nil? (core/add! writer [{:key "PI:KEY:<KEY>END_PI", :doc "def"}] [:key :doc] (analysis/standard-analyzer)) => (throws clojure.lang.ArityException))))) (facts "update!" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (core/update! @t-common/test-store {:key "2", :doc "Hello world"} [:key :doc] :key "2") => nil? (core/update! @t-common/test-store {:key "3", :doc "Osaka station"} [:key :doc] :key "3" (analysis/standard-analyzer)) => nil?) (fact "with writer" (with-open [writer (store/store-writer @t-common/test-store (analysis/standard-analyzer))] (core/update! writer {:key "2", :doc "Hello world"} [:key :doc] :key "2") => nil? (core/update! writer {:key "3", :doc "Osaka station"} [:key :doc] :key "3" (analysis/standard-analyzer)) => (throws clojure.lang.ArityException))))) (facts "delete!" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (core/delete! @t-common/test-store :key "1") => nil? (core/delete! @t-common/test-store :key "2" (analysis/standard-analyzer)) => nil?) (fact "with writer" (with-open [writer (store/store-writer @t-common/test-store (analysis/standard-analyzer))] (core/delete! writer :key "1") => nil? (core/delete! writer :key "2" (analysis/standard-analyzer)) => (throws clojure.lang.ArityException))))) (facts "search*" (with-state-changes [(before :facts (t-common/prepare! (analysis/standard-analyzer) nil t-fixture/entries-en-1)) (after :facts (t-common/finish!))] (fact "with store" (#'core/search* :query @t-common/test-store [{:doc t-fixture/entries-en-1-search-1}] 10 (analysis/standard-analyzer) 0 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0]))) (fact "with reader" (with-open [reader (store/store-reader @t-common/test-store)] (#'core/search* :query reader [{:doc t-fixture/entries-en-1-search-1}] 10 (analysis/standard-analyzer) 0 10) => (t-common/results-is-valid? 1 (get-in t-fixture/entries-en-1 [0 0]))))))
[ { "context": " kind of structure:\n {:user {:eppn \\\"\\\"eppn\\\" \\\"developer\\\"\n :email \\\"developer@e.mail\\\"\n ", "end": 9506, "score": 0.9623945355415344, "start": 9497, "tag": "USERNAME", "value": "developer" }, { "context": "eppn \\\"\\\"eppn\\\" \\\"developer\\\"\n :email \\\"developer@e.mail\\\"\n :displayName \\\"deve\\\"\n :su", "end": 9545, "score": 0.9755480885505676, "start": 9529, "tag": "EMAIL", "value": "developer@e.mail" }, { "context": "il \\\"developer@e.mail\\\"\n :displayName \\\"deve\\\"\n :surname \\\"loper\\\"\n ...}\n ", "end": 9578, "score": 0.9959245324134827, "start": 9574, "tag": "NAME", "value": "deve" }, { "context": " :displayName \\\"deve\\\"\n :surname \\\"loper\\\"\n ...}\n :roles [\\\"applicant\\\" \\\"app", "end": 9608, "score": 0.9980555772781372, "start": 9603, "tag": "NAME", "value": "loper" } ]
src/cljs/rems/spa.cljs
secureb2share/secureb2share-rems
0
(ns rems.spa (:require [reagent.core :as r] [re-frame.core :as rf :refer [dispatch reg-event-db reg-event-fx reg-sub reg-fx]] [secretary.core :as secretary] [goog.events :as events] [goog.history.EventType :as HistoryEventType] [markdown.core :refer [md->html]] [rems.actions :refer [actions-page fetch-actions]] [rems.administration :refer [administration-page]] [rems.administration.catalogue-item :refer [create-catalogue-item-page]] [rems.administration.form :refer [create-form-page]] [rems.administration.license :refer [create-license-page]] [rems.administration.resource :refer [create-resource-page]] [rems.administration.workflow :refer [create-workflow-page]] [rems.ajax :refer [load-interceptors!]] [rems.application :refer [application-page]] [rems.applications :refer [applications-page]] [rems.atoms :as atoms] [rems.auth.auth :as auth] [rems.cart :as cart] [rems.catalogue :refer [catalogue-page]] [rems.config :as config] [rems.guide-page :refer [guide-page]] [rems.navbar :as nav] [rems.new-application :refer [new-application-page]] [rems.text :refer [text]] [rems.util :refer [dispatch! fetch]]) (:require-macros [rems.read-gitlog :refer [read-current-version]]) (:import goog.History)) ;;; subscriptions (reg-sub :page (fn [db _] (:page db))) (reg-sub :docs (fn [db _] (:docs db))) ;; TODO: possibly move translations out (reg-sub :translations (fn [db _] (:translations db))) (reg-sub :language (fn [db _] (:language db))) (reg-sub :languages (fn [db _] (:languages db))) (reg-sub :default-language (fn [db _] (:default-language db))) ;; TODO: possibly move theme out (reg-sub :theme (fn [db _] (:theme db))) (reg-sub :identity (fn [db _] (:identity db))) (reg-sub :user (fn [db _] (get-in db [:identity :user]))) (reg-sub :roles (fn [db _] (get-in db [:identity :roles]))) ;;; handlers (reg-event-db :initialize-db (fn [_ _] {:page :home :language :en :languages [:en] :default-language :en :translations {} :identity {:user nil :roles nil}})) (reg-event-db :set-active-page (fn [db [_ page]] (assoc db :page page))) (reg-event-db :set-docs (fn [db [_ docs]] (assoc db :docs docs))) (reg-event-db :loaded-translations (fn [db [_ translations]] (assoc db :translations translations))) (reg-event-db :loaded-theme (fn [db [_ theme]] (assoc db :theme theme))) (reg-event-db :set-identity (fn [db [_ identity]] (assoc db :identity identity))) (reg-event-fx :set-current-language (fn [{:keys [db]} [_ language]] {:db (assoc db :language language) :update-document-language (name language)})) (reg-fx :update-document-language (fn [language] (set! (.. js/document -documentElement -lang) language))) (reg-event-fx :unauthorized! (fn [_ [_ current-url]] (println "Received unauthorized from" current-url) (.setItem js/sessionStorage "rems-redirect-url" current-url) (dispatch! "/"))) (reg-event-fx :forbidden! (fn [_ [_ current-url]] (println "Received forbidden from" current-url) {:dispatch [:set-active-page :forbidden]})) (reg-event-fx :landing-page-redirect! (fn [{:keys [db]}] ;; do we have the roles set by set-identity already? (if (get-in db [:identity :roles]) (let [roles (get-in db [:identity :roles])] (println "Selecting landing page based on roles" roles) (.removeItem js/sessionStorage "rems-redirect-url") (cond (contains? roles :owner) (dispatch! "/#/administration") (contains? roles :approver) (dispatch! "/#/actions") (contains? roles :reviewer) (dispatch! "/#/actions") :else (dispatch! "/#/catalogue")) {}) ;;; else dispatch the same event again while waiting for set-identity (happens especially with Firefox) {:dispatch [:landing-page-redirect!]}))) (defn about-page [] [:div.container [:div.row [:div.col-md-12 (text :t.about/text)]]]) (defn home-page [] (if @(rf/subscribe [:user]) ;; TODO this is a hack to show something useful on the home page ;; when we are logged in. We can't really perform a dispatch! ;; here, because that would be a race condition with #fragment ;; handling in hook-history-navigation! ;; ;; One possibility is to have a separate :init default page that ;; does the navigation/redirect logic, instead of using :home as ;; the default. (do (rf/dispatch [:rems.catalogue/enter-page]) [catalogue-page]) [auth/login-component])) (defn unauthorized-page [] [:div [:h2 (text :t.unauthorized-page/unauthorized)] [:p (text :t.unauthorized-page/you-are-unauthorized)]]) (defn forbidden-page [] [:div [:h2 (text :t.forbidden-page/forbidden)] [:p (text :t.forbidden-page/you-are-forbidden)]]) (defn not-found-page [] [:div [:h2 (text :t.not-found-page/not-found)] [:p (text :t.not-found-page/page-was-not-found)]]) (def pages {:home home-page :catalogue catalogue-page :guide guide-page :about about-page :actions actions-page :application application-page :new-application new-application-page :applications applications-page :administration administration-page :create-catalogue-item create-catalogue-item-page :create-form create-form-page :create-license create-license-page :create-resource create-resource-page :create-workflow create-workflow-page :unauthorized unauthorized-page :forbidden forbidden-page :not-found not-found-page}) (defn footer [] [:footer.footer [:div.container [:nav.navbar [:div.navbar-text (text :t/footer)] (when-let [{:keys [version revision repo-url]} (read-current-version)] [:div#footer-release-number [:a {:href (str repo-url revision)} version]])]]]) (defn logo [] [:div.logo [:div.container.img]]) (defn page [] (let [page-id @(rf/subscribe [:page]) content (pages page-id)] [:div [nav/navigation-widget page-id] [logo] [:div.container.main-content [content]] [footer]])) ;; ------------------------- ;; Routes (secretary/set-config! :prefix "#") (secretary/defroute "/" [] (rf/dispatch [:set-active-page :home])) (secretary/defroute "/catalogue" [] (rf/dispatch [:rems.catalogue/enter-page]) (rf/dispatch [:set-active-page :catalogue])) (secretary/defroute "/guide" [] (rf/dispatch [:set-active-page :guide])) (secretary/defroute "/about" [] (rf/dispatch [:set-active-page :about])) (secretary/defroute "/actions" [] (rf/dispatch [:rems.actions/enter-page]) (rf/dispatch [:set-active-page :actions])) (secretary/defroute "/application/:id" {id :id} (rf/dispatch [:rems.application/enter-application-page id]) (rf/dispatch [:set-active-page :application])) (secretary/defroute "/application" {{items :items} :query-params} (rf/dispatch [:rems.new-application/enter-new-application-page (cart/parse-items items)]) (rf/dispatch [:set-active-page :new-application])) (secretary/defroute "/applications" [] (rf/dispatch [:rems.applications/enter-page]) (rf/dispatch [:set-active-page :applications])) (secretary/defroute "/administration" [] (rf/dispatch [:rems.administration/enter-page]) (rf/dispatch [:set-active-page :administration])) (secretary/defroute "/create-catalogue-item" [] (rf/dispatch [:rems.administration.catalogue-item/enter-page]) (rf/dispatch [:set-active-page :create-catalogue-item])) (secretary/defroute "/create-form" [] (rf/dispatch [:rems.administration.form/enter-page]) (rf/dispatch [:set-active-page :create-form])) (secretary/defroute "/create-license" [] (rf/dispatch [:rems.administration.license/enter-page]) (rf/dispatch [:set-active-page :create-license])) (secretary/defroute "/create-resource" [] (rf/dispatch [:rems.administration.resource/enter-page]) (rf/dispatch [:set-active-page :create-resource])) (secretary/defroute "/create-workflow" [] (rf/dispatch [:rems.administration.workflow/enter-page]) (rf/dispatch [:set-active-page :create-workflow])) (secretary/defroute "/unauthorized" [] (rf/dispatch [:set-active-page :unauthorized])) (secretary/defroute "/forbidden" [] (rf/dispatch [:set-active-page :forbidden])) (secretary/defroute "/redirect" [] ;; user is logged in so redirect to a more specific page (if-let [url (.getItem js/sessionStorage "rems-redirect-url")] (do (println "Redirecting to" url "after authorization") (.removeItem js/sessionStorage "rems-redirect-url") (dispatch! url)) (rf/dispatch [:landing-page-redirect!]))) (secretary/defroute "*" [] (rf/dispatch [:set-active-page :not-found])) ;; ------------------------- ;; History ;; must be called after routes have been defined (defn hook-browser-navigation! [] (doto (History.) (events/listen HistoryEventType/NAVIGATE (fn [event] (js/window.rems.hooks.navigate (.-token event)) (secretary/dispatch! (.-token event)))) (.setEnabled true))) ;; ------------------------- ;; Initialize app (defn set-identity! "Receives as a parameter following kind of structure: {:user {:eppn \"\"eppn\" \"developer\" :email \"developer@e.mail\" :displayName \"deve\" :surname \"loper\" ...} :roles [\"applicant\" \"approver\"]} Roles are converted to clojure keywords inside the function before dispatching" [user-and-roles] (let [user-and-roles (js->clj user-and-roles :keywordize-keys true)] (rf/dispatch-sync [:set-identity (if (:user user-and-roles) (assoc user-and-roles :roles (set (map keyword (:roles user-and-roles)))) user-and-roles)]))) (defn fetch-translations! [] (fetch "/api/translations" {:handler #(rf/dispatch [:loaded-translations %])})) (defn fetch-theme! [] (fetch "/api/theme" {:handler #(rf/dispatch [:loaded-theme %])})) (defn mount-components [] (rf/clear-subscription-cache!) (r/render [page] (.getElementById js/document "app"))) (defn init! [] (rf/dispatch-sync [:initialize-db]) (load-interceptors!) (fetch-translations!) (fetch-theme!) (config/fetch-config!) (hook-browser-navigation!) (mount-components))
54545
(ns rems.spa (:require [reagent.core :as r] [re-frame.core :as rf :refer [dispatch reg-event-db reg-event-fx reg-sub reg-fx]] [secretary.core :as secretary] [goog.events :as events] [goog.history.EventType :as HistoryEventType] [markdown.core :refer [md->html]] [rems.actions :refer [actions-page fetch-actions]] [rems.administration :refer [administration-page]] [rems.administration.catalogue-item :refer [create-catalogue-item-page]] [rems.administration.form :refer [create-form-page]] [rems.administration.license :refer [create-license-page]] [rems.administration.resource :refer [create-resource-page]] [rems.administration.workflow :refer [create-workflow-page]] [rems.ajax :refer [load-interceptors!]] [rems.application :refer [application-page]] [rems.applications :refer [applications-page]] [rems.atoms :as atoms] [rems.auth.auth :as auth] [rems.cart :as cart] [rems.catalogue :refer [catalogue-page]] [rems.config :as config] [rems.guide-page :refer [guide-page]] [rems.navbar :as nav] [rems.new-application :refer [new-application-page]] [rems.text :refer [text]] [rems.util :refer [dispatch! fetch]]) (:require-macros [rems.read-gitlog :refer [read-current-version]]) (:import goog.History)) ;;; subscriptions (reg-sub :page (fn [db _] (:page db))) (reg-sub :docs (fn [db _] (:docs db))) ;; TODO: possibly move translations out (reg-sub :translations (fn [db _] (:translations db))) (reg-sub :language (fn [db _] (:language db))) (reg-sub :languages (fn [db _] (:languages db))) (reg-sub :default-language (fn [db _] (:default-language db))) ;; TODO: possibly move theme out (reg-sub :theme (fn [db _] (:theme db))) (reg-sub :identity (fn [db _] (:identity db))) (reg-sub :user (fn [db _] (get-in db [:identity :user]))) (reg-sub :roles (fn [db _] (get-in db [:identity :roles]))) ;;; handlers (reg-event-db :initialize-db (fn [_ _] {:page :home :language :en :languages [:en] :default-language :en :translations {} :identity {:user nil :roles nil}})) (reg-event-db :set-active-page (fn [db [_ page]] (assoc db :page page))) (reg-event-db :set-docs (fn [db [_ docs]] (assoc db :docs docs))) (reg-event-db :loaded-translations (fn [db [_ translations]] (assoc db :translations translations))) (reg-event-db :loaded-theme (fn [db [_ theme]] (assoc db :theme theme))) (reg-event-db :set-identity (fn [db [_ identity]] (assoc db :identity identity))) (reg-event-fx :set-current-language (fn [{:keys [db]} [_ language]] {:db (assoc db :language language) :update-document-language (name language)})) (reg-fx :update-document-language (fn [language] (set! (.. js/document -documentElement -lang) language))) (reg-event-fx :unauthorized! (fn [_ [_ current-url]] (println "Received unauthorized from" current-url) (.setItem js/sessionStorage "rems-redirect-url" current-url) (dispatch! "/"))) (reg-event-fx :forbidden! (fn [_ [_ current-url]] (println "Received forbidden from" current-url) {:dispatch [:set-active-page :forbidden]})) (reg-event-fx :landing-page-redirect! (fn [{:keys [db]}] ;; do we have the roles set by set-identity already? (if (get-in db [:identity :roles]) (let [roles (get-in db [:identity :roles])] (println "Selecting landing page based on roles" roles) (.removeItem js/sessionStorage "rems-redirect-url") (cond (contains? roles :owner) (dispatch! "/#/administration") (contains? roles :approver) (dispatch! "/#/actions") (contains? roles :reviewer) (dispatch! "/#/actions") :else (dispatch! "/#/catalogue")) {}) ;;; else dispatch the same event again while waiting for set-identity (happens especially with Firefox) {:dispatch [:landing-page-redirect!]}))) (defn about-page [] [:div.container [:div.row [:div.col-md-12 (text :t.about/text)]]]) (defn home-page [] (if @(rf/subscribe [:user]) ;; TODO this is a hack to show something useful on the home page ;; when we are logged in. We can't really perform a dispatch! ;; here, because that would be a race condition with #fragment ;; handling in hook-history-navigation! ;; ;; One possibility is to have a separate :init default page that ;; does the navigation/redirect logic, instead of using :home as ;; the default. (do (rf/dispatch [:rems.catalogue/enter-page]) [catalogue-page]) [auth/login-component])) (defn unauthorized-page [] [:div [:h2 (text :t.unauthorized-page/unauthorized)] [:p (text :t.unauthorized-page/you-are-unauthorized)]]) (defn forbidden-page [] [:div [:h2 (text :t.forbidden-page/forbidden)] [:p (text :t.forbidden-page/you-are-forbidden)]]) (defn not-found-page [] [:div [:h2 (text :t.not-found-page/not-found)] [:p (text :t.not-found-page/page-was-not-found)]]) (def pages {:home home-page :catalogue catalogue-page :guide guide-page :about about-page :actions actions-page :application application-page :new-application new-application-page :applications applications-page :administration administration-page :create-catalogue-item create-catalogue-item-page :create-form create-form-page :create-license create-license-page :create-resource create-resource-page :create-workflow create-workflow-page :unauthorized unauthorized-page :forbidden forbidden-page :not-found not-found-page}) (defn footer [] [:footer.footer [:div.container [:nav.navbar [:div.navbar-text (text :t/footer)] (when-let [{:keys [version revision repo-url]} (read-current-version)] [:div#footer-release-number [:a {:href (str repo-url revision)} version]])]]]) (defn logo [] [:div.logo [:div.container.img]]) (defn page [] (let [page-id @(rf/subscribe [:page]) content (pages page-id)] [:div [nav/navigation-widget page-id] [logo] [:div.container.main-content [content]] [footer]])) ;; ------------------------- ;; Routes (secretary/set-config! :prefix "#") (secretary/defroute "/" [] (rf/dispatch [:set-active-page :home])) (secretary/defroute "/catalogue" [] (rf/dispatch [:rems.catalogue/enter-page]) (rf/dispatch [:set-active-page :catalogue])) (secretary/defroute "/guide" [] (rf/dispatch [:set-active-page :guide])) (secretary/defroute "/about" [] (rf/dispatch [:set-active-page :about])) (secretary/defroute "/actions" [] (rf/dispatch [:rems.actions/enter-page]) (rf/dispatch [:set-active-page :actions])) (secretary/defroute "/application/:id" {id :id} (rf/dispatch [:rems.application/enter-application-page id]) (rf/dispatch [:set-active-page :application])) (secretary/defroute "/application" {{items :items} :query-params} (rf/dispatch [:rems.new-application/enter-new-application-page (cart/parse-items items)]) (rf/dispatch [:set-active-page :new-application])) (secretary/defroute "/applications" [] (rf/dispatch [:rems.applications/enter-page]) (rf/dispatch [:set-active-page :applications])) (secretary/defroute "/administration" [] (rf/dispatch [:rems.administration/enter-page]) (rf/dispatch [:set-active-page :administration])) (secretary/defroute "/create-catalogue-item" [] (rf/dispatch [:rems.administration.catalogue-item/enter-page]) (rf/dispatch [:set-active-page :create-catalogue-item])) (secretary/defroute "/create-form" [] (rf/dispatch [:rems.administration.form/enter-page]) (rf/dispatch [:set-active-page :create-form])) (secretary/defroute "/create-license" [] (rf/dispatch [:rems.administration.license/enter-page]) (rf/dispatch [:set-active-page :create-license])) (secretary/defroute "/create-resource" [] (rf/dispatch [:rems.administration.resource/enter-page]) (rf/dispatch [:set-active-page :create-resource])) (secretary/defroute "/create-workflow" [] (rf/dispatch [:rems.administration.workflow/enter-page]) (rf/dispatch [:set-active-page :create-workflow])) (secretary/defroute "/unauthorized" [] (rf/dispatch [:set-active-page :unauthorized])) (secretary/defroute "/forbidden" [] (rf/dispatch [:set-active-page :forbidden])) (secretary/defroute "/redirect" [] ;; user is logged in so redirect to a more specific page (if-let [url (.getItem js/sessionStorage "rems-redirect-url")] (do (println "Redirecting to" url "after authorization") (.removeItem js/sessionStorage "rems-redirect-url") (dispatch! url)) (rf/dispatch [:landing-page-redirect!]))) (secretary/defroute "*" [] (rf/dispatch [:set-active-page :not-found])) ;; ------------------------- ;; History ;; must be called after routes have been defined (defn hook-browser-navigation! [] (doto (History.) (events/listen HistoryEventType/NAVIGATE (fn [event] (js/window.rems.hooks.navigate (.-token event)) (secretary/dispatch! (.-token event)))) (.setEnabled true))) ;; ------------------------- ;; Initialize app (defn set-identity! "Receives as a parameter following kind of structure: {:user {:eppn \"\"eppn\" \"developer\" :email \"<EMAIL>\" :displayName \"<NAME>\" :surname \"<NAME>\" ...} :roles [\"applicant\" \"approver\"]} Roles are converted to clojure keywords inside the function before dispatching" [user-and-roles] (let [user-and-roles (js->clj user-and-roles :keywordize-keys true)] (rf/dispatch-sync [:set-identity (if (:user user-and-roles) (assoc user-and-roles :roles (set (map keyword (:roles user-and-roles)))) user-and-roles)]))) (defn fetch-translations! [] (fetch "/api/translations" {:handler #(rf/dispatch [:loaded-translations %])})) (defn fetch-theme! [] (fetch "/api/theme" {:handler #(rf/dispatch [:loaded-theme %])})) (defn mount-components [] (rf/clear-subscription-cache!) (r/render [page] (.getElementById js/document "app"))) (defn init! [] (rf/dispatch-sync [:initialize-db]) (load-interceptors!) (fetch-translations!) (fetch-theme!) (config/fetch-config!) (hook-browser-navigation!) (mount-components))
true
(ns rems.spa (:require [reagent.core :as r] [re-frame.core :as rf :refer [dispatch reg-event-db reg-event-fx reg-sub reg-fx]] [secretary.core :as secretary] [goog.events :as events] [goog.history.EventType :as HistoryEventType] [markdown.core :refer [md->html]] [rems.actions :refer [actions-page fetch-actions]] [rems.administration :refer [administration-page]] [rems.administration.catalogue-item :refer [create-catalogue-item-page]] [rems.administration.form :refer [create-form-page]] [rems.administration.license :refer [create-license-page]] [rems.administration.resource :refer [create-resource-page]] [rems.administration.workflow :refer [create-workflow-page]] [rems.ajax :refer [load-interceptors!]] [rems.application :refer [application-page]] [rems.applications :refer [applications-page]] [rems.atoms :as atoms] [rems.auth.auth :as auth] [rems.cart :as cart] [rems.catalogue :refer [catalogue-page]] [rems.config :as config] [rems.guide-page :refer [guide-page]] [rems.navbar :as nav] [rems.new-application :refer [new-application-page]] [rems.text :refer [text]] [rems.util :refer [dispatch! fetch]]) (:require-macros [rems.read-gitlog :refer [read-current-version]]) (:import goog.History)) ;;; subscriptions (reg-sub :page (fn [db _] (:page db))) (reg-sub :docs (fn [db _] (:docs db))) ;; TODO: possibly move translations out (reg-sub :translations (fn [db _] (:translations db))) (reg-sub :language (fn [db _] (:language db))) (reg-sub :languages (fn [db _] (:languages db))) (reg-sub :default-language (fn [db _] (:default-language db))) ;; TODO: possibly move theme out (reg-sub :theme (fn [db _] (:theme db))) (reg-sub :identity (fn [db _] (:identity db))) (reg-sub :user (fn [db _] (get-in db [:identity :user]))) (reg-sub :roles (fn [db _] (get-in db [:identity :roles]))) ;;; handlers (reg-event-db :initialize-db (fn [_ _] {:page :home :language :en :languages [:en] :default-language :en :translations {} :identity {:user nil :roles nil}})) (reg-event-db :set-active-page (fn [db [_ page]] (assoc db :page page))) (reg-event-db :set-docs (fn [db [_ docs]] (assoc db :docs docs))) (reg-event-db :loaded-translations (fn [db [_ translations]] (assoc db :translations translations))) (reg-event-db :loaded-theme (fn [db [_ theme]] (assoc db :theme theme))) (reg-event-db :set-identity (fn [db [_ identity]] (assoc db :identity identity))) (reg-event-fx :set-current-language (fn [{:keys [db]} [_ language]] {:db (assoc db :language language) :update-document-language (name language)})) (reg-fx :update-document-language (fn [language] (set! (.. js/document -documentElement -lang) language))) (reg-event-fx :unauthorized! (fn [_ [_ current-url]] (println "Received unauthorized from" current-url) (.setItem js/sessionStorage "rems-redirect-url" current-url) (dispatch! "/"))) (reg-event-fx :forbidden! (fn [_ [_ current-url]] (println "Received forbidden from" current-url) {:dispatch [:set-active-page :forbidden]})) (reg-event-fx :landing-page-redirect! (fn [{:keys [db]}] ;; do we have the roles set by set-identity already? (if (get-in db [:identity :roles]) (let [roles (get-in db [:identity :roles])] (println "Selecting landing page based on roles" roles) (.removeItem js/sessionStorage "rems-redirect-url") (cond (contains? roles :owner) (dispatch! "/#/administration") (contains? roles :approver) (dispatch! "/#/actions") (contains? roles :reviewer) (dispatch! "/#/actions") :else (dispatch! "/#/catalogue")) {}) ;;; else dispatch the same event again while waiting for set-identity (happens especially with Firefox) {:dispatch [:landing-page-redirect!]}))) (defn about-page [] [:div.container [:div.row [:div.col-md-12 (text :t.about/text)]]]) (defn home-page [] (if @(rf/subscribe [:user]) ;; TODO this is a hack to show something useful on the home page ;; when we are logged in. We can't really perform a dispatch! ;; here, because that would be a race condition with #fragment ;; handling in hook-history-navigation! ;; ;; One possibility is to have a separate :init default page that ;; does the navigation/redirect logic, instead of using :home as ;; the default. (do (rf/dispatch [:rems.catalogue/enter-page]) [catalogue-page]) [auth/login-component])) (defn unauthorized-page [] [:div [:h2 (text :t.unauthorized-page/unauthorized)] [:p (text :t.unauthorized-page/you-are-unauthorized)]]) (defn forbidden-page [] [:div [:h2 (text :t.forbidden-page/forbidden)] [:p (text :t.forbidden-page/you-are-forbidden)]]) (defn not-found-page [] [:div [:h2 (text :t.not-found-page/not-found)] [:p (text :t.not-found-page/page-was-not-found)]]) (def pages {:home home-page :catalogue catalogue-page :guide guide-page :about about-page :actions actions-page :application application-page :new-application new-application-page :applications applications-page :administration administration-page :create-catalogue-item create-catalogue-item-page :create-form create-form-page :create-license create-license-page :create-resource create-resource-page :create-workflow create-workflow-page :unauthorized unauthorized-page :forbidden forbidden-page :not-found not-found-page}) (defn footer [] [:footer.footer [:div.container [:nav.navbar [:div.navbar-text (text :t/footer)] (when-let [{:keys [version revision repo-url]} (read-current-version)] [:div#footer-release-number [:a {:href (str repo-url revision)} version]])]]]) (defn logo [] [:div.logo [:div.container.img]]) (defn page [] (let [page-id @(rf/subscribe [:page]) content (pages page-id)] [:div [nav/navigation-widget page-id] [logo] [:div.container.main-content [content]] [footer]])) ;; ------------------------- ;; Routes (secretary/set-config! :prefix "#") (secretary/defroute "/" [] (rf/dispatch [:set-active-page :home])) (secretary/defroute "/catalogue" [] (rf/dispatch [:rems.catalogue/enter-page]) (rf/dispatch [:set-active-page :catalogue])) (secretary/defroute "/guide" [] (rf/dispatch [:set-active-page :guide])) (secretary/defroute "/about" [] (rf/dispatch [:set-active-page :about])) (secretary/defroute "/actions" [] (rf/dispatch [:rems.actions/enter-page]) (rf/dispatch [:set-active-page :actions])) (secretary/defroute "/application/:id" {id :id} (rf/dispatch [:rems.application/enter-application-page id]) (rf/dispatch [:set-active-page :application])) (secretary/defroute "/application" {{items :items} :query-params} (rf/dispatch [:rems.new-application/enter-new-application-page (cart/parse-items items)]) (rf/dispatch [:set-active-page :new-application])) (secretary/defroute "/applications" [] (rf/dispatch [:rems.applications/enter-page]) (rf/dispatch [:set-active-page :applications])) (secretary/defroute "/administration" [] (rf/dispatch [:rems.administration/enter-page]) (rf/dispatch [:set-active-page :administration])) (secretary/defroute "/create-catalogue-item" [] (rf/dispatch [:rems.administration.catalogue-item/enter-page]) (rf/dispatch [:set-active-page :create-catalogue-item])) (secretary/defroute "/create-form" [] (rf/dispatch [:rems.administration.form/enter-page]) (rf/dispatch [:set-active-page :create-form])) (secretary/defroute "/create-license" [] (rf/dispatch [:rems.administration.license/enter-page]) (rf/dispatch [:set-active-page :create-license])) (secretary/defroute "/create-resource" [] (rf/dispatch [:rems.administration.resource/enter-page]) (rf/dispatch [:set-active-page :create-resource])) (secretary/defroute "/create-workflow" [] (rf/dispatch [:rems.administration.workflow/enter-page]) (rf/dispatch [:set-active-page :create-workflow])) (secretary/defroute "/unauthorized" [] (rf/dispatch [:set-active-page :unauthorized])) (secretary/defroute "/forbidden" [] (rf/dispatch [:set-active-page :forbidden])) (secretary/defroute "/redirect" [] ;; user is logged in so redirect to a more specific page (if-let [url (.getItem js/sessionStorage "rems-redirect-url")] (do (println "Redirecting to" url "after authorization") (.removeItem js/sessionStorage "rems-redirect-url") (dispatch! url)) (rf/dispatch [:landing-page-redirect!]))) (secretary/defroute "*" [] (rf/dispatch [:set-active-page :not-found])) ;; ------------------------- ;; History ;; must be called after routes have been defined (defn hook-browser-navigation! [] (doto (History.) (events/listen HistoryEventType/NAVIGATE (fn [event] (js/window.rems.hooks.navigate (.-token event)) (secretary/dispatch! (.-token event)))) (.setEnabled true))) ;; ------------------------- ;; Initialize app (defn set-identity! "Receives as a parameter following kind of structure: {:user {:eppn \"\"eppn\" \"developer\" :email \"PI:EMAIL:<EMAIL>END_PI\" :displayName \"PI:NAME:<NAME>END_PI\" :surname \"PI:NAME:<NAME>END_PI\" ...} :roles [\"applicant\" \"approver\"]} Roles are converted to clojure keywords inside the function before dispatching" [user-and-roles] (let [user-and-roles (js->clj user-and-roles :keywordize-keys true)] (rf/dispatch-sync [:set-identity (if (:user user-and-roles) (assoc user-and-roles :roles (set (map keyword (:roles user-and-roles)))) user-and-roles)]))) (defn fetch-translations! [] (fetch "/api/translations" {:handler #(rf/dispatch [:loaded-translations %])})) (defn fetch-theme! [] (fetch "/api/theme" {:handler #(rf/dispatch [:loaded-theme %])})) (defn mount-components [] (rf/clear-subscription-cache!) (r/render [page] (.getElementById js/document "app"))) (defn init! [] (rf/dispatch-sync [:initialize-db]) (load-interceptors!) (fetch-translations!) (fetch-theme!) (config/fetch-config!) (hook-browser-navigation!) (mount-components))
[ { "context": " merge\n {:Username username\n :Password passwo", "end": 745, "score": 0.997951328754425, "start": 737, "tag": "USERNAME", "value": "username" }, { "context": "sername\n :Password password}))))\n\n\n(defn jangosmtp-api [username password]\n ", "end": 797, "score": 0.9980918765068054, "start": 789, "tag": "PASSWORD", "value": "password" } ]
data/train/clojure/3e581d9eaca2346edfc67f184959a2b050cc4b7acore.clj
harshp8l/deep-learning-lang-detection
84
;; All jangosmtp api function throws ExceptionInfo whenever there are errors in jangosmtp server. The exception info's data can be accessed by using clojure.core/ex-data ;; ;; (ns clj-jangosmtp.core (:require [clj-http.client :as client] [clojure.data.xml :refer [parse-str]] [ribol.core :refer [manage on raise]])) (declare success? jangosmtp-request convert-send-transactional-email-data) (defprotocol HttpClient (post [service url req])) (defrecord JangoSmtpApi [username password] HttpClient (post [service url req] (client/post url (update-in req [:form-params] merge {:Username username :Password password})))) (defn jangosmtp-api [username password] ;; constructor for this api's component ;; the component returned from this function IS the first argument to any jangosmtp api function (->JangoSmtpApi username password)) (defn check-bounce [j email] ;; return true if email is in bounce list (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/CheckBounce" {:form-params {:EmailAddress email}}) :succ-fn success?})) (defn delete-bounce [j email] ;; delete email from bounce list, returns true even if the email is not in bounce list (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/DeleteBounce" {:form-params {:EmailAddress email}}) :succ-fn success?})) (defn get-bounce-list-all ;; returns vector containing email in bounce list ;; use since to specify since date in string date format e.g. 2014-03-29 ;; by default returns all email in bounce list ([j] (get-bounce-list-all j "")) ([j since] (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/GetBounceListAll" {:form-params {:Since since}}) :succ-fn (fn [s] (if (success? s) (-> (clojure.string/split s #"\n") (subvec 2)) []))}))) (defn send-transactional-email [j email-data] (let [ts (convert-send-transactional-email-data email-data)] (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/SendTransactionalEmail" {:form-params ts}) :succ-fn (fn [s] (if (success? s) (-> (clojure.string/split s #"\n") (subvec 2) first) nil))}))) (defn- convert-send-transactional-email-data [email-data] ;; convert send-transactional-email-data to JangoSMTP request format (let [default {:message-html "" :message-plain "" :options ""} ed (merge default email-data) {:keys [from-email from-name to-email-address subject message-plain message-html options]} ed] {:FromEmail from-email :FromName from-name :ToEmailAddress to-email-address :Subject subject :MessagePlain message-plain :MessageHTML message-html :Options options})) (defn- success? [s] ;; success based on jangosmtp api specification (= (re-find #"^0\nSUCCESS" s) "0\nSUCCESS" )) (defn- jangosmtp-request [{:keys [req-fn succ-fn]}] ;; encapsulate try catch block where req-fn is the api request to do and succ-fn is the function applied to result of request. ;; returns ex-info with :jangosmtp-exception and :data key (try (succ-fn (-> (req-fn) :body parse-str :content first)) (catch Exception e (raise {:jangosmtp-exception true :data (-> e ex-data :object)}))))
122045
;; All jangosmtp api function throws ExceptionInfo whenever there are errors in jangosmtp server. The exception info's data can be accessed by using clojure.core/ex-data ;; ;; (ns clj-jangosmtp.core (:require [clj-http.client :as client] [clojure.data.xml :refer [parse-str]] [ribol.core :refer [manage on raise]])) (declare success? jangosmtp-request convert-send-transactional-email-data) (defprotocol HttpClient (post [service url req])) (defrecord JangoSmtpApi [username password] HttpClient (post [service url req] (client/post url (update-in req [:form-params] merge {:Username username :Password <PASSWORD>})))) (defn jangosmtp-api [username password] ;; constructor for this api's component ;; the component returned from this function IS the first argument to any jangosmtp api function (->JangoSmtpApi username password)) (defn check-bounce [j email] ;; return true if email is in bounce list (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/CheckBounce" {:form-params {:EmailAddress email}}) :succ-fn success?})) (defn delete-bounce [j email] ;; delete email from bounce list, returns true even if the email is not in bounce list (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/DeleteBounce" {:form-params {:EmailAddress email}}) :succ-fn success?})) (defn get-bounce-list-all ;; returns vector containing email in bounce list ;; use since to specify since date in string date format e.g. 2014-03-29 ;; by default returns all email in bounce list ([j] (get-bounce-list-all j "")) ([j since] (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/GetBounceListAll" {:form-params {:Since since}}) :succ-fn (fn [s] (if (success? s) (-> (clojure.string/split s #"\n") (subvec 2)) []))}))) (defn send-transactional-email [j email-data] (let [ts (convert-send-transactional-email-data email-data)] (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/SendTransactionalEmail" {:form-params ts}) :succ-fn (fn [s] (if (success? s) (-> (clojure.string/split s #"\n") (subvec 2) first) nil))}))) (defn- convert-send-transactional-email-data [email-data] ;; convert send-transactional-email-data to JangoSMTP request format (let [default {:message-html "" :message-plain "" :options ""} ed (merge default email-data) {:keys [from-email from-name to-email-address subject message-plain message-html options]} ed] {:FromEmail from-email :FromName from-name :ToEmailAddress to-email-address :Subject subject :MessagePlain message-plain :MessageHTML message-html :Options options})) (defn- success? [s] ;; success based on jangosmtp api specification (= (re-find #"^0\nSUCCESS" s) "0\nSUCCESS" )) (defn- jangosmtp-request [{:keys [req-fn succ-fn]}] ;; encapsulate try catch block where req-fn is the api request to do and succ-fn is the function applied to result of request. ;; returns ex-info with :jangosmtp-exception and :data key (try (succ-fn (-> (req-fn) :body parse-str :content first)) (catch Exception e (raise {:jangosmtp-exception true :data (-> e ex-data :object)}))))
true
;; All jangosmtp api function throws ExceptionInfo whenever there are errors in jangosmtp server. The exception info's data can be accessed by using clojure.core/ex-data ;; ;; (ns clj-jangosmtp.core (:require [clj-http.client :as client] [clojure.data.xml :refer [parse-str]] [ribol.core :refer [manage on raise]])) (declare success? jangosmtp-request convert-send-transactional-email-data) (defprotocol HttpClient (post [service url req])) (defrecord JangoSmtpApi [username password] HttpClient (post [service url req] (client/post url (update-in req [:form-params] merge {:Username username :Password PI:PASSWORD:<PASSWORD>END_PI})))) (defn jangosmtp-api [username password] ;; constructor for this api's component ;; the component returned from this function IS the first argument to any jangosmtp api function (->JangoSmtpApi username password)) (defn check-bounce [j email] ;; return true if email is in bounce list (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/CheckBounce" {:form-params {:EmailAddress email}}) :succ-fn success?})) (defn delete-bounce [j email] ;; delete email from bounce list, returns true even if the email is not in bounce list (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/DeleteBounce" {:form-params {:EmailAddress email}}) :succ-fn success?})) (defn get-bounce-list-all ;; returns vector containing email in bounce list ;; use since to specify since date in string date format e.g. 2014-03-29 ;; by default returns all email in bounce list ([j] (get-bounce-list-all j "")) ([j since] (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/GetBounceListAll" {:form-params {:Since since}}) :succ-fn (fn [s] (if (success? s) (-> (clojure.string/split s #"\n") (subvec 2)) []))}))) (defn send-transactional-email [j email-data] (let [ts (convert-send-transactional-email-data email-data)] (jangosmtp-request {:req-fn #(post j "https://api.jangomail.com/api.asmx/SendTransactionalEmail" {:form-params ts}) :succ-fn (fn [s] (if (success? s) (-> (clojure.string/split s #"\n") (subvec 2) first) nil))}))) (defn- convert-send-transactional-email-data [email-data] ;; convert send-transactional-email-data to JangoSMTP request format (let [default {:message-html "" :message-plain "" :options ""} ed (merge default email-data) {:keys [from-email from-name to-email-address subject message-plain message-html options]} ed] {:FromEmail from-email :FromName from-name :ToEmailAddress to-email-address :Subject subject :MessagePlain message-plain :MessageHTML message-html :Options options})) (defn- success? [s] ;; success based on jangosmtp api specification (= (re-find #"^0\nSUCCESS" s) "0\nSUCCESS" )) (defn- jangosmtp-request [{:keys [req-fn succ-fn]}] ;; encapsulate try catch block where req-fn is the api request to do and succ-fn is the function applied to result of request. ;; returns ex-info with :jangosmtp-exception and :data key (try (succ-fn (-> (req-fn) :body parse-str :content first)) (catch Exception e (raise {:jangosmtp-exception true :data (-> e ex-data :object)}))))
[ { "context": " update-token (e/login (s/context) \"umm-var-user1\" [update-group-id])\n ;; Grant", "end": 826, "score": 0.4959416389465332, "start": 826, "tag": "PASSWORD", "value": "" } ]
system-int-test/test/cmr/system_int_test/ingest/service_ingest_test.clj
mschmele/Common-Metadata-Repository
0
(ns cmr.system-int-test.ingest.service-ingest-test "CMR service ingest integration tests." (:require [clojure.test :refer :all] [cmr.common.util :refer [are3]] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.ingest-util :as ingest-util] [cmr.system-int-test.utils.metadata-db-util :as mdb] [cmr.system-int-test.utils.service-util :as service-util])) (use-fixtures :each (ingest-util/reset-fixture)) (deftest create-service-ingest-test ;; CMR-4335 - services failures when using Oracle as the backend (s/only-with-in-memory-database (testing "ingest a new service" (let [;; Groups update-group-id (e/get-or-create-group (s/context) "umm-var-guid1") ;; Tokens update-token (e/login (s/context) "umm-var-user1" [update-group-id]) ;; Grants update-grant-id (e/grant-group-admin (assoc (s/context) :token update-token) update-group-id :update) service-data (service-util/make-service)] (is (e/permitted? update-token update-grant-id update-group-id (ingest-util/get-ingest-update-acls update-token))) (let [{:keys [status concept-id revision-id]} (service-util/create-service update-token service-data)] (is (= 201 status)) (is (= 1 revision-id)) (is (mdb/concept-exists-in-mdb? concept-id revision-id)) (service-util/assert-service-saved service-data "umm-var-user1" concept-id revision-id)))))) (deftest create-service-ingest-permissions-test ;; CMR-4335 - services failures when using Oracle as the backend (s/only-with-in-memory-database (testing "ingest create service permissions" (let [;; Groups guest-group-id (e/get-or-create-group (s/context) "umm-var-guid1") reg-user-group-id (e/get-or-create-group (s/context) "umm-var-guid2") update-group-id (e/get-or-create-group (s/context) "umm-var-guid3") ;; Tokens guest-token (e/login (s/context) "umm-var-user1" [guest-group-id]) reg-user-token (e/login (s/context) "umm-var-user1" [reg-user-group-id]) update-token (e/login (s/context) "umm-var-user2" [update-group-id]) ;; Grants guest-grant-id (e/grant (assoc (s/context) :token guest-token) [{:permissions [:read] :user_type :guest}] :system_identity {:target nil}) reg-user-grant-id (e/grant (assoc (s/context) :token reg-user-token) [{:permissions [:read] :user_type :registered}] :system_identity {:target nil}) update-grant-id (e/grant-group-admin (assoc (s/context) :token update-token) update-group-id :update) service-data (service-util/make-service)] (testing "acl setup and grants for different users" (is (e/not-permitted? guest-token guest-grant-id guest-group-id (ingest-util/get-ingest-update-acls guest-token))) (is (e/not-permitted? reg-user-token reg-user-grant-id reg-user-group-id (ingest-util/get-ingest-update-acls reg-user-token))) (is (e/permitted? update-token update-grant-id update-group-id (ingest-util/get-ingest-update-acls update-token)))) (testing "ingest service creation permissions" (are3 [token expected] (let [response (service-util/create-service token service-data)] (is (= expected (:status response)))) "System update permission allowed" update-token 201 "Regular user denied" reg-user-token 401 "Guest user denied" guest-token 401 "No token provided" nil 401))))))
32154
(ns cmr.system-int-test.ingest.service-ingest-test "CMR service ingest integration tests." (:require [clojure.test :refer :all] [cmr.common.util :refer [are3]] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.ingest-util :as ingest-util] [cmr.system-int-test.utils.metadata-db-util :as mdb] [cmr.system-int-test.utils.service-util :as service-util])) (use-fixtures :each (ingest-util/reset-fixture)) (deftest create-service-ingest-test ;; CMR-4335 - services failures when using Oracle as the backend (s/only-with-in-memory-database (testing "ingest a new service" (let [;; Groups update-group-id (e/get-or-create-group (s/context) "umm-var-guid1") ;; Tokens update-token (e/login (s/context) "umm<PASSWORD>-var-user1" [update-group-id]) ;; Grants update-grant-id (e/grant-group-admin (assoc (s/context) :token update-token) update-group-id :update) service-data (service-util/make-service)] (is (e/permitted? update-token update-grant-id update-group-id (ingest-util/get-ingest-update-acls update-token))) (let [{:keys [status concept-id revision-id]} (service-util/create-service update-token service-data)] (is (= 201 status)) (is (= 1 revision-id)) (is (mdb/concept-exists-in-mdb? concept-id revision-id)) (service-util/assert-service-saved service-data "umm-var-user1" concept-id revision-id)))))) (deftest create-service-ingest-permissions-test ;; CMR-4335 - services failures when using Oracle as the backend (s/only-with-in-memory-database (testing "ingest create service permissions" (let [;; Groups guest-group-id (e/get-or-create-group (s/context) "umm-var-guid1") reg-user-group-id (e/get-or-create-group (s/context) "umm-var-guid2") update-group-id (e/get-or-create-group (s/context) "umm-var-guid3") ;; Tokens guest-token (e/login (s/context) "umm-var-user1" [guest-group-id]) reg-user-token (e/login (s/context) "umm-var-user1" [reg-user-group-id]) update-token (e/login (s/context) "umm-var-user2" [update-group-id]) ;; Grants guest-grant-id (e/grant (assoc (s/context) :token guest-token) [{:permissions [:read] :user_type :guest}] :system_identity {:target nil}) reg-user-grant-id (e/grant (assoc (s/context) :token reg-user-token) [{:permissions [:read] :user_type :registered}] :system_identity {:target nil}) update-grant-id (e/grant-group-admin (assoc (s/context) :token update-token) update-group-id :update) service-data (service-util/make-service)] (testing "acl setup and grants for different users" (is (e/not-permitted? guest-token guest-grant-id guest-group-id (ingest-util/get-ingest-update-acls guest-token))) (is (e/not-permitted? reg-user-token reg-user-grant-id reg-user-group-id (ingest-util/get-ingest-update-acls reg-user-token))) (is (e/permitted? update-token update-grant-id update-group-id (ingest-util/get-ingest-update-acls update-token)))) (testing "ingest service creation permissions" (are3 [token expected] (let [response (service-util/create-service token service-data)] (is (= expected (:status response)))) "System update permission allowed" update-token 201 "Regular user denied" reg-user-token 401 "Guest user denied" guest-token 401 "No token provided" nil 401))))))
true
(ns cmr.system-int-test.ingest.service-ingest-test "CMR service ingest integration tests." (:require [clojure.test :refer :all] [cmr.common.util :refer [are3]] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.ingest-util :as ingest-util] [cmr.system-int-test.utils.metadata-db-util :as mdb] [cmr.system-int-test.utils.service-util :as service-util])) (use-fixtures :each (ingest-util/reset-fixture)) (deftest create-service-ingest-test ;; CMR-4335 - services failures when using Oracle as the backend (s/only-with-in-memory-database (testing "ingest a new service" (let [;; Groups update-group-id (e/get-or-create-group (s/context) "umm-var-guid1") ;; Tokens update-token (e/login (s/context) "ummPI:PASSWORD:<PASSWORD>END_PI-var-user1" [update-group-id]) ;; Grants update-grant-id (e/grant-group-admin (assoc (s/context) :token update-token) update-group-id :update) service-data (service-util/make-service)] (is (e/permitted? update-token update-grant-id update-group-id (ingest-util/get-ingest-update-acls update-token))) (let [{:keys [status concept-id revision-id]} (service-util/create-service update-token service-data)] (is (= 201 status)) (is (= 1 revision-id)) (is (mdb/concept-exists-in-mdb? concept-id revision-id)) (service-util/assert-service-saved service-data "umm-var-user1" concept-id revision-id)))))) (deftest create-service-ingest-permissions-test ;; CMR-4335 - services failures when using Oracle as the backend (s/only-with-in-memory-database (testing "ingest create service permissions" (let [;; Groups guest-group-id (e/get-or-create-group (s/context) "umm-var-guid1") reg-user-group-id (e/get-or-create-group (s/context) "umm-var-guid2") update-group-id (e/get-or-create-group (s/context) "umm-var-guid3") ;; Tokens guest-token (e/login (s/context) "umm-var-user1" [guest-group-id]) reg-user-token (e/login (s/context) "umm-var-user1" [reg-user-group-id]) update-token (e/login (s/context) "umm-var-user2" [update-group-id]) ;; Grants guest-grant-id (e/grant (assoc (s/context) :token guest-token) [{:permissions [:read] :user_type :guest}] :system_identity {:target nil}) reg-user-grant-id (e/grant (assoc (s/context) :token reg-user-token) [{:permissions [:read] :user_type :registered}] :system_identity {:target nil}) update-grant-id (e/grant-group-admin (assoc (s/context) :token update-token) update-group-id :update) service-data (service-util/make-service)] (testing "acl setup and grants for different users" (is (e/not-permitted? guest-token guest-grant-id guest-group-id (ingest-util/get-ingest-update-acls guest-token))) (is (e/not-permitted? reg-user-token reg-user-grant-id reg-user-group-id (ingest-util/get-ingest-update-acls reg-user-token))) (is (e/permitted? update-token update-grant-id update-group-id (ingest-util/get-ingest-update-acls update-token)))) (testing "ingest service creation permissions" (are3 [token expected] (let [response (service-util/create-service token service-data)] (is (= expected (:status response)))) "System update permission allowed" update-token 201 "Regular user denied" reg-user-token 401 "Guest user denied" guest-token 401 "No token provided" nil 401))))))
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis", "end": 33, "score": 0.9998537302017212, "start": 19, "tag": "NAME", "value": "Nicola Mometto" }, { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution ter", "end": 46, "score": 0.9998423457145691, "start": 35, "tag": "NAME", "value": "Rich Hickey" } ]
server/target/clojure/tools/analyzer/ast.clj
OctavioBR/healthcheck
15
;; Copyright (c) Nicola Mometto, Rich Hickey & contributors. ;; 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 clojure.tools.analyzer.ast "Utilities for AST walking/updating" (:refer-clojure :exclude [unreduced]) (:require [clojure.tools.analyzer.utils :refer [into! rseqv mapv']])) (defn cycling "Combine the given passes in a single pass that will be applieed repeatedly to the AST until applying it another time will have no effect" [& fns*] (let [fns (cycle fns*)] (fn [ast] (loop [[f & fns] fns ast ast res (zipmap fns* (repeat nil))] (let [ast* (f ast)] (if (= ast* (res f)) ast (recur fns ast* (assoc res f ast*)))))))) (defn children* "Return a vector of vectors of the children node key and the children expression of the AST node, if it has any. The returned vector returns the childrens in the order as they appear in the :children field of the AST, and the children expressions may be either a node or a vector of nodes." [{:keys [children] :as ast}] (when children (mapv #(find ast %) children))) (defn children "Return a vector of the children expression of the AST node, if it has any. The children expressions are kept in order and flattened so that the returning vector contains only nodes and not vectors of nodes." [ast] (persistent! (reduce (fn [acc [_ c]] ((if (vector? c) into! conj!) acc c)) (transient []) (children* ast)))) ;; return transient or reduced holding transient (defn ^:private -update-children [ast f r?] (let [fix (if r? rseqv identity)] (reduce (fn [ast [k v]] (let [multi (vector? v) val (if multi (mapv' f (fix v)) (f v))] (if (reduced? val) (reduced (reduced (assoc! ast k (if multi (fix @val) @val)))) (assoc! ast k (if multi (fix val) val))))) (transient ast) (fix (children* ast))))) (defn update-children-reduced "Like update-children but returns a reduced holding the AST if f short-circuited." ([ast f] (update-children-reduced ast f false)) ([ast f reversed?] (if (and (not (reduced? ast)) (:children ast)) (let [ret (-update-children ast f reversed?)] (if (reduced? ret) (reduced (persistent! @ret)) (persistent! ret))) ast))) (defn ^:private unreduced [x] (if (reduced? x) @x x)) (defn update-children "Applies `f` to each AST children node, replacing it with the returned value. If reversed? is not-nil, `pre` and `post` will be applied starting from the last children of the AST node to the first one. Short-circuits on reduced." ([ast f] (update-children ast f false)) ([ast f reversed?] (unreduced (update-children-reduced ast f reversed?)))) (defn walk "Walk the ast applying `pre` when entering the nodes, and `post` when exiting. Both functions must return a valid node since the returned value will replace the node in the AST which was given as input to the function. If reversed? is not-nil, `pre` and `post` will be applied starting from the last children of the AST node to the first one. Short-circuits on reduced." ([ast pre post] (walk ast pre post false)) ([ast pre post reversed?] (unreduced ((fn walk [ast pre post reversed?] (let [walk #(walk % pre post reversed?)] (if (reduced? ast) ast (let [ret (update-children-reduced (pre ast) walk reversed?)] (if (reduced? ret) ret (post ret)))))) ast pre post reversed?)))) (defn prewalk "Shorthand for (walk ast f identity)" [ast f] (walk ast f identity)) (defn postwalk "Shorthand for (walk ast identity f reversed?)" ([ast f] (postwalk ast f false)) ([ast f reversed?] (walk ast identity f reversed?))) (defn nodes "Returns a lazy-seq of all the nodes in the given AST, in depth-first pre-order." [ast] (lazy-seq (cons ast (mapcat nodes (children ast))))) (defn ast->eav "Returns an EAV representation of the current AST that can be used by Datomic's Datalog." [ast] (let [children (set (:children ast))] (mapcat (fn [[k v]] (if (children k) (if (map? v) (into [[ast k v]] (ast->eav v)) (mapcat (fn [v] (into [[ast k v]] (ast->eav v))) v)) [[ast k v]])) ast)))
114258
;; Copyright (c) <NAME>, <NAME> & contributors. ;; 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 clojure.tools.analyzer.ast "Utilities for AST walking/updating" (:refer-clojure :exclude [unreduced]) (:require [clojure.tools.analyzer.utils :refer [into! rseqv mapv']])) (defn cycling "Combine the given passes in a single pass that will be applieed repeatedly to the AST until applying it another time will have no effect" [& fns*] (let [fns (cycle fns*)] (fn [ast] (loop [[f & fns] fns ast ast res (zipmap fns* (repeat nil))] (let [ast* (f ast)] (if (= ast* (res f)) ast (recur fns ast* (assoc res f ast*)))))))) (defn children* "Return a vector of vectors of the children node key and the children expression of the AST node, if it has any. The returned vector returns the childrens in the order as they appear in the :children field of the AST, and the children expressions may be either a node or a vector of nodes." [{:keys [children] :as ast}] (when children (mapv #(find ast %) children))) (defn children "Return a vector of the children expression of the AST node, if it has any. The children expressions are kept in order and flattened so that the returning vector contains only nodes and not vectors of nodes." [ast] (persistent! (reduce (fn [acc [_ c]] ((if (vector? c) into! conj!) acc c)) (transient []) (children* ast)))) ;; return transient or reduced holding transient (defn ^:private -update-children [ast f r?] (let [fix (if r? rseqv identity)] (reduce (fn [ast [k v]] (let [multi (vector? v) val (if multi (mapv' f (fix v)) (f v))] (if (reduced? val) (reduced (reduced (assoc! ast k (if multi (fix @val) @val)))) (assoc! ast k (if multi (fix val) val))))) (transient ast) (fix (children* ast))))) (defn update-children-reduced "Like update-children but returns a reduced holding the AST if f short-circuited." ([ast f] (update-children-reduced ast f false)) ([ast f reversed?] (if (and (not (reduced? ast)) (:children ast)) (let [ret (-update-children ast f reversed?)] (if (reduced? ret) (reduced (persistent! @ret)) (persistent! ret))) ast))) (defn ^:private unreduced [x] (if (reduced? x) @x x)) (defn update-children "Applies `f` to each AST children node, replacing it with the returned value. If reversed? is not-nil, `pre` and `post` will be applied starting from the last children of the AST node to the first one. Short-circuits on reduced." ([ast f] (update-children ast f false)) ([ast f reversed?] (unreduced (update-children-reduced ast f reversed?)))) (defn walk "Walk the ast applying `pre` when entering the nodes, and `post` when exiting. Both functions must return a valid node since the returned value will replace the node in the AST which was given as input to the function. If reversed? is not-nil, `pre` and `post` will be applied starting from the last children of the AST node to the first one. Short-circuits on reduced." ([ast pre post] (walk ast pre post false)) ([ast pre post reversed?] (unreduced ((fn walk [ast pre post reversed?] (let [walk #(walk % pre post reversed?)] (if (reduced? ast) ast (let [ret (update-children-reduced (pre ast) walk reversed?)] (if (reduced? ret) ret (post ret)))))) ast pre post reversed?)))) (defn prewalk "Shorthand for (walk ast f identity)" [ast f] (walk ast f identity)) (defn postwalk "Shorthand for (walk ast identity f reversed?)" ([ast f] (postwalk ast f false)) ([ast f reversed?] (walk ast identity f reversed?))) (defn nodes "Returns a lazy-seq of all the nodes in the given AST, in depth-first pre-order." [ast] (lazy-seq (cons ast (mapcat nodes (children ast))))) (defn ast->eav "Returns an EAV representation of the current AST that can be used by Datomic's Datalog." [ast] (let [children (set (:children ast))] (mapcat (fn [[k v]] (if (children k) (if (map? v) (into [[ast k v]] (ast->eav v)) (mapcat (fn [v] (into [[ast k v]] (ast->eav v))) v)) [[ast k v]])) ast)))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors. ;; 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 clojure.tools.analyzer.ast "Utilities for AST walking/updating" (:refer-clojure :exclude [unreduced]) (:require [clojure.tools.analyzer.utils :refer [into! rseqv mapv']])) (defn cycling "Combine the given passes in a single pass that will be applieed repeatedly to the AST until applying it another time will have no effect" [& fns*] (let [fns (cycle fns*)] (fn [ast] (loop [[f & fns] fns ast ast res (zipmap fns* (repeat nil))] (let [ast* (f ast)] (if (= ast* (res f)) ast (recur fns ast* (assoc res f ast*)))))))) (defn children* "Return a vector of vectors of the children node key and the children expression of the AST node, if it has any. The returned vector returns the childrens in the order as they appear in the :children field of the AST, and the children expressions may be either a node or a vector of nodes." [{:keys [children] :as ast}] (when children (mapv #(find ast %) children))) (defn children "Return a vector of the children expression of the AST node, if it has any. The children expressions are kept in order and flattened so that the returning vector contains only nodes and not vectors of nodes." [ast] (persistent! (reduce (fn [acc [_ c]] ((if (vector? c) into! conj!) acc c)) (transient []) (children* ast)))) ;; return transient or reduced holding transient (defn ^:private -update-children [ast f r?] (let [fix (if r? rseqv identity)] (reduce (fn [ast [k v]] (let [multi (vector? v) val (if multi (mapv' f (fix v)) (f v))] (if (reduced? val) (reduced (reduced (assoc! ast k (if multi (fix @val) @val)))) (assoc! ast k (if multi (fix val) val))))) (transient ast) (fix (children* ast))))) (defn update-children-reduced "Like update-children but returns a reduced holding the AST if f short-circuited." ([ast f] (update-children-reduced ast f false)) ([ast f reversed?] (if (and (not (reduced? ast)) (:children ast)) (let [ret (-update-children ast f reversed?)] (if (reduced? ret) (reduced (persistent! @ret)) (persistent! ret))) ast))) (defn ^:private unreduced [x] (if (reduced? x) @x x)) (defn update-children "Applies `f` to each AST children node, replacing it with the returned value. If reversed? is not-nil, `pre` and `post` will be applied starting from the last children of the AST node to the first one. Short-circuits on reduced." ([ast f] (update-children ast f false)) ([ast f reversed?] (unreduced (update-children-reduced ast f reversed?)))) (defn walk "Walk the ast applying `pre` when entering the nodes, and `post` when exiting. Both functions must return a valid node since the returned value will replace the node in the AST which was given as input to the function. If reversed? is not-nil, `pre` and `post` will be applied starting from the last children of the AST node to the first one. Short-circuits on reduced." ([ast pre post] (walk ast pre post false)) ([ast pre post reversed?] (unreduced ((fn walk [ast pre post reversed?] (let [walk #(walk % pre post reversed?)] (if (reduced? ast) ast (let [ret (update-children-reduced (pre ast) walk reversed?)] (if (reduced? ret) ret (post ret)))))) ast pre post reversed?)))) (defn prewalk "Shorthand for (walk ast f identity)" [ast f] (walk ast f identity)) (defn postwalk "Shorthand for (walk ast identity f reversed?)" ([ast f] (postwalk ast f false)) ([ast f reversed?] (walk ast identity f reversed?))) (defn nodes "Returns a lazy-seq of all the nodes in the given AST, in depth-first pre-order." [ast] (lazy-seq (cons ast (mapcat nodes (children ast))))) (defn ast->eav "Returns an EAV representation of the current AST that can be used by Datomic's Datalog." [ast] (let [children (set (:children ast))] (mapcat (fn [[k v]] (if (children k) (if (map? v) (into [[ast k v]] (ast->eav v)) (mapcat (fn [v] (into [[ast k v]] (ast->eav v))) v)) [[ast k v]])) ast)))
[ { "context": "he rules.\n (insert (Customer. \"Tim\" true)\n (Order. 250)) ", "end": 760, "score": 0.9987039566040039, "start": 757, "tag": "NAME", "value": "Tim" } ]
src/main/clojure/clara/examples/java/shopping.clj
defaultUser4/clara-examples
50
(ns clara.examples.java.shopping (:require [clara.rules.accumulators :as acc] [clara.rules :refer :all]) (:import [clara.examples.java Customer Order Promotion])) (defrule awesome-promotion-for-vips "Creates an awesome promotion for VIPs that spend more than $200" [Customer (= true VIP)] [Order (> total 200)] => (insert! (Promotion. "Awesome promotion for our favorite VIP!"))) (defquery get-promotions "Query the promotions." [] [?promotion <- Promotion]) (defn run-examples "Function to run the above example. Also see ExampleMain.java to see this used from Java. " [] (let [session (-> (mk-session 'clara.examples.java.shopping :cache false) ; Load the rules. (insert (Customer. "Tim" true) (Order. 250)) ; Insert some facts. (fire-rules))] (doseq [{promotion :?promotion} (query session get-promotions)] (println "Promotion:" (.getDescription promotion)))) nil)
61583
(ns clara.examples.java.shopping (:require [clara.rules.accumulators :as acc] [clara.rules :refer :all]) (:import [clara.examples.java Customer Order Promotion])) (defrule awesome-promotion-for-vips "Creates an awesome promotion for VIPs that spend more than $200" [Customer (= true VIP)] [Order (> total 200)] => (insert! (Promotion. "Awesome promotion for our favorite VIP!"))) (defquery get-promotions "Query the promotions." [] [?promotion <- Promotion]) (defn run-examples "Function to run the above example. Also see ExampleMain.java to see this used from Java. " [] (let [session (-> (mk-session 'clara.examples.java.shopping :cache false) ; Load the rules. (insert (Customer. "<NAME>" true) (Order. 250)) ; Insert some facts. (fire-rules))] (doseq [{promotion :?promotion} (query session get-promotions)] (println "Promotion:" (.getDescription promotion)))) nil)
true
(ns clara.examples.java.shopping (:require [clara.rules.accumulators :as acc] [clara.rules :refer :all]) (:import [clara.examples.java Customer Order Promotion])) (defrule awesome-promotion-for-vips "Creates an awesome promotion for VIPs that spend more than $200" [Customer (= true VIP)] [Order (> total 200)] => (insert! (Promotion. "Awesome promotion for our favorite VIP!"))) (defquery get-promotions "Query the promotions." [] [?promotion <- Promotion]) (defn run-examples "Function to run the above example. Also see ExampleMain.java to see this used from Java. " [] (let [session (-> (mk-session 'clara.examples.java.shopping :cache false) ; Load the rules. (insert (Customer. "PI:NAME:<NAME>END_PI" true) (Order. 250)) ; Insert some facts. (fire-rules))] (doseq [{promotion :?promotion} (query session get-promotions)] (println "Promotion:" (.getDescription promotion)))) nil)
[ { "context": "s\n :basic-auth {:user \"61a2666419b8361ae639d5f9\"\n :pass \"", "end": 5985, "score": 0.9075126647949219, "start": 5961, "tag": "KEY", "value": "61a2666419b8361ae639d5f9" }, { "context": "\"\n :pass \"5t9O24UTTtT656cYfmNXXBr06fNIxSlVbZ0ajO3o\"}}))) \n\n token-r\n\n (def endpoint {:production-u", "end": 6075, "score": 0.9950085282325745, "start": 6035, "tag": "PASSWORD", "value": "5t9O24UTTtT656cYfmNXXBr06fNIxSlVbZ0ajO3o" }, { "context": "666419b8361ae639d5f9\"\n :password \"5t9O24UTTtT656cYfmNXXBr06fNIxSlVbZ0ajO3o\"} )\n\n (def httpc (http/build-http-client {:conne", "end": 6386, "score": 0.9978376030921936, "start": 6346, "tag": "PASSWORD", "value": "5t9O24UTTtT656cYfmNXXBr06fNIxSlVbZ0ajO3o" } ]
components/production-api/src/de/virtual_earth/superdesk_graphql/production_api/core.clj
virtual-earth-de/superdesk-graphql
0
;; Copyright [2021] [virtual earth Gesellschaft für Wissens re/prä sentation mbH] ;; 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 de.virtual-earth.superdesk-graphql.production-api.core (:require [clojure.data.json :as json] [clojure.pprint :refer [pprint]] [clojure.string :as str] [clojure.walk :as walk] [hato.client :as http]) (:import (java.util Base64) (java.time Instant) (java.net URLEncoder URLDecoder))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; functions to add a path to an item ;; and to get the unique_name back from the path ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn document-path "add document path for URL to item" [{:keys [unique_name slugline] :or {unique_name "#XXXXXXXXX" slugline "missing slugline!"} :as item}] (let [id (subs unique_name 1) slug (URLEncoder/encode slugline "UTF-8")] (str id "-" slug))) (defn item-with-path "add document path to item" [item] (if (= (type item) clojure.lang.PersistentHashMap) (do (assoc item :path (document-path item))) item)) (defn struct-with-item-paths "add path to every item in data structure" [ds] (walk/postwalk item-with-path ds)) (defn id-from-path "creates the id/unique_name (numbers until dash w. prepended '#') from document path" [path] (let [id (first (str/split path #"-" 2))] (str "#" id))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn epochTimeInc "Add arg seconds to epoch time and return result" [seconds] (+ (.getEpochSecond (Instant/now)) seconds)) (defn refresh-inc "calculate preferred expiration time, 5 min before actual expiration, which should be in seconds. Should this be configurable?" [expires-in] ;; bit overkill here :-D (let [five-min (* 5 60)] (- expires-in five-min))) (defn refresh-now? [refresh-at] "Return true if arg (epoch time) is older than 'now' or if it's nil" (if refresh-at (< refresh-at (.getEpochSecond (Instant/now))) true)) (defn get-token "Get the token response from endpoint" [client endpoint] (let [tokenresponse (http/post (:token-url endpoint) {:form-params {:grant_type "client_credentials"} :as :json :coerce :always :http-client client :basic-auth {:user (:client-id endpoint) :pass (:password endpoint)}})] ;; FIXME should *really* add some error processing here ;) (:body tokenresponse))) (defn refresh-token! "Create or update token and store it in conn" [conn] (let [token (get-token (:httpc @conn) (:endpoint @conn))] (swap! conn (fn [conn token] (-> conn (assoc :token token) (assoc :refresh-at (epochTimeInc (refresh-inc (:expires_in token)))))) token ))) (defn ensure-authenticated-conn! "Update or create token if necessary, return connection value" [conn] "Refresh conn if it's stale, return value of conn" (if (refresh-now? (:refresh-at @conn)) (refresh-token! conn)) @conn) (defn papi-get! "Send a get with current bearer token" [conn args] (ensure-authenticated-conn! conn) (let [{:keys [endpoint token]} @conn] ;;this connection can fail for various reasons even if our token is fresh. FIXME: add error handling (json/read-str (:body (http/get (str (:production-url endpoint) args) {:oauth-token (:access_token token)})) :key-fn keyword))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn init "Get oauth token from Superdesk, store it in an atom, create http-client and put it in the same atom, as well as all the endpoint info (so we can regenerate the token later on" [endpoint] (let [httpc (http/build-http-client {:connect-timeout 10000}) token (get-token httpc endpoint) conn (atom {:endpoint endpoint :httpc httpc} )] (ensure-authenticated-conn! conn) ;; I need to return the wohl conn/atom, ;; so functions using this can hand us back the (stateful) connection atom for updates conn)) (defn users-list [conn] (papi-get! conn "/users")) (defn user-by-id [conn id] (papi-get! conn (str "/users/" id))) (defn item-by-guid [conn guid] (struct-with-item-paths (papi-get! conn (str "/items/" guid)))) (defn item-by-path [conn path] (let [unique_name (id-from-path path) ;; unque_name starts with a '#', so we have to urlencode it for use as URL query string query {:query {:term {:unique_name (URLEncoder/encode unique_name "UTF-8")}}}] (struct-with-item-paths (first (:_items (papi-get! conn (str "/items?source=" (json/write-str query)))))))) (defn items-by-query [conn query] "Send query for items, args are conn and query as edn which will be turned into json" (:_items (struct-with-item-paths (papi-get! conn (str "/items?source=" (json/write-str query)))))) (comment (def token-r (:body (http/post "https://superdesk.literatur.review/api/auth_server/token" {:form-params {:grant_type "client_credentials"} :as :json :coerce :always :basic-auth {:user "61a2666419b8361ae639d5f9" :pass "5t9O24UTTtT656cYfmNXXBr06fNIxSlVbZ0ajO3o"}}))) token-r (def endpoint {:production-url "https://superdesk.literatur.review/prodapi/v1" :token-url "https://superdesk.literatur.review/api/auth_server/token" :client-id "61a2666419b8361ae639d5f9" :password "5t9O24UTTtT656cYfmNXXBr06fNIxSlVbZ0ajO3o"} ) (def httpc (http/build-http-client {:connect-timeout 10000})) httpc (def wrapped-token (get-token httpc endpoint)) (def conn (atom {:endpoint endpoint :httpc httpc})) conn (ensure-authenticated-conn! conn) conn (def realconn (init endpoint)) realconn (def schachnovelle (item-by-guid conn "90bf03f7-75cf-4404-b3b4-fc4b01c7b272")) schachnovelle (:authors schachnovelle) (item-authors conn (:authors schachnovelle)) (def einbild (item-by-guid conn "dcd55151-7f97-42e9-a066-07f46cc21694")) (user-by-id conn (:parent (first (:authors schachnovelle)))) (def ffox_query (json/read-str "{\"query\":{\"filtered\":{\"filter\":{\"and\":[{\"not\":{\"term\":{\"state\":\"spiked\"}}},{\"term\":{\"family_id\":\"90bf03f7-75cf-4404-b3b4-fc4b01c7b272\"}},{\"not\":{\"term\":{\"unique_id\":35}}}]}}},\"size\":200,\"from\":0,\"sort\":{\"versioncreated\":\"desc\"}}" :key-fn keyword)) (def testquery { :query { :filtered { :filter { :and [{ :not { :term { :state "spiked" } } } { :term { :family_id "90bf03f7-75cf-4404-b3b4-fc4b01c7b272" } } { :not { :term { :unique_id 35 } } } ] } } }, :size 200, :from 0, :sort { :versioncreated "desc" } } ) (def testquery2 { :query { :filtered { :filter { :and [{ :not { :term { :state "spiked" } } } { :not { :term { :unique_id 35 } } } ] } } }, :size 200, :from 0, :sort { :versioncreated "desc" } } ) (def ffox-items (items-by-query conn ffox_query)) (def composite-items (items-by-query conn (json/write-str {:query {:filtered {:filter {:not {:term {:state :spiked} }}}}}))) (def composite-items (items-by-query conn testquery2)) (def items-not-spiked-query {:query {:filtered {:filter {:not {:term {:state :spiked}}}}}} ) (def items-not-spiked-string-query "{\"query\":{\"filtered\":{\"filter\":{\"not\":{\"term\":{\"state\":\"spiked\"}}}}}}") (= (json/write-str items-not-spiked-query) items-not-spiked-string-query) (def items-not-spiked (items-by-query conn items-not-spiked-string-query)) (def testq {:query {:term {:type {:value "picture"}}} }) (def testitems (items-by-query conn (json/write-str testq))) composite-items (:_items (json/read-str (:body composite-items) :key-fn keyword)) (json/read-str (:body ffox-items)) (json/read-str (:body (users-list conn)) :key-fn keyword) (swap! conn (fn [myconn] (-> myconn (assoc :refresh-at (- (.getEpochSecond (Instant/now)) (* 5 60))) ))) (def query-r (:body (http/post "https://superdesk.literatur.review/prodapi/v1/items?source=")) ) (defn items-query [{:keys [endpoint token]} query] (http/get (str "https://superdesk.literatur.review/prodapi/v1/items?source=" (URLEncoder/encode (json/write-str {:query {:filtered {:filter {:not {:term {:state :spiked}}}}}}) "UTF-8")) {:oauth-token (:access_token token) })) (items-query @conn nil) )
58120
;; Copyright [2021] [virtual earth Gesellschaft für Wissens re/prä sentation mbH] ;; 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 de.virtual-earth.superdesk-graphql.production-api.core (:require [clojure.data.json :as json] [clojure.pprint :refer [pprint]] [clojure.string :as str] [clojure.walk :as walk] [hato.client :as http]) (:import (java.util Base64) (java.time Instant) (java.net URLEncoder URLDecoder))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; functions to add a path to an item ;; and to get the unique_name back from the path ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn document-path "add document path for URL to item" [{:keys [unique_name slugline] :or {unique_name "#XXXXXXXXX" slugline "missing slugline!"} :as item}] (let [id (subs unique_name 1) slug (URLEncoder/encode slugline "UTF-8")] (str id "-" slug))) (defn item-with-path "add document path to item" [item] (if (= (type item) clojure.lang.PersistentHashMap) (do (assoc item :path (document-path item))) item)) (defn struct-with-item-paths "add path to every item in data structure" [ds] (walk/postwalk item-with-path ds)) (defn id-from-path "creates the id/unique_name (numbers until dash w. prepended '#') from document path" [path] (let [id (first (str/split path #"-" 2))] (str "#" id))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn epochTimeInc "Add arg seconds to epoch time and return result" [seconds] (+ (.getEpochSecond (Instant/now)) seconds)) (defn refresh-inc "calculate preferred expiration time, 5 min before actual expiration, which should be in seconds. Should this be configurable?" [expires-in] ;; bit overkill here :-D (let [five-min (* 5 60)] (- expires-in five-min))) (defn refresh-now? [refresh-at] "Return true if arg (epoch time) is older than 'now' or if it's nil" (if refresh-at (< refresh-at (.getEpochSecond (Instant/now))) true)) (defn get-token "Get the token response from endpoint" [client endpoint] (let [tokenresponse (http/post (:token-url endpoint) {:form-params {:grant_type "client_credentials"} :as :json :coerce :always :http-client client :basic-auth {:user (:client-id endpoint) :pass (:password endpoint)}})] ;; FIXME should *really* add some error processing here ;) (:body tokenresponse))) (defn refresh-token! "Create or update token and store it in conn" [conn] (let [token (get-token (:httpc @conn) (:endpoint @conn))] (swap! conn (fn [conn token] (-> conn (assoc :token token) (assoc :refresh-at (epochTimeInc (refresh-inc (:expires_in token)))))) token ))) (defn ensure-authenticated-conn! "Update or create token if necessary, return connection value" [conn] "Refresh conn if it's stale, return value of conn" (if (refresh-now? (:refresh-at @conn)) (refresh-token! conn)) @conn) (defn papi-get! "Send a get with current bearer token" [conn args] (ensure-authenticated-conn! conn) (let [{:keys [endpoint token]} @conn] ;;this connection can fail for various reasons even if our token is fresh. FIXME: add error handling (json/read-str (:body (http/get (str (:production-url endpoint) args) {:oauth-token (:access_token token)})) :key-fn keyword))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn init "Get oauth token from Superdesk, store it in an atom, create http-client and put it in the same atom, as well as all the endpoint info (so we can regenerate the token later on" [endpoint] (let [httpc (http/build-http-client {:connect-timeout 10000}) token (get-token httpc endpoint) conn (atom {:endpoint endpoint :httpc httpc} )] (ensure-authenticated-conn! conn) ;; I need to return the wohl conn/atom, ;; so functions using this can hand us back the (stateful) connection atom for updates conn)) (defn users-list [conn] (papi-get! conn "/users")) (defn user-by-id [conn id] (papi-get! conn (str "/users/" id))) (defn item-by-guid [conn guid] (struct-with-item-paths (papi-get! conn (str "/items/" guid)))) (defn item-by-path [conn path] (let [unique_name (id-from-path path) ;; unque_name starts with a '#', so we have to urlencode it for use as URL query string query {:query {:term {:unique_name (URLEncoder/encode unique_name "UTF-8")}}}] (struct-with-item-paths (first (:_items (papi-get! conn (str "/items?source=" (json/write-str query)))))))) (defn items-by-query [conn query] "Send query for items, args are conn and query as edn which will be turned into json" (:_items (struct-with-item-paths (papi-get! conn (str "/items?source=" (json/write-str query)))))) (comment (def token-r (:body (http/post "https://superdesk.literatur.review/api/auth_server/token" {:form-params {:grant_type "client_credentials"} :as :json :coerce :always :basic-auth {:user "<KEY>" :pass "<PASSWORD>"}}))) token-r (def endpoint {:production-url "https://superdesk.literatur.review/prodapi/v1" :token-url "https://superdesk.literatur.review/api/auth_server/token" :client-id "61a2666419b8361ae639d5f9" :password "<PASSWORD>"} ) (def httpc (http/build-http-client {:connect-timeout 10000})) httpc (def wrapped-token (get-token httpc endpoint)) (def conn (atom {:endpoint endpoint :httpc httpc})) conn (ensure-authenticated-conn! conn) conn (def realconn (init endpoint)) realconn (def schachnovelle (item-by-guid conn "90bf03f7-75cf-4404-b3b4-fc4b01c7b272")) schachnovelle (:authors schachnovelle) (item-authors conn (:authors schachnovelle)) (def einbild (item-by-guid conn "dcd55151-7f97-42e9-a066-07f46cc21694")) (user-by-id conn (:parent (first (:authors schachnovelle)))) (def ffox_query (json/read-str "{\"query\":{\"filtered\":{\"filter\":{\"and\":[{\"not\":{\"term\":{\"state\":\"spiked\"}}},{\"term\":{\"family_id\":\"90bf03f7-75cf-4404-b3b4-fc4b01c7b272\"}},{\"not\":{\"term\":{\"unique_id\":35}}}]}}},\"size\":200,\"from\":0,\"sort\":{\"versioncreated\":\"desc\"}}" :key-fn keyword)) (def testquery { :query { :filtered { :filter { :and [{ :not { :term { :state "spiked" } } } { :term { :family_id "90bf03f7-75cf-4404-b3b4-fc4b01c7b272" } } { :not { :term { :unique_id 35 } } } ] } } }, :size 200, :from 0, :sort { :versioncreated "desc" } } ) (def testquery2 { :query { :filtered { :filter { :and [{ :not { :term { :state "spiked" } } } { :not { :term { :unique_id 35 } } } ] } } }, :size 200, :from 0, :sort { :versioncreated "desc" } } ) (def ffox-items (items-by-query conn ffox_query)) (def composite-items (items-by-query conn (json/write-str {:query {:filtered {:filter {:not {:term {:state :spiked} }}}}}))) (def composite-items (items-by-query conn testquery2)) (def items-not-spiked-query {:query {:filtered {:filter {:not {:term {:state :spiked}}}}}} ) (def items-not-spiked-string-query "{\"query\":{\"filtered\":{\"filter\":{\"not\":{\"term\":{\"state\":\"spiked\"}}}}}}") (= (json/write-str items-not-spiked-query) items-not-spiked-string-query) (def items-not-spiked (items-by-query conn items-not-spiked-string-query)) (def testq {:query {:term {:type {:value "picture"}}} }) (def testitems (items-by-query conn (json/write-str testq))) composite-items (:_items (json/read-str (:body composite-items) :key-fn keyword)) (json/read-str (:body ffox-items)) (json/read-str (:body (users-list conn)) :key-fn keyword) (swap! conn (fn [myconn] (-> myconn (assoc :refresh-at (- (.getEpochSecond (Instant/now)) (* 5 60))) ))) (def query-r (:body (http/post "https://superdesk.literatur.review/prodapi/v1/items?source=")) ) (defn items-query [{:keys [endpoint token]} query] (http/get (str "https://superdesk.literatur.review/prodapi/v1/items?source=" (URLEncoder/encode (json/write-str {:query {:filtered {:filter {:not {:term {:state :spiked}}}}}}) "UTF-8")) {:oauth-token (:access_token token) })) (items-query @conn nil) )
true
;; Copyright [2021] [virtual earth Gesellschaft für Wissens re/prä sentation mbH] ;; 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 de.virtual-earth.superdesk-graphql.production-api.core (:require [clojure.data.json :as json] [clojure.pprint :refer [pprint]] [clojure.string :as str] [clojure.walk :as walk] [hato.client :as http]) (:import (java.util Base64) (java.time Instant) (java.net URLEncoder URLDecoder))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; functions to add a path to an item ;; and to get the unique_name back from the path ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn document-path "add document path for URL to item" [{:keys [unique_name slugline] :or {unique_name "#XXXXXXXXX" slugline "missing slugline!"} :as item}] (let [id (subs unique_name 1) slug (URLEncoder/encode slugline "UTF-8")] (str id "-" slug))) (defn item-with-path "add document path to item" [item] (if (= (type item) clojure.lang.PersistentHashMap) (do (assoc item :path (document-path item))) item)) (defn struct-with-item-paths "add path to every item in data structure" [ds] (walk/postwalk item-with-path ds)) (defn id-from-path "creates the id/unique_name (numbers until dash w. prepended '#') from document path" [path] (let [id (first (str/split path #"-" 2))] (str "#" id))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn epochTimeInc "Add arg seconds to epoch time and return result" [seconds] (+ (.getEpochSecond (Instant/now)) seconds)) (defn refresh-inc "calculate preferred expiration time, 5 min before actual expiration, which should be in seconds. Should this be configurable?" [expires-in] ;; bit overkill here :-D (let [five-min (* 5 60)] (- expires-in five-min))) (defn refresh-now? [refresh-at] "Return true if arg (epoch time) is older than 'now' or if it's nil" (if refresh-at (< refresh-at (.getEpochSecond (Instant/now))) true)) (defn get-token "Get the token response from endpoint" [client endpoint] (let [tokenresponse (http/post (:token-url endpoint) {:form-params {:grant_type "client_credentials"} :as :json :coerce :always :http-client client :basic-auth {:user (:client-id endpoint) :pass (:password endpoint)}})] ;; FIXME should *really* add some error processing here ;) (:body tokenresponse))) (defn refresh-token! "Create or update token and store it in conn" [conn] (let [token (get-token (:httpc @conn) (:endpoint @conn))] (swap! conn (fn [conn token] (-> conn (assoc :token token) (assoc :refresh-at (epochTimeInc (refresh-inc (:expires_in token)))))) token ))) (defn ensure-authenticated-conn! "Update or create token if necessary, return connection value" [conn] "Refresh conn if it's stale, return value of conn" (if (refresh-now? (:refresh-at @conn)) (refresh-token! conn)) @conn) (defn papi-get! "Send a get with current bearer token" [conn args] (ensure-authenticated-conn! conn) (let [{:keys [endpoint token]} @conn] ;;this connection can fail for various reasons even if our token is fresh. FIXME: add error handling (json/read-str (:body (http/get (str (:production-url endpoint) args) {:oauth-token (:access_token token)})) :key-fn keyword))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn init "Get oauth token from Superdesk, store it in an atom, create http-client and put it in the same atom, as well as all the endpoint info (so we can regenerate the token later on" [endpoint] (let [httpc (http/build-http-client {:connect-timeout 10000}) token (get-token httpc endpoint) conn (atom {:endpoint endpoint :httpc httpc} )] (ensure-authenticated-conn! conn) ;; I need to return the wohl conn/atom, ;; so functions using this can hand us back the (stateful) connection atom for updates conn)) (defn users-list [conn] (papi-get! conn "/users")) (defn user-by-id [conn id] (papi-get! conn (str "/users/" id))) (defn item-by-guid [conn guid] (struct-with-item-paths (papi-get! conn (str "/items/" guid)))) (defn item-by-path [conn path] (let [unique_name (id-from-path path) ;; unque_name starts with a '#', so we have to urlencode it for use as URL query string query {:query {:term {:unique_name (URLEncoder/encode unique_name "UTF-8")}}}] (struct-with-item-paths (first (:_items (papi-get! conn (str "/items?source=" (json/write-str query)))))))) (defn items-by-query [conn query] "Send query for items, args are conn and query as edn which will be turned into json" (:_items (struct-with-item-paths (papi-get! conn (str "/items?source=" (json/write-str query)))))) (comment (def token-r (:body (http/post "https://superdesk.literatur.review/api/auth_server/token" {:form-params {:grant_type "client_credentials"} :as :json :coerce :always :basic-auth {:user "PI:KEY:<KEY>END_PI" :pass "PI:PASSWORD:<PASSWORD>END_PI"}}))) token-r (def endpoint {:production-url "https://superdesk.literatur.review/prodapi/v1" :token-url "https://superdesk.literatur.review/api/auth_server/token" :client-id "61a2666419b8361ae639d5f9" :password "PI:PASSWORD:<PASSWORD>END_PI"} ) (def httpc (http/build-http-client {:connect-timeout 10000})) httpc (def wrapped-token (get-token httpc endpoint)) (def conn (atom {:endpoint endpoint :httpc httpc})) conn (ensure-authenticated-conn! conn) conn (def realconn (init endpoint)) realconn (def schachnovelle (item-by-guid conn "90bf03f7-75cf-4404-b3b4-fc4b01c7b272")) schachnovelle (:authors schachnovelle) (item-authors conn (:authors schachnovelle)) (def einbild (item-by-guid conn "dcd55151-7f97-42e9-a066-07f46cc21694")) (user-by-id conn (:parent (first (:authors schachnovelle)))) (def ffox_query (json/read-str "{\"query\":{\"filtered\":{\"filter\":{\"and\":[{\"not\":{\"term\":{\"state\":\"spiked\"}}},{\"term\":{\"family_id\":\"90bf03f7-75cf-4404-b3b4-fc4b01c7b272\"}},{\"not\":{\"term\":{\"unique_id\":35}}}]}}},\"size\":200,\"from\":0,\"sort\":{\"versioncreated\":\"desc\"}}" :key-fn keyword)) (def testquery { :query { :filtered { :filter { :and [{ :not { :term { :state "spiked" } } } { :term { :family_id "90bf03f7-75cf-4404-b3b4-fc4b01c7b272" } } { :not { :term { :unique_id 35 } } } ] } } }, :size 200, :from 0, :sort { :versioncreated "desc" } } ) (def testquery2 { :query { :filtered { :filter { :and [{ :not { :term { :state "spiked" } } } { :not { :term { :unique_id 35 } } } ] } } }, :size 200, :from 0, :sort { :versioncreated "desc" } } ) (def ffox-items (items-by-query conn ffox_query)) (def composite-items (items-by-query conn (json/write-str {:query {:filtered {:filter {:not {:term {:state :spiked} }}}}}))) (def composite-items (items-by-query conn testquery2)) (def items-not-spiked-query {:query {:filtered {:filter {:not {:term {:state :spiked}}}}}} ) (def items-not-spiked-string-query "{\"query\":{\"filtered\":{\"filter\":{\"not\":{\"term\":{\"state\":\"spiked\"}}}}}}") (= (json/write-str items-not-spiked-query) items-not-spiked-string-query) (def items-not-spiked (items-by-query conn items-not-spiked-string-query)) (def testq {:query {:term {:type {:value "picture"}}} }) (def testitems (items-by-query conn (json/write-str testq))) composite-items (:_items (json/read-str (:body composite-items) :key-fn keyword)) (json/read-str (:body ffox-items)) (json/read-str (:body (users-list conn)) :key-fn keyword) (swap! conn (fn [myconn] (-> myconn (assoc :refresh-at (- (.getEpochSecond (Instant/now)) (* 5 60))) ))) (def query-r (:body (http/post "https://superdesk.literatur.review/prodapi/v1/items?source=")) ) (defn items-query [{:keys [endpoint token]} query] (http/get (str "https://superdesk.literatur.review/prodapi/v1/items?source=" (URLEncoder/encode (json/write-str {:query {:filtered {:filter {:not {:term {:state :spiked}}}}}}) "UTF-8")) {:oauth-token (:access_token token) })) (items-query @conn nil) )
[ { "context": "(comment\n Formation, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,", "end": 49, "score": 0.999880313873291, "start": 37, "tag": "NAME", "value": "Ronen Narkis" }, { "context": "omment\n Formation, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version 2.", "end": 62, "score": 0.6973394155502319, "start": 52, "tag": "EMAIL", "value": "arkisr.com" } ]
src/formation/core.clj
narkisr/formation
2
(comment Formation, 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 formation.core (:require [taoensso.timbre.appenders.core :as appenders] [clojure.tools.reader.edn :as edn] [clojure.pprint :refer (pprint)] [taoensso.timbre :as timbre] [clojure.core.strint :refer (<<)] [clojure.java.io :refer (file)])) (timbre/refer-timbre) (defn config-paths [project] [(<<"/etc/~{project}/~{project}.edn") (<< "~(System/getProperty \"user.home\")/.~{project}.edn")]) (defn path-of [project] (first (filter #(.exists (file %)) (config-paths project)))) (defn pretty-error "A pretty print error log" [m c project] (let [st (java.io.StringWriter.)] (binding [*out* st] (clojure.pprint/pprint m)) (timbre/merge-config! {:appenders {:spit (appenders/spit-appender {:fname (get-in c [(keyword project) :log :path] (<< "~{project}.log"))})}}) (error (str "Following configuration errors found:\n" (.toString st))))) (defn read-and-validate [path validate-conf project] (let [c (edn/read-string (slurp path)) es (validate-conf c)] (when-not (empty? es) (pretty-error es c project) (System/exit 1)) c)) (defn config "main configuation" [project validate-conf] (if-let [path (path-of project)] (read-and-validate path validate-conf project) (when-not (System/getProperty "disable-conf") ; enables repl/testing (error (<< "Missing configuration file, you should configure ~{project} in either ~(config-paths project)")) (System/exit 1))))
105312
(comment Formation, 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 formation.core (:require [taoensso.timbre.appenders.core :as appenders] [clojure.tools.reader.edn :as edn] [clojure.pprint :refer (pprint)] [taoensso.timbre :as timbre] [clojure.core.strint :refer (<<)] [clojure.java.io :refer (file)])) (timbre/refer-timbre) (defn config-paths [project] [(<<"/etc/~{project}/~{project}.edn") (<< "~(System/getProperty \"user.home\")/.~{project}.edn")]) (defn path-of [project] (first (filter #(.exists (file %)) (config-paths project)))) (defn pretty-error "A pretty print error log" [m c project] (let [st (java.io.StringWriter.)] (binding [*out* st] (clojure.pprint/pprint m)) (timbre/merge-config! {:appenders {:spit (appenders/spit-appender {:fname (get-in c [(keyword project) :log :path] (<< "~{project}.log"))})}}) (error (str "Following configuration errors found:\n" (.toString st))))) (defn read-and-validate [path validate-conf project] (let [c (edn/read-string (slurp path)) es (validate-conf c)] (when-not (empty? es) (pretty-error es c project) (System/exit 1)) c)) (defn config "main configuation" [project validate-conf] (if-let [path (path-of project)] (read-and-validate path validate-conf project) (when-not (System/getProperty "disable-conf") ; enables repl/testing (error (<< "Missing configuration file, you should configure ~{project} in either ~(config-paths project)")) (System/exit 1))))
true
(comment Formation, 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 formation.core (:require [taoensso.timbre.appenders.core :as appenders] [clojure.tools.reader.edn :as edn] [clojure.pprint :refer (pprint)] [taoensso.timbre :as timbre] [clojure.core.strint :refer (<<)] [clojure.java.io :refer (file)])) (timbre/refer-timbre) (defn config-paths [project] [(<<"/etc/~{project}/~{project}.edn") (<< "~(System/getProperty \"user.home\")/.~{project}.edn")]) (defn path-of [project] (first (filter #(.exists (file %)) (config-paths project)))) (defn pretty-error "A pretty print error log" [m c project] (let [st (java.io.StringWriter.)] (binding [*out* st] (clojure.pprint/pprint m)) (timbre/merge-config! {:appenders {:spit (appenders/spit-appender {:fname (get-in c [(keyword project) :log :path] (<< "~{project}.log"))})}}) (error (str "Following configuration errors found:\n" (.toString st))))) (defn read-and-validate [path validate-conf project] (let [c (edn/read-string (slurp path)) es (validate-conf c)] (when-not (empty? es) (pretty-error es c project) (System/exit 1)) c)) (defn config "main configuation" [project validate-conf] (if-let [path (path-of project)] (read-and-validate path validate-conf project) (when-not (System/getProperty "disable-conf") ; enables repl/testing (error (<< "Missing configuration file, you should configure ~{project} in either ~(config-paths project)")) (System/exit 1))))
[ { "context": " {:authorize-url \"https://github.com/login/oauth/authorize\"\n :access-token-url ", "end": 1990, "score": 0.9332331418991089, "start": 1985, "tag": "USERNAME", "value": "login" }, { "context": " :access-token-url \"https://github.com/login/oauth/access_token\"\n :client-id ", "end": 2071, "score": 0.8166596293449402, "start": 2066, "tag": "USERNAME", "value": "login" }, { "context": "CLIENT_ID\"\n :client-secret \"CLIENT_SECRET\"\n :scopes [\"u", "end": 2187, "score": 0.8174195289611816, "start": 2181, "tag": "KEY", "value": "CLIENT" } ]
resources/leiningen/new/cyrus/src/_namespace_/authenticator.clj
dryewo/cyrus
9
(ns {{namespace}}.authenticator (:require [mount.lite :as m] [dovetail.core :as log] [cyrus-config.core :as cfg]{{#swagger1st-oauth2}} [fahrscheine-bitte.core :as oauth2]{{/swagger1st-oauth2}}{{#ui-oauth2}} [cyrus-ui-oauth2.core :as ui-oauth2]{{/ui-oauth2}})) (cfg/def TOKENINFO_URL "URL to check access tokens against. If not set, tokens won't be checked.") {{#swagger1st-oauth2}} ;; Checks if TOKENINFO_URL is set and returns a pass-through handler in case it's not ;; Works as a security handler for io.sarnowski.swagger1st.core/protector (m/defstate oauth2-s1st-security-handler :start (if TOKENINFO_URL (let [access-token-resolver-fn (oauth2/make-cached-access-token-resolver TOKENINFO_URL {})] (log/info "Checking OAuth2 access tokens against %s." TOKENINFO_URL) (oauth2/make-oauth2-s1st-security-handler access-token-resolver-fn oauth2/check-corresponding-attributes)) (do (log/warn "TOKENINFO_URL is not set; NOT CHECKING ACCESS TOKENS!") (fn [request definition requirements] request)))) (defn log-access-denied-reason [reason] (log/info "Access denied: %s" reason)) (defn wrap-reason-logger [handler] (oauth2/wrap-log-auth-error handler log-access-denied-reason)) {{/swagger1st-oauth2}}{{#ui-oauth2}} (cfg/def EXTERNAL_URL "Public URL of the deployed application, used to generate redirect back from IAM provider.") (cfg/def UI_ALLOW_ANON "Whether to allow unauthenticated users in web UI." {:spec boolean?}) (m/defstate ui-oauth2-profile :start (if UI_ALLOW_ANON (do (log/warn "UI_ALLOW_ANON is set; NOT PROTECTING UI!") nil) ;; Go to https://github.com/settings/developers and register a new app (use http://localhost:8080/ui/callback), ;; copy its client credentials here. {:authorize-url "https://github.com/login/oauth/authorize" :access-token-url "https://github.com/login/oauth/access_token" :client-id "CLIENT_ID" :client-secret "CLIENT_SECRET" :scopes ["user:email"] :allow-anon? UI_ALLOW_ANON :external-url EXTERNAL_URL :default-landing-endpoint "/ui" :redirect-endpoint "/ui/callback" :login-endpoint "/ui/login" :logout-endpoint "/ui/logout"})) (defn wrap-ui-oauth2 [handler] (if @ui-oauth2-profile (ui-oauth2/wrap-ui-oauth2 handler @ui-oauth2-profile) handler)) {{/ui-oauth2}}
61343
(ns {{namespace}}.authenticator (:require [mount.lite :as m] [dovetail.core :as log] [cyrus-config.core :as cfg]{{#swagger1st-oauth2}} [fahrscheine-bitte.core :as oauth2]{{/swagger1st-oauth2}}{{#ui-oauth2}} [cyrus-ui-oauth2.core :as ui-oauth2]{{/ui-oauth2}})) (cfg/def TOKENINFO_URL "URL to check access tokens against. If not set, tokens won't be checked.") {{#swagger1st-oauth2}} ;; Checks if TOKENINFO_URL is set and returns a pass-through handler in case it's not ;; Works as a security handler for io.sarnowski.swagger1st.core/protector (m/defstate oauth2-s1st-security-handler :start (if TOKENINFO_URL (let [access-token-resolver-fn (oauth2/make-cached-access-token-resolver TOKENINFO_URL {})] (log/info "Checking OAuth2 access tokens against %s." TOKENINFO_URL) (oauth2/make-oauth2-s1st-security-handler access-token-resolver-fn oauth2/check-corresponding-attributes)) (do (log/warn "TOKENINFO_URL is not set; NOT CHECKING ACCESS TOKENS!") (fn [request definition requirements] request)))) (defn log-access-denied-reason [reason] (log/info "Access denied: %s" reason)) (defn wrap-reason-logger [handler] (oauth2/wrap-log-auth-error handler log-access-denied-reason)) {{/swagger1st-oauth2}}{{#ui-oauth2}} (cfg/def EXTERNAL_URL "Public URL of the deployed application, used to generate redirect back from IAM provider.") (cfg/def UI_ALLOW_ANON "Whether to allow unauthenticated users in web UI." {:spec boolean?}) (m/defstate ui-oauth2-profile :start (if UI_ALLOW_ANON (do (log/warn "UI_ALLOW_ANON is set; NOT PROTECTING UI!") nil) ;; Go to https://github.com/settings/developers and register a new app (use http://localhost:8080/ui/callback), ;; copy its client credentials here. {:authorize-url "https://github.com/login/oauth/authorize" :access-token-url "https://github.com/login/oauth/access_token" :client-id "CLIENT_ID" :client-secret "<KEY>_SECRET" :scopes ["user:email"] :allow-anon? UI_ALLOW_ANON :external-url EXTERNAL_URL :default-landing-endpoint "/ui" :redirect-endpoint "/ui/callback" :login-endpoint "/ui/login" :logout-endpoint "/ui/logout"})) (defn wrap-ui-oauth2 [handler] (if @ui-oauth2-profile (ui-oauth2/wrap-ui-oauth2 handler @ui-oauth2-profile) handler)) {{/ui-oauth2}}
true
(ns {{namespace}}.authenticator (:require [mount.lite :as m] [dovetail.core :as log] [cyrus-config.core :as cfg]{{#swagger1st-oauth2}} [fahrscheine-bitte.core :as oauth2]{{/swagger1st-oauth2}}{{#ui-oauth2}} [cyrus-ui-oauth2.core :as ui-oauth2]{{/ui-oauth2}})) (cfg/def TOKENINFO_URL "URL to check access tokens against. If not set, tokens won't be checked.") {{#swagger1st-oauth2}} ;; Checks if TOKENINFO_URL is set and returns a pass-through handler in case it's not ;; Works as a security handler for io.sarnowski.swagger1st.core/protector (m/defstate oauth2-s1st-security-handler :start (if TOKENINFO_URL (let [access-token-resolver-fn (oauth2/make-cached-access-token-resolver TOKENINFO_URL {})] (log/info "Checking OAuth2 access tokens against %s." TOKENINFO_URL) (oauth2/make-oauth2-s1st-security-handler access-token-resolver-fn oauth2/check-corresponding-attributes)) (do (log/warn "TOKENINFO_URL is not set; NOT CHECKING ACCESS TOKENS!") (fn [request definition requirements] request)))) (defn log-access-denied-reason [reason] (log/info "Access denied: %s" reason)) (defn wrap-reason-logger [handler] (oauth2/wrap-log-auth-error handler log-access-denied-reason)) {{/swagger1st-oauth2}}{{#ui-oauth2}} (cfg/def EXTERNAL_URL "Public URL of the deployed application, used to generate redirect back from IAM provider.") (cfg/def UI_ALLOW_ANON "Whether to allow unauthenticated users in web UI." {:spec boolean?}) (m/defstate ui-oauth2-profile :start (if UI_ALLOW_ANON (do (log/warn "UI_ALLOW_ANON is set; NOT PROTECTING UI!") nil) ;; Go to https://github.com/settings/developers and register a new app (use http://localhost:8080/ui/callback), ;; copy its client credentials here. {:authorize-url "https://github.com/login/oauth/authorize" :access-token-url "https://github.com/login/oauth/access_token" :client-id "CLIENT_ID" :client-secret "PI:KEY:<KEY>END_PI_SECRET" :scopes ["user:email"] :allow-anon? UI_ALLOW_ANON :external-url EXTERNAL_URL :default-landing-endpoint "/ui" :redirect-endpoint "/ui/callback" :login-endpoint "/ui/login" :logout-endpoint "/ui/logout"})) (defn wrap-ui-oauth2 [handler] (if @ui-oauth2-profile (ui-oauth2/wrap-ui-oauth2 handler @ui-oauth2-profile) handler)) {{/ui-oauth2}}
[ { "context": "\"name\": \"new-name\"}\n ;; /update | [{\"name\": \"new-name\", \"id\": 5} {\"name\": \"other\", \"id\": 6}]\n (", "end": 8643, "score": 0.6419525742530823, "start": 8640, "tag": "NAME", "value": "new" }, { "context": "cause they should just be the id field... I hope - natevecc\n transformed-params (rename-keys (keywor", "end": 10391, "score": 0.9981592893600464, "start": 10383, "tag": "USERNAME", "value": "natevecc" } ]
src/com/rjmetrics/sweet_liberty/handlers.clj
RJMetrics/sweet-liberty
114
(ns com.rjmetrics.sweet-liberty.handlers (:require [clojure.walk :refer [keywordize-keys]] [clojure.data.json :as json] [clojure.tools.logging :as log] [com.rjmetrics.sweet-liberty.util :as util] [com.rjmetrics.sweet-liberty.expansion :as expansion] [com.rjmetrics.sweet-liberty.db :as db] [com.rjmetrics.sweet-liberty.process :as p] [com.rjmetrics.sweet-liberty.request-interpretation :as req] [clojure.set :refer [rename-keys map-invert]])) (defn- log-request-from-context [ctx] (let [mdc (into {} (org.apache.log4j.MDC/getContext)) log-structure (-> ctx (select-keys [:request]) (merge mdc))] (log/debug (json/write-str log-structure :value-fn util/json-value-fn)))) (defn- make-special-query-param-processor-fn "Make function to apply expansion and grouping response processing." [ctx service-broker table] (fn [result-data] (let [request (:request ctx)] (->> result-data (expansion/expand-all-resources service-broker (:route-params request) (req/extract-expand-query-param request) table (:headers request)))))) (defn- run-with-conditions "Runs preconditions, executor and postconditions in appropriate order. Throws exception if condition fails." [data conditions ctx executor] (log-request-from-context ctx) (if ((:before conditions (constantly true)) data ctx) (let [result (executor)] (if ((:after conditions (constantly true)) data result ctx) result (throw (ex-info (str (req/raw-request-method ctx) " Postcondition failed") {:is-sweet-lib-exception? true :more-info ""})))) (throw (ex-info (str (req/raw-request-method ctx) " Precondition failed") {:is-sweet-lib-exception? true :more-info ""})))) (defn make-allowed?-handler-fn "Create a handler for the 'allowed?' liberator hook based on permissions supplied. Permissions can either be a function or a map with http methods as keys and respective permission functions as values." [permissions] (fn [ctx] ((cond (fn? permissions) permissions (map? permissions) (get permissions (-> ctx :request :request-method) (get permissions :any (constantly false)))) ctx))) (defn make-entities-exist?-fn "Check to see if any entities exist for the given database, table and the query-params of the request object. Existing entities are attached to the ctx with the ::entities keyword" [table db-spec url-params name-transforms query-transform output-transform] (fn [{{:keys [query-params]} :request :as ctx}] (log-request-from-context ctx) (let [keyworded-input (keywordize-keys (merge query-params url-params)) where-map (p/resource->db ctx keyworded-input :key-rename-map name-transforms :values-transform-fn query-transform) entities (db/get-records-from-storage db-spec table where-map) entities-transformed (p/db->resource ctx entities :key-rename-map name-transforms :values-transform-fn output-transform)] [true {util/entities-kw entities util/existing-entities-transformed-kw entities-transformed}]))) (defn- entity-exists-where-map "If we aren't doing a PUT (normal), just get a single entity from the route params. Otherwise extract the keys from the body for a bulk put based on column-name" [column-name url-params {{:keys [body-params form-params route-params body request-method]} :request :as ctx}] (let [params (or body-params form-params)] (hash-map column-name (if (and (= :put request-method) (seq params) (not (map? params))) (vec (map column-name (map keywordize-keys params))) (or (get url-params column-name) (get route-params column-name)))))) (defn make-entity-exists?-fn "Check to see if an entity exists for the given database, table and route-params of the request object. If an entity is found it is attached to the ctx object with the ::entities keyword." [table db-spec url-params column-name name-transforms query-transform output-transform] (fn [{{:keys [route-params]} :request :as ctx}] (log-request-from-context ctx) (let [where (entity-exists-where-map column-name url-params ctx) transformed-where (p/resource->db ctx where :key-rename-map name-transforms :values-transform-fn query-transform) results (seq (db/get-records-from-storage db-spec table transformed-where)) results-transformed (p/db->resource ctx results :key-rename-map name-transforms :values-transform-fn output-transform)] (if results [true {util/entities-kw results util/existing-entities-transformed-kw results-transformed}] false)))) (defn make-read-created-entity-fn "Create a function that reads the new entity from storage and attaches it to the liberator context map at ::entities." [db-spec table-struct name-transforms output-transform controller service-broker] (fn [ctx] (log-request-from-context ctx) (let [created-entity (db/get-records-from-storage db-spec table-struct (hash-map (:primary-key table-struct) (get ctx util/post-id-kw)))] (-> ctx (assoc util/entities-kw created-entity) (p/process-data-response name-transforms output-transform (or controller util/identity-transform-fn) false))))) (defn make-create-entity-fn "Create a function that creates a new entity in storage and returns the new primary key value on the ctx at ::post-id." [table db-spec name-transforms input-transform _ conditions] (fn [{{form-params :form-params body-params :body-params} :request :as ctx}] (let [data (keywordize-keys (or body-params form-params)) transformed-data (p/resource->db ctx data :key-rename-map name-transforms :values-transform-fn input-transform)] (->> (run-with-conditions data conditions ctx #(db/insert-entity-into-storage table db-spec transformed-data)) (hash-map util/post-id-kw))))) (defn make-read-entities-fn "Create a function that returns a entity collection after running the given result-set-transform-fn on it." [db-spec table-struct name-transforms output-transform controller collection? service-broker] (fn [ctx] (p/process-data-response ctx name-transforms output-transform controller collection? :inject-processing (make-special-query-param-processor-fn ctx service-broker table-struct)))) (defn make-update-entity-fn [table db-spec column-name name-transforms query-transform input-transform output-transform url-params conditions] (fn [{:keys [request] :as ctx}] ;; Form params only exist if the body is of content type form-urlencoded ;; Body params only exist if it's json or otherwise. ;; Url formencoded CANNOT be bulk, only single updates. ;; Examples - Route | Body ;; /update/5 | name=new-name ;; /update/5 | {"name": "new-name"} ;; /update | [{"name": "new-name", "id": 5} {"name": "other", "id": 6}] (let [data (req/extract-merged-body-params request url-params) transformed-params (p/resource->db ctx (req/extract-merged-query-params request url-params) :key-rename-map name-transforms :values-transform-fn query-transform) transformed-column-name (get (map-invert name-transforms) column-name column-name)] (->> (p/resource->db ctx data :key-rename-map name-transforms :values-transform-fn input-transform) (partial db/update-entity-in-storage transformed-column-name (keywordize-keys transformed-params) ctx table db-spec) (run-with-conditions data conditions ctx) (hash-map util/entities-kw))))) (defn make-delete-entity-fn "Make a handler function for deleting one or more entities from storage." [table db-spec column-name name-transforms conditions] ;; :params is used here since otherwise we'd merge all parameters together anyway ;; E.g. DELETE /item/5, /items?id=5&id=6, /items id=5&id=6, /items {"id":[5, 6]} ;; These would parse to route params, query params, form params, and body params. (fn [{{params :params} :request :as ctx}] (let [;; we only have to transform the names of the params because they should just be the id field... I hope - natevecc transformed-params (rename-keys (keywordize-keys params) (map-invert name-transforms)) transformed-column-name (get (map-invert name-transforms) column-name column-name) data (keywordize-keys params)] (->> (p/resource->db ctx data :key-rename-map name-transforms) (partial db/delete-entity-in-storage transformed-column-name transformed-params table db-spec) (run-with-conditions data conditions ctx)))))
103503
(ns com.rjmetrics.sweet-liberty.handlers (:require [clojure.walk :refer [keywordize-keys]] [clojure.data.json :as json] [clojure.tools.logging :as log] [com.rjmetrics.sweet-liberty.util :as util] [com.rjmetrics.sweet-liberty.expansion :as expansion] [com.rjmetrics.sweet-liberty.db :as db] [com.rjmetrics.sweet-liberty.process :as p] [com.rjmetrics.sweet-liberty.request-interpretation :as req] [clojure.set :refer [rename-keys map-invert]])) (defn- log-request-from-context [ctx] (let [mdc (into {} (org.apache.log4j.MDC/getContext)) log-structure (-> ctx (select-keys [:request]) (merge mdc))] (log/debug (json/write-str log-structure :value-fn util/json-value-fn)))) (defn- make-special-query-param-processor-fn "Make function to apply expansion and grouping response processing." [ctx service-broker table] (fn [result-data] (let [request (:request ctx)] (->> result-data (expansion/expand-all-resources service-broker (:route-params request) (req/extract-expand-query-param request) table (:headers request)))))) (defn- run-with-conditions "Runs preconditions, executor and postconditions in appropriate order. Throws exception if condition fails." [data conditions ctx executor] (log-request-from-context ctx) (if ((:before conditions (constantly true)) data ctx) (let [result (executor)] (if ((:after conditions (constantly true)) data result ctx) result (throw (ex-info (str (req/raw-request-method ctx) " Postcondition failed") {:is-sweet-lib-exception? true :more-info ""})))) (throw (ex-info (str (req/raw-request-method ctx) " Precondition failed") {:is-sweet-lib-exception? true :more-info ""})))) (defn make-allowed?-handler-fn "Create a handler for the 'allowed?' liberator hook based on permissions supplied. Permissions can either be a function or a map with http methods as keys and respective permission functions as values." [permissions] (fn [ctx] ((cond (fn? permissions) permissions (map? permissions) (get permissions (-> ctx :request :request-method) (get permissions :any (constantly false)))) ctx))) (defn make-entities-exist?-fn "Check to see if any entities exist for the given database, table and the query-params of the request object. Existing entities are attached to the ctx with the ::entities keyword" [table db-spec url-params name-transforms query-transform output-transform] (fn [{{:keys [query-params]} :request :as ctx}] (log-request-from-context ctx) (let [keyworded-input (keywordize-keys (merge query-params url-params)) where-map (p/resource->db ctx keyworded-input :key-rename-map name-transforms :values-transform-fn query-transform) entities (db/get-records-from-storage db-spec table where-map) entities-transformed (p/db->resource ctx entities :key-rename-map name-transforms :values-transform-fn output-transform)] [true {util/entities-kw entities util/existing-entities-transformed-kw entities-transformed}]))) (defn- entity-exists-where-map "If we aren't doing a PUT (normal), just get a single entity from the route params. Otherwise extract the keys from the body for a bulk put based on column-name" [column-name url-params {{:keys [body-params form-params route-params body request-method]} :request :as ctx}] (let [params (or body-params form-params)] (hash-map column-name (if (and (= :put request-method) (seq params) (not (map? params))) (vec (map column-name (map keywordize-keys params))) (or (get url-params column-name) (get route-params column-name)))))) (defn make-entity-exists?-fn "Check to see if an entity exists for the given database, table and route-params of the request object. If an entity is found it is attached to the ctx object with the ::entities keyword." [table db-spec url-params column-name name-transforms query-transform output-transform] (fn [{{:keys [route-params]} :request :as ctx}] (log-request-from-context ctx) (let [where (entity-exists-where-map column-name url-params ctx) transformed-where (p/resource->db ctx where :key-rename-map name-transforms :values-transform-fn query-transform) results (seq (db/get-records-from-storage db-spec table transformed-where)) results-transformed (p/db->resource ctx results :key-rename-map name-transforms :values-transform-fn output-transform)] (if results [true {util/entities-kw results util/existing-entities-transformed-kw results-transformed}] false)))) (defn make-read-created-entity-fn "Create a function that reads the new entity from storage and attaches it to the liberator context map at ::entities." [db-spec table-struct name-transforms output-transform controller service-broker] (fn [ctx] (log-request-from-context ctx) (let [created-entity (db/get-records-from-storage db-spec table-struct (hash-map (:primary-key table-struct) (get ctx util/post-id-kw)))] (-> ctx (assoc util/entities-kw created-entity) (p/process-data-response name-transforms output-transform (or controller util/identity-transform-fn) false))))) (defn make-create-entity-fn "Create a function that creates a new entity in storage and returns the new primary key value on the ctx at ::post-id." [table db-spec name-transforms input-transform _ conditions] (fn [{{form-params :form-params body-params :body-params} :request :as ctx}] (let [data (keywordize-keys (or body-params form-params)) transformed-data (p/resource->db ctx data :key-rename-map name-transforms :values-transform-fn input-transform)] (->> (run-with-conditions data conditions ctx #(db/insert-entity-into-storage table db-spec transformed-data)) (hash-map util/post-id-kw))))) (defn make-read-entities-fn "Create a function that returns a entity collection after running the given result-set-transform-fn on it." [db-spec table-struct name-transforms output-transform controller collection? service-broker] (fn [ctx] (p/process-data-response ctx name-transforms output-transform controller collection? :inject-processing (make-special-query-param-processor-fn ctx service-broker table-struct)))) (defn make-update-entity-fn [table db-spec column-name name-transforms query-transform input-transform output-transform url-params conditions] (fn [{:keys [request] :as ctx}] ;; Form params only exist if the body is of content type form-urlencoded ;; Body params only exist if it's json or otherwise. ;; Url formencoded CANNOT be bulk, only single updates. ;; Examples - Route | Body ;; /update/5 | name=new-name ;; /update/5 | {"name": "new-name"} ;; /update | [{"name": "<NAME>-name", "id": 5} {"name": "other", "id": 6}] (let [data (req/extract-merged-body-params request url-params) transformed-params (p/resource->db ctx (req/extract-merged-query-params request url-params) :key-rename-map name-transforms :values-transform-fn query-transform) transformed-column-name (get (map-invert name-transforms) column-name column-name)] (->> (p/resource->db ctx data :key-rename-map name-transforms :values-transform-fn input-transform) (partial db/update-entity-in-storage transformed-column-name (keywordize-keys transformed-params) ctx table db-spec) (run-with-conditions data conditions ctx) (hash-map util/entities-kw))))) (defn make-delete-entity-fn "Make a handler function for deleting one or more entities from storage." [table db-spec column-name name-transforms conditions] ;; :params is used here since otherwise we'd merge all parameters together anyway ;; E.g. DELETE /item/5, /items?id=5&id=6, /items id=5&id=6, /items {"id":[5, 6]} ;; These would parse to route params, query params, form params, and body params. (fn [{{params :params} :request :as ctx}] (let [;; we only have to transform the names of the params because they should just be the id field... I hope - natevecc transformed-params (rename-keys (keywordize-keys params) (map-invert name-transforms)) transformed-column-name (get (map-invert name-transforms) column-name column-name) data (keywordize-keys params)] (->> (p/resource->db ctx data :key-rename-map name-transforms) (partial db/delete-entity-in-storage transformed-column-name transformed-params table db-spec) (run-with-conditions data conditions ctx)))))
true
(ns com.rjmetrics.sweet-liberty.handlers (:require [clojure.walk :refer [keywordize-keys]] [clojure.data.json :as json] [clojure.tools.logging :as log] [com.rjmetrics.sweet-liberty.util :as util] [com.rjmetrics.sweet-liberty.expansion :as expansion] [com.rjmetrics.sweet-liberty.db :as db] [com.rjmetrics.sweet-liberty.process :as p] [com.rjmetrics.sweet-liberty.request-interpretation :as req] [clojure.set :refer [rename-keys map-invert]])) (defn- log-request-from-context [ctx] (let [mdc (into {} (org.apache.log4j.MDC/getContext)) log-structure (-> ctx (select-keys [:request]) (merge mdc))] (log/debug (json/write-str log-structure :value-fn util/json-value-fn)))) (defn- make-special-query-param-processor-fn "Make function to apply expansion and grouping response processing." [ctx service-broker table] (fn [result-data] (let [request (:request ctx)] (->> result-data (expansion/expand-all-resources service-broker (:route-params request) (req/extract-expand-query-param request) table (:headers request)))))) (defn- run-with-conditions "Runs preconditions, executor and postconditions in appropriate order. Throws exception if condition fails." [data conditions ctx executor] (log-request-from-context ctx) (if ((:before conditions (constantly true)) data ctx) (let [result (executor)] (if ((:after conditions (constantly true)) data result ctx) result (throw (ex-info (str (req/raw-request-method ctx) " Postcondition failed") {:is-sweet-lib-exception? true :more-info ""})))) (throw (ex-info (str (req/raw-request-method ctx) " Precondition failed") {:is-sweet-lib-exception? true :more-info ""})))) (defn make-allowed?-handler-fn "Create a handler for the 'allowed?' liberator hook based on permissions supplied. Permissions can either be a function or a map with http methods as keys and respective permission functions as values." [permissions] (fn [ctx] ((cond (fn? permissions) permissions (map? permissions) (get permissions (-> ctx :request :request-method) (get permissions :any (constantly false)))) ctx))) (defn make-entities-exist?-fn "Check to see if any entities exist for the given database, table and the query-params of the request object. Existing entities are attached to the ctx with the ::entities keyword" [table db-spec url-params name-transforms query-transform output-transform] (fn [{{:keys [query-params]} :request :as ctx}] (log-request-from-context ctx) (let [keyworded-input (keywordize-keys (merge query-params url-params)) where-map (p/resource->db ctx keyworded-input :key-rename-map name-transforms :values-transform-fn query-transform) entities (db/get-records-from-storage db-spec table where-map) entities-transformed (p/db->resource ctx entities :key-rename-map name-transforms :values-transform-fn output-transform)] [true {util/entities-kw entities util/existing-entities-transformed-kw entities-transformed}]))) (defn- entity-exists-where-map "If we aren't doing a PUT (normal), just get a single entity from the route params. Otherwise extract the keys from the body for a bulk put based on column-name" [column-name url-params {{:keys [body-params form-params route-params body request-method]} :request :as ctx}] (let [params (or body-params form-params)] (hash-map column-name (if (and (= :put request-method) (seq params) (not (map? params))) (vec (map column-name (map keywordize-keys params))) (or (get url-params column-name) (get route-params column-name)))))) (defn make-entity-exists?-fn "Check to see if an entity exists for the given database, table and route-params of the request object. If an entity is found it is attached to the ctx object with the ::entities keyword." [table db-spec url-params column-name name-transforms query-transform output-transform] (fn [{{:keys [route-params]} :request :as ctx}] (log-request-from-context ctx) (let [where (entity-exists-where-map column-name url-params ctx) transformed-where (p/resource->db ctx where :key-rename-map name-transforms :values-transform-fn query-transform) results (seq (db/get-records-from-storage db-spec table transformed-where)) results-transformed (p/db->resource ctx results :key-rename-map name-transforms :values-transform-fn output-transform)] (if results [true {util/entities-kw results util/existing-entities-transformed-kw results-transformed}] false)))) (defn make-read-created-entity-fn "Create a function that reads the new entity from storage and attaches it to the liberator context map at ::entities." [db-spec table-struct name-transforms output-transform controller service-broker] (fn [ctx] (log-request-from-context ctx) (let [created-entity (db/get-records-from-storage db-spec table-struct (hash-map (:primary-key table-struct) (get ctx util/post-id-kw)))] (-> ctx (assoc util/entities-kw created-entity) (p/process-data-response name-transforms output-transform (or controller util/identity-transform-fn) false))))) (defn make-create-entity-fn "Create a function that creates a new entity in storage and returns the new primary key value on the ctx at ::post-id." [table db-spec name-transforms input-transform _ conditions] (fn [{{form-params :form-params body-params :body-params} :request :as ctx}] (let [data (keywordize-keys (or body-params form-params)) transformed-data (p/resource->db ctx data :key-rename-map name-transforms :values-transform-fn input-transform)] (->> (run-with-conditions data conditions ctx #(db/insert-entity-into-storage table db-spec transformed-data)) (hash-map util/post-id-kw))))) (defn make-read-entities-fn "Create a function that returns a entity collection after running the given result-set-transform-fn on it." [db-spec table-struct name-transforms output-transform controller collection? service-broker] (fn [ctx] (p/process-data-response ctx name-transforms output-transform controller collection? :inject-processing (make-special-query-param-processor-fn ctx service-broker table-struct)))) (defn make-update-entity-fn [table db-spec column-name name-transforms query-transform input-transform output-transform url-params conditions] (fn [{:keys [request] :as ctx}] ;; Form params only exist if the body is of content type form-urlencoded ;; Body params only exist if it's json or otherwise. ;; Url formencoded CANNOT be bulk, only single updates. ;; Examples - Route | Body ;; /update/5 | name=new-name ;; /update/5 | {"name": "new-name"} ;; /update | [{"name": "PI:NAME:<NAME>END_PI-name", "id": 5} {"name": "other", "id": 6}] (let [data (req/extract-merged-body-params request url-params) transformed-params (p/resource->db ctx (req/extract-merged-query-params request url-params) :key-rename-map name-transforms :values-transform-fn query-transform) transformed-column-name (get (map-invert name-transforms) column-name column-name)] (->> (p/resource->db ctx data :key-rename-map name-transforms :values-transform-fn input-transform) (partial db/update-entity-in-storage transformed-column-name (keywordize-keys transformed-params) ctx table db-spec) (run-with-conditions data conditions ctx) (hash-map util/entities-kw))))) (defn make-delete-entity-fn "Make a handler function for deleting one or more entities from storage." [table db-spec column-name name-transforms conditions] ;; :params is used here since otherwise we'd merge all parameters together anyway ;; E.g. DELETE /item/5, /items?id=5&id=6, /items id=5&id=6, /items {"id":[5, 6]} ;; These would parse to route params, query params, form params, and body params. (fn [{{params :params} :request :as ctx}] (let [;; we only have to transform the names of the params because they should just be the id field... I hope - natevecc transformed-params (rename-keys (keywordize-keys params) (map-invert name-transforms)) transformed-column-name (get (map-invert name-transforms) column-name column-name) data (keywordize-keys params)] (->> (p/resource->db ctx data :key-rename-map name-transforms) (partial db/delete-entity-in-storage transformed-column-name transformed-params table db-spec) (run-with-conditions data conditions ctx)))))
[ { "context": "nput#login-password.ui-inited\n {:placeholder \"Password\"\n :name \"password\"\n :type ", "end": 588, "score": 0.9623198509216309, "start": 580, "tag": "PASSWORD", "value": "Password" } ]
src/clj/clojurecademy/view/login.clj
harunpehlivan/clojurecademy
651
(ns clojurecademy.view.login (:require [hiccup.page :refer [include-js include-css html5]] [hiccup.core :as hiccup] [clojurecademy.view.common :as view.common])) (defn username-or-email-field [] [:div.form-field [:div.field.field--text [:input#login-username-or-email.ui-inited {:autofocus true :placeholder "Username or email" :name "username-or-email" :type "text"}]]]) (defn password-field [] [:div.form-field [:div.field.field--text [:input#login-password.ui-inited {:placeholder "Password" :name "password" :type "password"}]]]) (defn error-field [] [:div.field-errors [:div#login-error-field.field-error]]) (defn submit-field [] [:input#login-button.button.button--large.button--secondary.button--fill-space.ui-inited {:value "Log in" :name "commit" :type "submit"}]) (defn forgot-field [] [:a.forgot-password {:href "/forgotpass"} "Forgot your password?"]) (defn html [_] (view.common/full-html "Login" [:main.sessions.new [:article.fit-fixed [:div.grid-row [:div.grid-col-12 [:div.grid-row.grid-col-12 [:div.grid-col-6.grid-col--center.login-registration-form.grid-col--no-padding [:div {:data-react-class "LoginRegistrationForms"} [:div.login-registration-forms [:div.login-registration-form ;(text-field) [:div.new_user (username-or-email-field) (password-field) (error-field) (submit-field)] (forgot-field)]]]]]]]]]))
102046
(ns clojurecademy.view.login (:require [hiccup.page :refer [include-js include-css html5]] [hiccup.core :as hiccup] [clojurecademy.view.common :as view.common])) (defn username-or-email-field [] [:div.form-field [:div.field.field--text [:input#login-username-or-email.ui-inited {:autofocus true :placeholder "Username or email" :name "username-or-email" :type "text"}]]]) (defn password-field [] [:div.form-field [:div.field.field--text [:input#login-password.ui-inited {:placeholder "<PASSWORD>" :name "password" :type "password"}]]]) (defn error-field [] [:div.field-errors [:div#login-error-field.field-error]]) (defn submit-field [] [:input#login-button.button.button--large.button--secondary.button--fill-space.ui-inited {:value "Log in" :name "commit" :type "submit"}]) (defn forgot-field [] [:a.forgot-password {:href "/forgotpass"} "Forgot your password?"]) (defn html [_] (view.common/full-html "Login" [:main.sessions.new [:article.fit-fixed [:div.grid-row [:div.grid-col-12 [:div.grid-row.grid-col-12 [:div.grid-col-6.grid-col--center.login-registration-form.grid-col--no-padding [:div {:data-react-class "LoginRegistrationForms"} [:div.login-registration-forms [:div.login-registration-form ;(text-field) [:div.new_user (username-or-email-field) (password-field) (error-field) (submit-field)] (forgot-field)]]]]]]]]]))
true
(ns clojurecademy.view.login (:require [hiccup.page :refer [include-js include-css html5]] [hiccup.core :as hiccup] [clojurecademy.view.common :as view.common])) (defn username-or-email-field [] [:div.form-field [:div.field.field--text [:input#login-username-or-email.ui-inited {:autofocus true :placeholder "Username or email" :name "username-or-email" :type "text"}]]]) (defn password-field [] [:div.form-field [:div.field.field--text [:input#login-password.ui-inited {:placeholder "PI:PASSWORD:<PASSWORD>END_PI" :name "password" :type "password"}]]]) (defn error-field [] [:div.field-errors [:div#login-error-field.field-error]]) (defn submit-field [] [:input#login-button.button.button--large.button--secondary.button--fill-space.ui-inited {:value "Log in" :name "commit" :type "submit"}]) (defn forgot-field [] [:a.forgot-password {:href "/forgotpass"} "Forgot your password?"]) (defn html [_] (view.common/full-html "Login" [:main.sessions.new [:article.fit-fixed [:div.grid-row [:div.grid-col-12 [:div.grid-row.grid-col-12 [:div.grid-col-6.grid-col--center.login-registration-form.grid-col--no-padding [:div {:data-react-class "LoginRegistrationForms"} [:div.login-registration-forms [:div.login-registration-form ;(text-field) [:div.new_user (username-or-email-field) (password-field) (error-field) (submit-field)] (forgot-field)]]]]]]]]]))
[ { "context": "parser {}))\n\n(def sample-item\n {:id 42\n :name \"Some Product\"\n :description \"This should be a cool product.\"", "end": 175, "score": 0.9135626554489136, "start": 163, "tag": "NAME", "value": "Some Product" }, { "context": "d time: 3013.386195 msecs\"\n ; => {:id 42, :name \"Some Product\", :description \"This should be a cool product.\"}\n", "end": 704, "score": 0.8817890882492065, "start": 692, "tag": "NAME", "value": "Some Product" }, { "context": "ed time: 1006.479409 msecs\"\n ;=> {:id 42, :name \"Some Product\", :description \"This should be a cool product.\"}\n", "end": 1155, "score": 0.873913049697876, "start": 1143, "tag": "NAME", "value": "Some Product" } ]
src-docs/com/wsscode/pathom/book/entities/atom_entities.cljc
agilecreativity/pathom
0
(ns com.wsscode.pathom.book.entities.atom-entities (:require [com.wsscode.pathom.core :as p])) (def parser (p/parser {})) (def sample-item {:id 42 :name "Some Product" :description "This should be a cool product."}) (defn item-reader [{:keys [ast] :as env}] #?(:clj (Thread/sleep 1000)) (-> (p/swap-entity! env merge sample-item) (get (:key ast)))) (comment (time (parser {::p/entity (atom {}) ::p/reader {:id item-reader :name item-reader :description item-reader}} [:id :name :description])) ; since we are always hitting the expensive reader, each entry has to spend a second ; "Elapsed time: 3013.386195 msecs" ; => {:id 42, :name "Some Product", :description "This should be a cool product."} (time (parser {::p/entity (atom {}) ::p/reader [p/map-reader {:id item-reader :name item-reader :description item-reader}]} [:id :name :description])) ; now, adding the map-reader to the game will allow it to check on the entity first, ; making the cached entity effective. ;"Elapsed time: 1006.479409 msecs" ;=> {:id 42, :name "Some Product", :description "This should be a cool product."} )
116615
(ns com.wsscode.pathom.book.entities.atom-entities (:require [com.wsscode.pathom.core :as p])) (def parser (p/parser {})) (def sample-item {:id 42 :name "<NAME>" :description "This should be a cool product."}) (defn item-reader [{:keys [ast] :as env}] #?(:clj (Thread/sleep 1000)) (-> (p/swap-entity! env merge sample-item) (get (:key ast)))) (comment (time (parser {::p/entity (atom {}) ::p/reader {:id item-reader :name item-reader :description item-reader}} [:id :name :description])) ; since we are always hitting the expensive reader, each entry has to spend a second ; "Elapsed time: 3013.386195 msecs" ; => {:id 42, :name "<NAME>", :description "This should be a cool product."} (time (parser {::p/entity (atom {}) ::p/reader [p/map-reader {:id item-reader :name item-reader :description item-reader}]} [:id :name :description])) ; now, adding the map-reader to the game will allow it to check on the entity first, ; making the cached entity effective. ;"Elapsed time: 1006.479409 msecs" ;=> {:id 42, :name "<NAME>", :description "This should be a cool product."} )
true
(ns com.wsscode.pathom.book.entities.atom-entities (:require [com.wsscode.pathom.core :as p])) (def parser (p/parser {})) (def sample-item {:id 42 :name "PI:NAME:<NAME>END_PI" :description "This should be a cool product."}) (defn item-reader [{:keys [ast] :as env}] #?(:clj (Thread/sleep 1000)) (-> (p/swap-entity! env merge sample-item) (get (:key ast)))) (comment (time (parser {::p/entity (atom {}) ::p/reader {:id item-reader :name item-reader :description item-reader}} [:id :name :description])) ; since we are always hitting the expensive reader, each entry has to spend a second ; "Elapsed time: 3013.386195 msecs" ; => {:id 42, :name "PI:NAME:<NAME>END_PI", :description "This should be a cool product."} (time (parser {::p/entity (atom {}) ::p/reader [p/map-reader {:id item-reader :name item-reader :description item-reader}]} [:id :name :description])) ; now, adding the map-reader to the game will allow it to check on the entity first, ; making the cached entity effective. ;"Elapsed time: 1006.479409 msecs" ;=> {:id 42, :name "PI:NAME:<NAME>END_PI", :description "This should be a cool product."} )
[ { "context": "st/client_cert.edn\"))))\n(def client-key (gen-key 65537 (read-string (slurp \"test/client_key.edn\"))))\n", "end": 1556, "score": 0.5683966875076294, "start": 1555, "tag": "KEY", "value": "5" } ]
test/aleph/ssl.clj
arnaudgeiser/aleph
43
(ns aleph.ssl (:require [aleph.netty :as netty]) (:import [io.netty.handler.ssl SslContextBuilder ClientAuth] [java.io ByteArrayInputStream] [java.security KeyFactory PrivateKey] [java.security.cert CertificateFactory X509Certificate] [java.security.spec RSAPrivateCrtKeySpec] [org.apache.commons.codec.binary Base64])) (set! *warn-on-reflection* false) (defn gen-cert ^X509Certificate [^String pemstr] (.generateCertificate (CertificateFactory/getInstance "X.509") (ByteArrayInputStream. (Base64/decodeBase64 pemstr)))) (defn gen-key ^PrivateKey [public-exponent k] (let [k (zipmap (keys k) (->> k vals (map #(BigInteger. ^String % 16)))) spec (RSAPrivateCrtKeySpec. (:modulus k) (biginteger public-exponent) (:privateExponent k) (:prime1 k) (:prime2 k) (:exponent1 k) (:exponent2 k) (:coefficient k)) gen (KeyFactory/getInstance "RSA")] (.generatePrivate gen spec))) (def server-cert (gen-cert (read-string (slurp "test/server_cert.edn")))) (def server-key (gen-key 65537 (read-string (slurp "test/server_key.edn")))) (def ca-cert (gen-cert (read-string (slurp "test/ca_cert.edn")))) (def ca-key (gen-key 65537 (read-string (slurp "test/ca_key.edn")))) (def ^X509Certificate client-cert (gen-cert (read-string (slurp "test/client_cert.edn")))) (def client-key (gen-key 65537 (read-string (slurp "test/client_key.edn")))) (def server-ssl-context (-> (SslContextBuilder/forServer server-key (into-array X509Certificate [server-cert])) (.trustManager (into-array X509Certificate [ca-cert])) (.clientAuth ClientAuth/OPTIONAL) .build)) (def client-ssl-context (netty/ssl-client-context {:private-key client-key :certificate-chain (into-array X509Certificate [client-cert]) :trust-store (into-array X509Certificate [ca-cert])}))
46222
(ns aleph.ssl (:require [aleph.netty :as netty]) (:import [io.netty.handler.ssl SslContextBuilder ClientAuth] [java.io ByteArrayInputStream] [java.security KeyFactory PrivateKey] [java.security.cert CertificateFactory X509Certificate] [java.security.spec RSAPrivateCrtKeySpec] [org.apache.commons.codec.binary Base64])) (set! *warn-on-reflection* false) (defn gen-cert ^X509Certificate [^String pemstr] (.generateCertificate (CertificateFactory/getInstance "X.509") (ByteArrayInputStream. (Base64/decodeBase64 pemstr)))) (defn gen-key ^PrivateKey [public-exponent k] (let [k (zipmap (keys k) (->> k vals (map #(BigInteger. ^String % 16)))) spec (RSAPrivateCrtKeySpec. (:modulus k) (biginteger public-exponent) (:privateExponent k) (:prime1 k) (:prime2 k) (:exponent1 k) (:exponent2 k) (:coefficient k)) gen (KeyFactory/getInstance "RSA")] (.generatePrivate gen spec))) (def server-cert (gen-cert (read-string (slurp "test/server_cert.edn")))) (def server-key (gen-key 65537 (read-string (slurp "test/server_key.edn")))) (def ca-cert (gen-cert (read-string (slurp "test/ca_cert.edn")))) (def ca-key (gen-key 65537 (read-string (slurp "test/ca_key.edn")))) (def ^X509Certificate client-cert (gen-cert (read-string (slurp "test/client_cert.edn")))) (def client-key (gen-key 6<KEY>537 (read-string (slurp "test/client_key.edn")))) (def server-ssl-context (-> (SslContextBuilder/forServer server-key (into-array X509Certificate [server-cert])) (.trustManager (into-array X509Certificate [ca-cert])) (.clientAuth ClientAuth/OPTIONAL) .build)) (def client-ssl-context (netty/ssl-client-context {:private-key client-key :certificate-chain (into-array X509Certificate [client-cert]) :trust-store (into-array X509Certificate [ca-cert])}))
true
(ns aleph.ssl (:require [aleph.netty :as netty]) (:import [io.netty.handler.ssl SslContextBuilder ClientAuth] [java.io ByteArrayInputStream] [java.security KeyFactory PrivateKey] [java.security.cert CertificateFactory X509Certificate] [java.security.spec RSAPrivateCrtKeySpec] [org.apache.commons.codec.binary Base64])) (set! *warn-on-reflection* false) (defn gen-cert ^X509Certificate [^String pemstr] (.generateCertificate (CertificateFactory/getInstance "X.509") (ByteArrayInputStream. (Base64/decodeBase64 pemstr)))) (defn gen-key ^PrivateKey [public-exponent k] (let [k (zipmap (keys k) (->> k vals (map #(BigInteger. ^String % 16)))) spec (RSAPrivateCrtKeySpec. (:modulus k) (biginteger public-exponent) (:privateExponent k) (:prime1 k) (:prime2 k) (:exponent1 k) (:exponent2 k) (:coefficient k)) gen (KeyFactory/getInstance "RSA")] (.generatePrivate gen spec))) (def server-cert (gen-cert (read-string (slurp "test/server_cert.edn")))) (def server-key (gen-key 65537 (read-string (slurp "test/server_key.edn")))) (def ca-cert (gen-cert (read-string (slurp "test/ca_cert.edn")))) (def ca-key (gen-key 65537 (read-string (slurp "test/ca_key.edn")))) (def ^X509Certificate client-cert (gen-cert (read-string (slurp "test/client_cert.edn")))) (def client-key (gen-key 6PI:KEY:<KEY>END_PI537 (read-string (slurp "test/client_key.edn")))) (def server-ssl-context (-> (SslContextBuilder/forServer server-key (into-array X509Certificate [server-cert])) (.trustManager (into-array X509Certificate [ca-cert])) (.clientAuth ClientAuth/OPTIONAL) .build)) (def client-ssl-context (netty/ssl-client-context {:private-key client-key :certificate-chain (into-array X509Certificate [client-cert]) :trust-store (into-array X509Certificate [ca-cert])}))
[ { "context": "oc \"L-BFGS optimization for Clojure\"\n :author \"Antoine Choppin\"}\n bozo.core\n (:import [riso.numerical LBFGS])", "end": 75, "score": 0.9998669624328613, "start": 60, "tag": "NAME", "value": "Antoine Choppin" } ]
src/clojure/bozo/core.clj
japonophile/bozo
3
(ns ^{:doc "L-BFGS optimization for Clojure" :author "Antoine Choppin"} bozo.core (:import [riso.numerical LBFGS])) (def ^:private default-params {:maxit 200 :m 5 :eps 1.0e-5 :xtol 1.0e-16 :iprint [-1 0]}) (defn lbfgs " Finds a minimum of the function f, using the L-BFGS algorithm starting with an initial estimate x0. f is a function of x (double array) and must return: - the value of f at x - the derivatives of f wrt x at x The following parameters can be optionally specified: :maxit maximum number of iterations (default 200) :m number of corrections used in the BFGS update 3 <= m <= 7 is recommended (default 5) :eps accuracy with which the solution is to be found (default 1.0e-5) :xtol estimate of the machine precision (default 1.0e-16) :iprint pair [i1 i2] to specify the output generated by lbfgs (default [-1 0]) - i1 specifies the frequency of the output: -1 (silent), 0 (once) or > 0 - i2 specifies the type of output generated: 0, 1, 2 or 3 Override the defaults like this: (lbfgs f x0 {:m 3}) " [f ^doubles x0 & [params]] (let [x (aclone x0) n (count x) p (merge default-params params) maxit (:maxit p) m (:m p) eps (:eps p) xtol (:xtol p) iprint (int-array (:iprint p)) diagco false diag (double-array (repeat n 0.0)) iflag (int-array [0])] (loop [it 0] (let [[fval gval] (f x)] (LBFGS/lbfgs n m x fval gval diagco diag iprint eps xtol iflag) (if (and (not= 0 (nth iflag 0)) (< it maxit)) (recur (inc it)) x)))))
24232
(ns ^{:doc "L-BFGS optimization for Clojure" :author "<NAME>"} bozo.core (:import [riso.numerical LBFGS])) (def ^:private default-params {:maxit 200 :m 5 :eps 1.0e-5 :xtol 1.0e-16 :iprint [-1 0]}) (defn lbfgs " Finds a minimum of the function f, using the L-BFGS algorithm starting with an initial estimate x0. f is a function of x (double array) and must return: - the value of f at x - the derivatives of f wrt x at x The following parameters can be optionally specified: :maxit maximum number of iterations (default 200) :m number of corrections used in the BFGS update 3 <= m <= 7 is recommended (default 5) :eps accuracy with which the solution is to be found (default 1.0e-5) :xtol estimate of the machine precision (default 1.0e-16) :iprint pair [i1 i2] to specify the output generated by lbfgs (default [-1 0]) - i1 specifies the frequency of the output: -1 (silent), 0 (once) or > 0 - i2 specifies the type of output generated: 0, 1, 2 or 3 Override the defaults like this: (lbfgs f x0 {:m 3}) " [f ^doubles x0 & [params]] (let [x (aclone x0) n (count x) p (merge default-params params) maxit (:maxit p) m (:m p) eps (:eps p) xtol (:xtol p) iprint (int-array (:iprint p)) diagco false diag (double-array (repeat n 0.0)) iflag (int-array [0])] (loop [it 0] (let [[fval gval] (f x)] (LBFGS/lbfgs n m x fval gval diagco diag iprint eps xtol iflag) (if (and (not= 0 (nth iflag 0)) (< it maxit)) (recur (inc it)) x)))))
true
(ns ^{:doc "L-BFGS optimization for Clojure" :author "PI:NAME:<NAME>END_PI"} bozo.core (:import [riso.numerical LBFGS])) (def ^:private default-params {:maxit 200 :m 5 :eps 1.0e-5 :xtol 1.0e-16 :iprint [-1 0]}) (defn lbfgs " Finds a minimum of the function f, using the L-BFGS algorithm starting with an initial estimate x0. f is a function of x (double array) and must return: - the value of f at x - the derivatives of f wrt x at x The following parameters can be optionally specified: :maxit maximum number of iterations (default 200) :m number of corrections used in the BFGS update 3 <= m <= 7 is recommended (default 5) :eps accuracy with which the solution is to be found (default 1.0e-5) :xtol estimate of the machine precision (default 1.0e-16) :iprint pair [i1 i2] to specify the output generated by lbfgs (default [-1 0]) - i1 specifies the frequency of the output: -1 (silent), 0 (once) or > 0 - i2 specifies the type of output generated: 0, 1, 2 or 3 Override the defaults like this: (lbfgs f x0 {:m 3}) " [f ^doubles x0 & [params]] (let [x (aclone x0) n (count x) p (merge default-params params) maxit (:maxit p) m (:m p) eps (:eps p) xtol (:xtol p) iprint (int-array (:iprint p)) diagco false diag (double-array (repeat n 0.0)) iflag (int-array [0])] (loop [it 0] (let [[fval gval] (f x)] (LBFGS/lbfgs n m x fval gval diagco diag iprint eps xtol iflag) (if (and (not= 0 (nth iflag 0)) (< it maxit)) (recur (inc it)) x)))))
[ { "context": "ndler/site {:session {:store (cookie-store {:key \"TOP SECRET\"})}})\n (permacookie \"ring-session\")\n ", "end": 1389, "score": 0.5810694694519043, "start": 1383, "tag": "KEY", "value": "TOP SE" }, { "context": " [\"-i\" \"--ip\" \"IP to listen\" :default \"127.0.0.1\"]\n [\"-e\" \"--persona\" \"Persona callbac", "end": 1674, "score": 0.9996381402015686, "start": 1665, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
src/warmagnet/main.clj
wunderwaffle/warmagnet
9
(ns warmagnet.main (:gen-class) (:require [clojure.tools.cli :refer [cli]] [org.httpkit.server :as hk] [ring.middleware.reload :as reload] [ring.middleware.session.cookie :refer [cookie-store]] [ring.util.response :refer [resource-response]] [compojure.core :refer [defroutes GET POST]] [compojure.handler :as handler] [compojure.route :as route] [taoensso.timbre :refer [info]] [warmagnet.permacookie :refer [permacookie]] [warmagnet.config :refer [config]] [warmagnet.utils :refer [wrap-logging]] [warmagnet.app :refer [ws-handler]])) (defroutes app-routes (GET "/" [] (resource-response "index.html")) (GET "/ws" [] ws-handler) ;; (GET "/games" [] (file-response "resources/games.html")) ;; (GET "/games/new" [] (file-response "resources/new_game.html")) ;; (GET "/games/placeholder" [] (file-response "resources/game_mockup.html")) ;; (GET "/leaderboard" [] (file-response "resources/leaderboard.html")) (route/resources "/static" { :root "static"}) (route/not-found "404 Nothing to see here, move along")) (def app (-> #'app-routes (handler/site {:session {:store (cookie-store {:key "TOP SECRET"})}}) (permacookie "ring-session") (wrap-logging))) (defn -main [& args] (let [[opts args help] (cli args ["-p" "--port" "Listen on this port" :default 3000 :parse-fn #(Integer. %)] ["-i" "--ip" "IP to listen" :default "127.0.0.1"] ["-e" "--persona" "Persona callback" :default "http://localhost:3000"] ["-d" "--dev" "Development mode (auto-reload)" :flag true]) app (if (:dev opts) (reload/wrap-reload app) app)] (info (if (:dev opts) "Development mode" "Production mode")) (info "Starting to listen on " (:port opts)) (if (:persona opts) (swap! config assoc :persona-callback (:persona opts))) (info "Persona callback" (:persona-callback @config)) (hk/run-server app (select-keys opts [:port :ip])))) (defn run [& opts] (apply -main (or (seq opts) ["-d"])))
28472
(ns warmagnet.main (:gen-class) (:require [clojure.tools.cli :refer [cli]] [org.httpkit.server :as hk] [ring.middleware.reload :as reload] [ring.middleware.session.cookie :refer [cookie-store]] [ring.util.response :refer [resource-response]] [compojure.core :refer [defroutes GET POST]] [compojure.handler :as handler] [compojure.route :as route] [taoensso.timbre :refer [info]] [warmagnet.permacookie :refer [permacookie]] [warmagnet.config :refer [config]] [warmagnet.utils :refer [wrap-logging]] [warmagnet.app :refer [ws-handler]])) (defroutes app-routes (GET "/" [] (resource-response "index.html")) (GET "/ws" [] ws-handler) ;; (GET "/games" [] (file-response "resources/games.html")) ;; (GET "/games/new" [] (file-response "resources/new_game.html")) ;; (GET "/games/placeholder" [] (file-response "resources/game_mockup.html")) ;; (GET "/leaderboard" [] (file-response "resources/leaderboard.html")) (route/resources "/static" { :root "static"}) (route/not-found "404 Nothing to see here, move along")) (def app (-> #'app-routes (handler/site {:session {:store (cookie-store {:key "<KEY>CRET"})}}) (permacookie "ring-session") (wrap-logging))) (defn -main [& args] (let [[opts args help] (cli args ["-p" "--port" "Listen on this port" :default 3000 :parse-fn #(Integer. %)] ["-i" "--ip" "IP to listen" :default "127.0.0.1"] ["-e" "--persona" "Persona callback" :default "http://localhost:3000"] ["-d" "--dev" "Development mode (auto-reload)" :flag true]) app (if (:dev opts) (reload/wrap-reload app) app)] (info (if (:dev opts) "Development mode" "Production mode")) (info "Starting to listen on " (:port opts)) (if (:persona opts) (swap! config assoc :persona-callback (:persona opts))) (info "Persona callback" (:persona-callback @config)) (hk/run-server app (select-keys opts [:port :ip])))) (defn run [& opts] (apply -main (or (seq opts) ["-d"])))
true
(ns warmagnet.main (:gen-class) (:require [clojure.tools.cli :refer [cli]] [org.httpkit.server :as hk] [ring.middleware.reload :as reload] [ring.middleware.session.cookie :refer [cookie-store]] [ring.util.response :refer [resource-response]] [compojure.core :refer [defroutes GET POST]] [compojure.handler :as handler] [compojure.route :as route] [taoensso.timbre :refer [info]] [warmagnet.permacookie :refer [permacookie]] [warmagnet.config :refer [config]] [warmagnet.utils :refer [wrap-logging]] [warmagnet.app :refer [ws-handler]])) (defroutes app-routes (GET "/" [] (resource-response "index.html")) (GET "/ws" [] ws-handler) ;; (GET "/games" [] (file-response "resources/games.html")) ;; (GET "/games/new" [] (file-response "resources/new_game.html")) ;; (GET "/games/placeholder" [] (file-response "resources/game_mockup.html")) ;; (GET "/leaderboard" [] (file-response "resources/leaderboard.html")) (route/resources "/static" { :root "static"}) (route/not-found "404 Nothing to see here, move along")) (def app (-> #'app-routes (handler/site {:session {:store (cookie-store {:key "PI:KEY:<KEY>END_PICRET"})}}) (permacookie "ring-session") (wrap-logging))) (defn -main [& args] (let [[opts args help] (cli args ["-p" "--port" "Listen on this port" :default 3000 :parse-fn #(Integer. %)] ["-i" "--ip" "IP to listen" :default "127.0.0.1"] ["-e" "--persona" "Persona callback" :default "http://localhost:3000"] ["-d" "--dev" "Development mode (auto-reload)" :flag true]) app (if (:dev opts) (reload/wrap-reload app) app)] (info (if (:dev opts) "Development mode" "Production mode")) (info "Starting to listen on " (:port opts)) (if (:persona opts) (swap! config assoc :persona-callback (:persona opts))) (info "Persona callback" (:persona-callback @config)) (hk/run-server app (select-keys opts [:port :ip])))) (defn run [& opts] (apply -main (or (seq opts) ["-d"])))
[ { "context": "\n :labels {:user \"test-user\"}\n :mem 1536}]}]\n", "end": 1605, "score": 0.9995334148406982, "start": 1596, "tag": "USERNAME", "value": "test-user" }, { "context": "l \"http://cook.localtest.me\"\n run-as-user \"test-user\"\n job-uuids [\"uuid-1\" \"uuid-2\" \"uuid-3\"]]\n", "end": 3620, "score": 0.9473373293876648, "start": 3611, "tag": "USERNAME", "value": "test-user" }, { "context": " :url cook-url}\n test-user \"test-user\"\n current-time (t/now)\n service-id ", "end": 5775, "score": 0.9995893836021423, "start": 5766, "tag": "USERNAME", "value": "test-user" }, { "context": " :state states\n :user test-user}]\n (with-redefs [http-utils/http-request", "end": 7506, "score": 0.999023973941803, "start": 7497, "tag": "USERNAME", "value": "test-user" }, { "context": " :state states\n :user test-user}]\n (with-redefs [http-utils/http-request", "end": 8126, "score": 0.9992567896842957, "start": 8117, "tag": "USERNAME", "value": "test-user" }, { "context": " :state states\n :user test-user}]\n (with-redefs [http-utils/http-request", "end": 8793, "score": 0.9991922974586487, "start": 8784, "tag": "USERNAME", "value": "test-user" }, { "context": " :state states\n :user test-user}]\n (with-redefs [http-utils/http-request", "end": 9482, "score": 0.9983987808227539, "start": 9473, "tag": "USERNAME", "value": "test-user" }, { "context": " :state states\n :user test-user}]\n (with-redefs [http-utils/http-request", "end": 10119, "score": 0.9985377192497253, "start": 10110, "tag": "USERNAME", "value": "test-user" }, { "context": "st-user\"\n \"LOGNAME\" \"test-user\"\n \"USER\" \"test-", "end": 14731, "score": 0.8297956585884094, "start": 14727, "tag": "USERNAME", "value": "test" }, { "context": "er\"\n \"LOGNAME\" \"test-user\"\n \"USER\" \"test-user\"", "end": 14736, "score": 0.663681149482727, "start": 14732, "tag": "USERNAME", "value": "user" }, { "context": "\"test-user\"\n \"USER\" \"test-user\"\n \"WAITER_CLUSTER\" \"", "end": 14785, "score": 0.9870265126228333, "start": 14776, "tag": "USERNAME", "value": "test-user" }, { "context": "\n \"WAITER_PASSWORD\" \"test-service-1-password\"\n \"WAITER_SERVICE_ID", "end": 15083, "score": 0.9993148446083069, "start": 15060, "tag": "PASSWORD", "value": "test-service-1-password" }, { "context": "\n \"WAITER_USERNAME\" \"waiter\"}\n :executor \"cook\"\n ", "end": 15207, "score": 0.9996567964553833, "start": 15201, "tag": "USERNAME", "value": "waiter" }, { "context": " \"waiter\"\n :user \"test-user\"}\n :max-retries 1\n ", "end": 15534, "score": 0.9993954300880432, "start": 15525, "tag": "USERNAME", "value": "test-user" }, { "context": "\n service-id->password-fn (constantly \"password\")\n home-path-prefix \"/home/path/\"\n ", "end": 19751, "score": 0.988092303276062, "start": 19743, "tag": "PASSWORD", "value": "password" }, { "context": " service-id \"test-service-id\"\n test-user \"test-user\"]\n (with-redefs [get-jobs (fn [_ user states &", "end": 20465, "score": 0.998472273349762, "start": 20456, "tag": "USERNAME", "value": "test-user" }, { "context": "service-id\"\n :user \"test-user\"}\n :name \"job-name\"\n ", "end": 22538, "score": 0.9996094703674316, "start": 22529, "tag": "USERNAME", "value": "test-user" }, { "context": " :user \"test-user\"}\n :name \"job-name\"\n :priority 75\n ", "end": 22578, "score": 0.8938911557197571, "start": 22570, "tag": "USERNAME", "value": "job-name" }, { "context": " :host (str \"10.141.141.\" instance-id)\n ", "end": 24918, "score": 0.9928032755851746, "start": 24909, "tag": "IP_ADDRESS", "value": "0.141.141" }, { "context": "orities [60 55 50 45 40]\n :allowed-users #{\"test-user\"}\n :cook-api {}\n :home-path-prefix \"/", "end": 34939, "score": 0.9983627796173096, "start": 34930, "tag": "USERNAME", "value": "test-user" }, { "context": " (atom {})\n :service-id->password-fn #(str % \".password\")\n :service-id->service-description-fn (con", "end": 35250, "score": 0.7947536706924438, "start": 35240, "tag": "PASSWORD", "value": "\".password" }, { "context": "nce\n (let [cook-api (Object.)\n test-user \"test-user\"\n cook-scheduler (create-cook-scheduler-he", "end": 39938, "score": 0.9992832541465759, "start": 39929, "tag": "USERNAME", "value": "test-user" }, { "context": "eduler\"\n (let [valid-config {:allowed-users #{\"test-user\"}\n :authorizer {:kind :def", "end": 49652, "score": 0.9400908350944519, "start": 49643, "tag": "USERNAME", "value": "test-user" }, { "context": " :service-id->password-fn #(str % \".password\")\n :service-id->service-de", "end": 50269, "score": 0.9397212266921997, "start": 50259, "tag": "PASSWORD", "value": "\".password" } ]
waiter/test/waiter/scheduler/cook_test.clj
twosigmajab/waiter
0
;; ;; 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 waiter.scheduler.cook-test (:require [clj-time.coerce :as tc] [clj-time.core :as t] [clojure.string :as str] [clojure.test :refer :all] [waiter.config :as config] [waiter.scheduler.cook :refer :all] [waiter.mesos.mesos :as mesos] [waiter.scheduler :as scheduler] [waiter.util.date-utils :as du] [waiter.util.http-utils :as http-utils] [waiter.util.utils :as utils]) (:import (clojure.lang ExceptionInfo) (java.util UUID) (waiter.scheduler.cook CookScheduler))) (deftest test-post-jobs (let [http-client (Object.) cook-url "http://cook.localtest.me" job-description {:jobs [{:application {:name "test-service" :version "123456"} :command "test-command" :cpus 1 :labels {:user "test-user"} :mem 1536}]}] (testing "impersonation disabled" (let [cook-api {:http-client http-client :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/jobs") in-request-url)) (is (= {:accept "application/json" :body (utils/clj->json job-description) :content-type "application/json" :headers {} :request-method :post :spnego-auth "test-spnego-auth"} options)))] (post-jobs cook-api job-description)))) (testing "impersonation enabled" (let [cook-api {:http-client http-client :impersonate true :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/jobs") in-request-url)) (is (= {:accept "application/json" :body (utils/clj->json job-description) :content-type "application/json" :headers {"x-cook-impersonate" "test-user"} :request-method :post :spnego-auth "test-spnego-auth"} options)))] (post-jobs cook-api job-description)))))) (deftest test-delete-jobs (let [http-client (Object.) cook-url "http://cook.localtest.me" run-as-user "test-user" job-uuids ["uuid-1" "uuid-2" "uuid-3"]] (testing "impersonation disabled" (let [cook-api {:http-client http-client :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/rawscheduler") in-request-url)) (is (= {:accept "application/json" :content-type "application/json" :headers {} :query-string {:job job-uuids} :request-method :delete :spnego-auth "test-spnego-auth"} options)))] (delete-jobs cook-api run-as-user job-uuids)))) (testing "impersonation enabled" (let [cook-api {:http-client http-client :impersonate true :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/rawscheduler") in-request-url)) (is (= {:accept "application/json" :content-type "application/json" :headers {"x-cook-impersonate" "test-user"} :query-string {:job job-uuids} :request-method :delete :spnego-auth "test-spnego-auth"} options)))] (delete-jobs cook-api run-as-user job-uuids)))))) (deftest test-get-jobs (let [http-client (Object.) cook-url "http://cook.localtest.me" cook-api {:http-client http-client :spnego-auth "test-spnego-auth" :url cook-url} test-user "test-user" current-time (t/now) service-id "test-service-id" cook-job-1 {:application {:name "test-job" :version "123456"} :labels {:user test-user}} cook-job-2 {:application {:name "test-service-1" :version "123456"} :labels {:source "waiter" :user test-user}} cook-job-3 {:application {:name "test-service-3" :version "238723"} :labels {:source "waiter" :user test-user}} http-request-fn-factory (fn [expected-query-string] (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/jobs") in-request-url)) (is (= {:accept "application/json" :content-type "application/json" :query-string expected-query-string :request-method :get :spnego-auth "test-spnego-auth"} options)) [cook-job-1 cook-job-2 cook-job-3]))] (with-redefs [t/now (constantly current-time)] (testing "no optional arguments" (let [end-time current-time search-interval (t/days 7) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states)))))) (testing "only search interval argument" (let [end-time current-time search-interval (t/days 4) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :search-interval search-interval)))))) (testing "only end-time argument" (let [end-time (t/minus current-time (t/days 1)) search-interval (t/days 7) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :end-time end-time)))))) (testing "only service-id argument" (let [end-time current-time search-interval (t/days 7) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :name (str service-id "*") :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :service-id service-id)))))) (testing "all arguments" (let [end-time current-time search-interval (t/days 2) start-time (t/minus end-time search-interval) states ["running" "waiting"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :end-time end-time :start-time start-time))))))))) (deftest test-job-healthy? (with-redefs [http-utils/http-request (fn [_ in-health-check-url] (is (str/starts-with? in-health-check-url "http://www.hostname.com:1234/")) (when-not (str/includes? in-health-check-url "unhealthy") in-health-check-url))] (is (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [1234] :status "running" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/healthy"}})) (is (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [4567] :status "running" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-port "1234" :backend-proto "http" :health-check-url "/healthy"}})) (is (not (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [1234] :status "running" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/unhealthy"}}))) (is (not (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [1234] :status "failed" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/healthy"}}))) (is (not (job-healthy? {:status "completed" :instances [{:hostname "www.hostname.com" :ports [1234] :status "success" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/healthy"}}))))) (deftest test-create-job-description (with-redefs [config/retrieve-cluster-name (constantly "test-cluster")] (let [service-id->password-fn (fn [service-id] (str service-id "-password")) home-path-prefix "/home/path/" service-id "test-service-1" service-description {"backend-proto" "http" "cmd" "test-command" "concurrency-level" 1 "cpus" 1 "mem" 1536 "run-as-user" "test-user" "ports" 2 "restart-backoff-factor" 2 "grace-period-secs" 111 "health-check-interval-secs" 10 "health-check-max-consecutive-failures" 5 "health-check-port-index" 0 "health-check-url" "/health-check" "instance-expiry-mins" 3600 "env" {"FOO" "bar" "BAZ" "quux"} "name" "test-service" "version" "123456"} instance-priority 75 expected-job {:application {:name "test-service" :version "123456"} :command "test-command" :cpus 1 :disable-mea-culpa-retries true :env {"BAZ" "quux" "FOO" "bar" "HOME" "/home/path/test-user" "LOGNAME" "test-user" "USER" "test-user" "WAITER_CLUSTER" "test-cluster" "WAITER_CONCURRENCY_LEVEL" "1" "WAITER_CPUS" "1" "WAITER_MEM_MB" "1536" "WAITER_PASSWORD" "test-service-1-password" "WAITER_SERVICE_ID" "test-service-1" "WAITER_USERNAME" "waiter"} :executor "cook" :labels {:backend-proto "http" :health-check-url "/health-check" :service-id "test-service-1" :source "waiter" :user "test-user"} :max-retries 1 :max-runtime 216300000 :mem 1536 :ports 2 :priority 75}] (testing "basic-test-with-defaults" (let [backend-port nil actual (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port) job-uuid (-> actual :jobs first :uuid) expected {:jobs [(assoc expected-job :name (str "test-service-1." job-uuid) :uuid job-uuid)]}] (is (= expected actual)))) (testing "basic-test-custom-port" (let [service-description service-description backend-port 4567 actual (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port) job-uuid (-> actual :jobs first :uuid) expected {:jobs [(-> expected-job (assoc :name (str "test-service-1." job-uuid) :uuid job-uuid) (update :labels assoc :backend-port "4567"))]}] (is (= expected actual)))) (testing "basic-test-with-docker-image" (let [service-description (assoc service-description "cmd-type" "docker" "version" "foo/bar:baz") backend-port nil actual (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port) job-uuid (-> actual :jobs first :uuid) expected {:jobs [(assoc expected-job :application {:name "test-service" :version "baz"} :container {:docker {:force-pull-image false :image "namespace:foo,name:bar,label:baz" :network "HOST"} :type "docker"} :name (str "test-service-1." job-uuid) :uuid job-uuid)]}] (is (= expected actual))) (is (thrown-with-msg? ExceptionInfo #"to use container support format version as namespace/name:label" (let [service-description (assoc service-description "cmd-type" "docker" "version" "foo/bar-baz") backend-port nil] (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port)))))))) (deftest test-determine-instance-priority (let [allowed-priorities [75 70 65 60 55]] (is (= 75 (determine-instance-priority allowed-priorities #{}))) (is (= 70 (determine-instance-priority allowed-priorities #{75}))) (is (= 65 (determine-instance-priority allowed-priorities #{75 70}))) (is (= 70 (determine-instance-priority allowed-priorities #{75 65}))) (is (= 60 (determine-instance-priority allowed-priorities #{75 70 65 55}))) (is (= 55 (determine-instance-priority allowed-priorities #{75 70 65 60}))) (is (= 55 (determine-instance-priority allowed-priorities #{75 70 65 60 55}))))) (deftest test-launch-jobs (let [posted-jobs-atom (atom [])] (with-redefs [create-job-description (fn [service-id _ _ _ instance-priority _] {:priority instance-priority :service-id service-id}) post-jobs (fn [_ job] (swap! posted-jobs-atom conj job))] (let [cook-api (Object.) service-id "test-service-id" service-description {} service-id->password-fn (constantly "password") home-path-prefix "/home/path/" num-instances 3 allowed-priorities [75 70 65 60 55] reserved-priorities #{75 65} backend-port nil] (launch-jobs cook-api service-id service-description service-id->password-fn home-path-prefix num-instances allowed-priorities reserved-priorities backend-port) (is (= [{:priority 70 :service-id service-id} {:priority 60 :service-id service-id} {:priority 55 :service-id service-id}] @posted-jobs-atom)))))) (deftest test-retrieve-jobs (let [search-interval (t/days 1) service-id "test-service-id" test-user "test-user"] (with-redefs [get-jobs (fn [_ user states & {:as options}] (is (= test-user user)) (is (= ["running" "waiting"] states)) (is (= {:search-interval search-interval :service-id service-id} options)) [])] (retrieve-jobs (Object.) search-interval service-id {"run-as-user" test-user})))) (deftest test-job->service-instance (with-redefs [job-healthy? (constantly true)] (let [job-uuid (str (UUID/randomUUID)) start-time (System/currentTimeMillis) expected-instance {:cook/job-name "job-name" :cook/job-uuid job-uuid :cook/priority 75 :cook/task-id "task-id" :exit-code 0 :extra-ports [5678 7890] :flags #{} :health-check-status nil :healthy? true :host "hostname.localtest.me" :id "job-name_test-user_task-id" :log-directory "/sandbox/directory" :message "test reason" :port 1234 :service-id "service-id" :started-at (tc/from-long start-time)} actual-job {:instances [{:exit_code 0 :hostname "hostname.localtest.me" :ports [1234 5678 7890] :reason_string "test reason" :sandbox_directory "/sandbox/directory" :start_time start-time :task_id "task-id"}] :labels {:backend-proto "http" :health-check-port-index 1 :service-id "service-id" :user "test-user"} :name "job-name" :priority 75 :status "running" :uuid job-uuid}] (testing "basic job" (is (= (scheduler/make-ServiceInstance expected-instance) (job->service-instance actual-job)))) (testing "job with custom port" (let [expected-instance (assoc expected-instance :extra-ports [1234 5678 7890] :port 4321) actual-job (update actual-job :labels assoc :backend-port "4321")] (is (= (scheduler/make-ServiceInstance expected-instance) (job->service-instance actual-job)))))))) (deftest test-jobs->service (with-redefs [job-healthy? #(str/includes? (:name %) "healthy-")] (let [suffix (System/nanoTime) jobs [{:labels {:service-id "test-service-id"} :name (str "healthy-1." suffix) :status "running"} {:labels {:service-id "test-service-id"} :name (str "healthy-2." suffix) :status "running"} {:labels {:service-id "test-service-id"} :name (str "unhealthy." suffix) :status "running"} {:labels {:service-id "test-service-id"} :name (str "staging-1." suffix) :status "staging"}]] (is (= (scheduler/make-Service {:id "test-service-id" :instances 4 :task-count 4 :task-stats {:healthy 2 :running 3 :staged 1 :unhealthy 1}}) (jobs->service jobs)))))) (defn- parse-and-store-failed-instance! "Parses the failed instance response and adds it to the known set of failed instances." [service-id->failed-instances-transient-store service-id failed-instance] (when failed-instance (let [max-instances-to-keep 10] (scheduler/add-instance-to-buffered-collection! service-id->failed-instances-transient-store max-instances-to-keep service-id failed-instance (fn [] #{}) (fn [instances] (-> (scheduler/sort-instances instances) (rest) (set))))))) (deftest test-service-id->failed-instances-transient-store (let [health-check-url "/status" failed-instance-response-fn (fn [service-id instance-id] {:health-check-path health-check-url :host (str "10.141.141." instance-id) :id (str service-id "." instance-id) :message "Abnormal executor termination" :port 0 :service-id service-id :started-at (du/str-to-date "2014-09-12T23:23:41.711Z") :version "2014-09-12T23:28:21.737Z"}) service-id-1 "test-service-id-failed-instances-1" service-id-2 "test-service-id-failed-instances-2" service-id->failed-instances-transient-store (atom {})] (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store []) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 1 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 1 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "B") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "B") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "C") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "D") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 4 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store []) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 1 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "B") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "C") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "D") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "E") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "F") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "G") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "H") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "I") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 9 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-2)))) (->> (failed-instance-response-fn service-id-2 "X") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-2)) (->> (failed-instance-response-fn service-id-2 "Y") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-2)) (->> (failed-instance-response-fn service-id-2 "Z") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-2)) (remove-failed-instances-for-service! service-id->failed-instances-transient-store service-id-1) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-2)))) (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store [service-id-2]) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-2)))))) (deftest test-max-failed-instances-cache (let [current-time (t/now) current-time-str (du/date-to-str current-time) service-id->failed-instances-transient-store (atom {}) make-instance (fn [n] {:id (str "service-1." n) :service-id "service-1" :started-at (du/str-to-date current-time-str) :healthy? false :port 0})] (testing "test-max-failed-instances-cache" (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store []) (doseq [n (range 10 50)] (parse-and-store-failed-instance! service-id->failed-instances-transient-store "service-1" (make-instance n))) (let [actual-failed-instances (set (service-id->failed-instances service-id->failed-instances-transient-store "service-1"))] (is (= 10 (count actual-failed-instances))) (doseq [n (range 40 50)] (is (contains? actual-failed-instances (make-instance n)) (str "Failed instances does not contain instance service-1." n))))))) (deftest test-retrieve-log-url (let [host "agent-1.com" mesos-api (Object.)] (with-redefs [mesos/get-agent-state (fn [in-mesos-api in-host] (is (= mesos-api in-mesos-api)) (is (= host in-host)) {:frameworks [{:completed_executors [{:directory "/path/to/instance1/directory" :id "service-id-1.instance-id-1"}] :executors [{:directory "/path/to/instance2/directory" :id "service-id-1.instance-id-2"}] :role "cook"} {:completed_executors [{:directory "/marathon/instance1/directory" :id "service-id-1.instance-id-1"}] :executors [{:directory "/marathon/instance2/directory" :id "service-id-1.instance-id-2"}] :name "marathon"} {:completed_executors [{:directory "/path/to/instance3/directory" :id "service-id-1.instance-id-3"}] :executors [{:directory "/path/to/instance4/directory" :id "service-id-1.instance-id-4"}] :name "Cook-1.17.4" :role "*"}]})] (is (= "/path/to/instance1/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-1" host "cook"))) (is (= "/path/to/instance2/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-2" host "cook"))) (is (= "/path/to/instance3/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-3" host "cook"))) (is (= "/path/to/instance4/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-4" host "cook")))))) (defn create-cook-scheduler-helper [& {:as cook-config}] (-> {:allowed-priorities [60 55 50 45 40] :allowed-users #{"test-user"} :cook-api {} :home-path-prefix "/home/path/" :search-interval (t/minutes 10) ;; context :retrieve-syncer-state-fn (constantly {}) :scheduler-name "cook" :service-id->failed-instances-transient-store (atom {}) :service-id->password-fn #(str % ".password") :service-id->service-description-fn (constantly {})} (merge cook-config) map->CookScheduler)) (deftest test-get-services->instances (let [{:keys [allowed-users cook-api search-interval service-id->failed-instances-transient-store] :as scheduler} (create-cook-scheduler-helper) suffix (System/nanoTime) jobs [{:labels {:service-id "S1"} :name (str "healthy-S1.1." suffix) :status "running"} {:labels {:service-id "S1"} :name (str "healthy-S1.2." suffix) :status "running"} {:labels {:service-id "S1"} :name (str "unhealthy-S1." suffix) :status "running"} {:labels {:service-id "S1"} :name (str "staging-S1.1." suffix) :status "staging"} {:labels {:service-id "S2"} :name (str "healthy-S2.1." suffix) :status "running"} {:labels {:service-id "S2"} :name (str "staging-S2.1." suffix) :status "staging"}]] (with-redefs [job-healthy? #(str/includes? (:name %) "healthy-") get-jobs (fn [cook-api _ states & {:keys [search-interval]}] (is (= (:cook-api scheduler) cook-api)) (is (= ["running" "waiting"] states)) (is (= (:search-interval scheduler) search-interval)) jobs) job->service-instance (fn [{:keys [name]}] {:id name})] (scheduler/add-instance-to-buffered-collection! service-id->failed-instances-transient-store 1 "S2" {:id (str "failed-S2.1." suffix) :service-id "S2"} (fn [] #{}) (fn [instances] (-> (scheduler/sort-instances instances) (rest) (set)))) (try (let [service-1 (scheduler/make-Service {:id "S1" :instances 4 :task-count 4 :task-stats {:healthy 3 :running 3 :staged 1 :unhealthy 0}}) service-1-instances {:active-instances [{:id (str "healthy-S1.1." suffix)} {:id (str "healthy-S1.2." suffix)} {:id (str "unhealthy-S1." suffix)} {:id (str "staging-S1.1." suffix)}] :failed-instances []} service-2 (scheduler/make-Service {:id "S2" :instances 2 :task-count 2 :task-stats {:healthy 1 :running 1 :staged 1 :unhealthy 0}}) service-2-instances {:active-instances [{:id (str "healthy-S2.1." suffix)} {:id (str "staging-S2.1." suffix)}] :failed-instances (service-id->failed-instances service-id->failed-instances-transient-store "S2")}] (is (seq (service-id->failed-instances service-id->failed-instances-transient-store "S2"))) (is (= {service-1 service-1-instances, service-2 service-2-instances} (get-service->instances cook-api allowed-users search-interval service-id->failed-instances-transient-store)))) (finally (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store [])))))) (deftest test-kill-instance (let [scheduler (create-cook-scheduler-helper) service-id "foo" test-instance {:cook/job-uuid "uuid-1" :id "foo.1A" :service-id service-id} current-time (t/now)] (with-redefs [retrieve-jobs (constantly [{:uuid "uuid-1"} {:uuid "uuid-2"} {:uuid "uuid-3"}]) t/now (constantly current-time)] (with-redefs [delete-jobs (constantly {:deploymentId 12345})] (is (= {:killed? true :message "Killed foo.1A" :result :killed :success true} (scheduler/kill-instance scheduler test-instance)))) (with-redefs [delete-jobs (constantly {})] (is (= {:killed? true :message "Killed foo.1A" :result :killed :success true} (scheduler/kill-instance scheduler test-instance)))) (with-redefs [delete-jobs (fn [_ _] (throw (ex-info "Delete error" {:status 400})))] (is (= {:killed? false :message "Unable to kill foo.1A" :result :failed :success false} (scheduler/kill-instance scheduler test-instance)))) (with-redefs [delete-jobs (constantly {}) retrieve-jobs (constantly nil)] (is (= {:message "foo does not exist!" :result :no-such-service-exists :success false} (scheduler/kill-instance scheduler test-instance))))))) (deftest test-create-instance (let [cook-api (Object.) test-user "test-user" cook-scheduler (create-cook-scheduler-helper :allowed-users #{test-user} :cook-api cook-api) service-id "foo" min-instances 4 descriptor {:service-description {"min-instances" min-instances "run-as-user" test-user} :service-id service-id}] (testing "create service - success" (let [updated-invoked-promise (promise)] (with-redefs [scheduler/service-exists? (constantly false) launch-jobs (fn [in-cook-api in-service-id _ _ _ num-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= min-instances num-instances)) true)] (is (= {:message "Created foo" :result :created :success true} (scheduler/create-service-if-new cook-scheduler descriptor))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "create service - failure" (let [updated-invoked-promise (promise)] (with-redefs [scheduler/service-exists? (constantly false) launch-jobs (fn [in-cook-api in-service-id _ _ _ num-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= min-instances num-instances)) (throw (ex-info "Failed" {})))] (is (= {:message "Unable to create foo" :result :failed :success false} (scheduler/create-service-if-new cook-scheduler descriptor))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "create service - service exists" (with-redefs [retrieve-jobs (fn [_ _ in-service-id & _] (= service-id in-service-id))] (is (scheduler/service-exists? cook-scheduler service-id)) (is (= {:message "foo already exists!" :result :already-exists :success false} (scheduler/create-service-if-new cook-scheduler descriptor))))))) (deftest test-delete-service (with-redefs [retrieve-jobs (constantly [{:uuid "uuid-1"} {:uuid "uuid-2"} {:uuid "uuid-3"}])] (let [scheduler (create-cook-scheduler-helper)] (with-redefs [delete-jobs (constantly {:deploymentId 12345})] (is (= {:message "Deleted foo" :result :deleted :success true} (scheduler/delete-service scheduler "foo")))) (with-redefs [delete-jobs (constantly {})] (is (= {:message "Deleted foo" :result :deleted :success true} (scheduler/delete-service scheduler "foo")))) (with-redefs [delete-jobs (fn [_ _] (throw (ex-info "Delete error" {:status 400})))] (is (= {:message "Unable to delete foo" :result :failed :success false} (scheduler/delete-service scheduler "foo")))) (with-redefs [delete-jobs (constantly {}) retrieve-jobs (constantly nil)] (is (= {:message "foo does not exist!" :result :no-such-service-exists :success false} (scheduler/delete-service scheduler "foo"))))))) (deftest test-scale-service (let [cook-api (Object.) cook-scheduler (create-cook-scheduler-helper :cook-api cook-api) service-id "test-service-id"] (testing "scale of service - no such service" (let [updated-invoked-promise (promise) instances 5] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) nil) launch-jobs (fn [in-cook-api in-service-id & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) true)] (is (= {:message "test-service-id does not exist!" :result :no-such-service-exists :success false} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :not-invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "scale of service - no-op" (let [updated-invoked-promise (promise) instances 5] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (for [n (range 10)] {:cook/job-uuid (str "uuid-" n) :id (str service-id "." n) :priority n :service-id service-id})) launch-jobs (fn [in-cook-api in-service-id _ _ _ extra-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= 20 extra-instances)) true)] (is (= {:message "Scaled test-service-id" :result :scaling-not-needed :success true} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :not-invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "scale of service - success" (let [updated-invoked-promise (promise) instances 30] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (for [n (range 10)] {:cook/job-uuid (str "uuid-" n) :id (str service-id "." n) :priority n :service-id service-id})) launch-jobs (fn [in-cook-api in-service-id _ _ _ extra-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= 20 extra-instances)) true)] (is (= {:message "Scaled test-service-id" :result :scaled :success true} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "scale of service - fail" (let [updated-invoked-promise (promise) instances 30] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (for [n (range 10)] {:cook/job-uuid (str "uuid-" n) :id (str service-id "." n) :priority n :service-id service-id})) launch-jobs (fn [in-cook-api in-service-id _ _ _ extra-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= 20 extra-instances)) (throw (ex-info "Launch failed!" {})))] (is (= {:message "Unable to scale test-service-id" :result :failed :success false} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))))) (deftest test-service-id->state (let [service-id "service-id" syncer-state-atom (atom {:last-update-time :time :service-id->health-check-context {}}) retrieve-syncer-state-fn (partial scheduler/retrieve-syncer-state @syncer-state-atom) cook-scheduler (create-cook-scheduler-helper :retrieve-syncer-state-fn retrieve-syncer-state-fn :service-id->failed-instances-transient-store (atom {service-id [:failed-instances]}))] (is (= {:failed-instances [:failed-instances] :syncer {:last-update-time :time}} (scheduler/service-id->state cook-scheduler service-id))) (is (= {:authorizer nil :service-id->failed-instances-transient-store {"service-id" [:failed-instances]} :syncer {:last-update-time :time :service-id->health-check-context {}}} (scheduler/state cook-scheduler))))) (deftest test-cook-scheduler (testing "Creating a CookScheduler" (let [valid-config {:allowed-users #{"test-user"} :authorizer {:kind :default :default {:factory-fn 'waiter.authorization/noop-authorizer}} :backend-port 7890 :cook-api {} :home-path-prefix "/home/path/" :instance-priorities {:delta 5 :max 70 :min 30} :search-interval-days 10 :scheduler-name "cook" :service-id->password-fn #(str % ".password") :service-id->service-description-fn (constantly {})} cook-api (Object.) service-id->failed-instances-transient-store (atom {}) syncer-state-atom (atom {}) create-cook-scheduler-helper (fn create-cook-scheduler-helper [config] (create-cook-scheduler config cook-api service-id->failed-instances-transient-store syncer-state-atom))] (testing "should throw on invalid configuration" (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :allowed-users #{})))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :backend-port -5)))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :backend-port 0)))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :home-path-prefix nil)))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :instance-priorities {})))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :search-interval-days 0))))) (testing "should work with valid configuration" (is (instance? CookScheduler (create-cook-scheduler-helper valid-config)))) (testing "validate service - normal" (scheduler/validate-service (create-cook-scheduler-helper (assoc valid-config :service-id->service-description-fn (constantly {}))) nil)) (testing "validate service - test that image can't be set" (is (thrown? Throwable (scheduler/validate-service (create-cook-scheduler-helper (assoc valid-config :service-id->service-description-fn (constantly {"image" "twosigma/waiter-test-apps"}))) nil)))))))
24545
;; ;; 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 waiter.scheduler.cook-test (:require [clj-time.coerce :as tc] [clj-time.core :as t] [clojure.string :as str] [clojure.test :refer :all] [waiter.config :as config] [waiter.scheduler.cook :refer :all] [waiter.mesos.mesos :as mesos] [waiter.scheduler :as scheduler] [waiter.util.date-utils :as du] [waiter.util.http-utils :as http-utils] [waiter.util.utils :as utils]) (:import (clojure.lang ExceptionInfo) (java.util UUID) (waiter.scheduler.cook CookScheduler))) (deftest test-post-jobs (let [http-client (Object.) cook-url "http://cook.localtest.me" job-description {:jobs [{:application {:name "test-service" :version "123456"} :command "test-command" :cpus 1 :labels {:user "test-user"} :mem 1536}]}] (testing "impersonation disabled" (let [cook-api {:http-client http-client :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/jobs") in-request-url)) (is (= {:accept "application/json" :body (utils/clj->json job-description) :content-type "application/json" :headers {} :request-method :post :spnego-auth "test-spnego-auth"} options)))] (post-jobs cook-api job-description)))) (testing "impersonation enabled" (let [cook-api {:http-client http-client :impersonate true :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/jobs") in-request-url)) (is (= {:accept "application/json" :body (utils/clj->json job-description) :content-type "application/json" :headers {"x-cook-impersonate" "test-user"} :request-method :post :spnego-auth "test-spnego-auth"} options)))] (post-jobs cook-api job-description)))))) (deftest test-delete-jobs (let [http-client (Object.) cook-url "http://cook.localtest.me" run-as-user "test-user" job-uuids ["uuid-1" "uuid-2" "uuid-3"]] (testing "impersonation disabled" (let [cook-api {:http-client http-client :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/rawscheduler") in-request-url)) (is (= {:accept "application/json" :content-type "application/json" :headers {} :query-string {:job job-uuids} :request-method :delete :spnego-auth "test-spnego-auth"} options)))] (delete-jobs cook-api run-as-user job-uuids)))) (testing "impersonation enabled" (let [cook-api {:http-client http-client :impersonate true :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/rawscheduler") in-request-url)) (is (= {:accept "application/json" :content-type "application/json" :headers {"x-cook-impersonate" "test-user"} :query-string {:job job-uuids} :request-method :delete :spnego-auth "test-spnego-auth"} options)))] (delete-jobs cook-api run-as-user job-uuids)))))) (deftest test-get-jobs (let [http-client (Object.) cook-url "http://cook.localtest.me" cook-api {:http-client http-client :spnego-auth "test-spnego-auth" :url cook-url} test-user "test-user" current-time (t/now) service-id "test-service-id" cook-job-1 {:application {:name "test-job" :version "123456"} :labels {:user test-user}} cook-job-2 {:application {:name "test-service-1" :version "123456"} :labels {:source "waiter" :user test-user}} cook-job-3 {:application {:name "test-service-3" :version "238723"} :labels {:source "waiter" :user test-user}} http-request-fn-factory (fn [expected-query-string] (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/jobs") in-request-url)) (is (= {:accept "application/json" :content-type "application/json" :query-string expected-query-string :request-method :get :spnego-auth "test-spnego-auth"} options)) [cook-job-1 cook-job-2 cook-job-3]))] (with-redefs [t/now (constantly current-time)] (testing "no optional arguments" (let [end-time current-time search-interval (t/days 7) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states)))))) (testing "only search interval argument" (let [end-time current-time search-interval (t/days 4) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :search-interval search-interval)))))) (testing "only end-time argument" (let [end-time (t/minus current-time (t/days 1)) search-interval (t/days 7) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :end-time end-time)))))) (testing "only service-id argument" (let [end-time current-time search-interval (t/days 7) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :name (str service-id "*") :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :service-id service-id)))))) (testing "all arguments" (let [end-time current-time search-interval (t/days 2) start-time (t/minus end-time search-interval) states ["running" "waiting"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :end-time end-time :start-time start-time))))))))) (deftest test-job-healthy? (with-redefs [http-utils/http-request (fn [_ in-health-check-url] (is (str/starts-with? in-health-check-url "http://www.hostname.com:1234/")) (when-not (str/includes? in-health-check-url "unhealthy") in-health-check-url))] (is (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [1234] :status "running" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/healthy"}})) (is (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [4567] :status "running" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-port "1234" :backend-proto "http" :health-check-url "/healthy"}})) (is (not (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [1234] :status "running" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/unhealthy"}}))) (is (not (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [1234] :status "failed" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/healthy"}}))) (is (not (job-healthy? {:status "completed" :instances [{:hostname "www.hostname.com" :ports [1234] :status "success" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/healthy"}}))))) (deftest test-create-job-description (with-redefs [config/retrieve-cluster-name (constantly "test-cluster")] (let [service-id->password-fn (fn [service-id] (str service-id "-password")) home-path-prefix "/home/path/" service-id "test-service-1" service-description {"backend-proto" "http" "cmd" "test-command" "concurrency-level" 1 "cpus" 1 "mem" 1536 "run-as-user" "test-user" "ports" 2 "restart-backoff-factor" 2 "grace-period-secs" 111 "health-check-interval-secs" 10 "health-check-max-consecutive-failures" 5 "health-check-port-index" 0 "health-check-url" "/health-check" "instance-expiry-mins" 3600 "env" {"FOO" "bar" "BAZ" "quux"} "name" "test-service" "version" "123456"} instance-priority 75 expected-job {:application {:name "test-service" :version "123456"} :command "test-command" :cpus 1 :disable-mea-culpa-retries true :env {"BAZ" "quux" "FOO" "bar" "HOME" "/home/path/test-user" "LOGNAME" "test-user" "USER" "test-user" "WAITER_CLUSTER" "test-cluster" "WAITER_CONCURRENCY_LEVEL" "1" "WAITER_CPUS" "1" "WAITER_MEM_MB" "1536" "WAITER_PASSWORD" "<PASSWORD>" "WAITER_SERVICE_ID" "test-service-1" "WAITER_USERNAME" "waiter"} :executor "cook" :labels {:backend-proto "http" :health-check-url "/health-check" :service-id "test-service-1" :source "waiter" :user "test-user"} :max-retries 1 :max-runtime 216300000 :mem 1536 :ports 2 :priority 75}] (testing "basic-test-with-defaults" (let [backend-port nil actual (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port) job-uuid (-> actual :jobs first :uuid) expected {:jobs [(assoc expected-job :name (str "test-service-1." job-uuid) :uuid job-uuid)]}] (is (= expected actual)))) (testing "basic-test-custom-port" (let [service-description service-description backend-port 4567 actual (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port) job-uuid (-> actual :jobs first :uuid) expected {:jobs [(-> expected-job (assoc :name (str "test-service-1." job-uuid) :uuid job-uuid) (update :labels assoc :backend-port "4567"))]}] (is (= expected actual)))) (testing "basic-test-with-docker-image" (let [service-description (assoc service-description "cmd-type" "docker" "version" "foo/bar:baz") backend-port nil actual (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port) job-uuid (-> actual :jobs first :uuid) expected {:jobs [(assoc expected-job :application {:name "test-service" :version "baz"} :container {:docker {:force-pull-image false :image "namespace:foo,name:bar,label:baz" :network "HOST"} :type "docker"} :name (str "test-service-1." job-uuid) :uuid job-uuid)]}] (is (= expected actual))) (is (thrown-with-msg? ExceptionInfo #"to use container support format version as namespace/name:label" (let [service-description (assoc service-description "cmd-type" "docker" "version" "foo/bar-baz") backend-port nil] (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port)))))))) (deftest test-determine-instance-priority (let [allowed-priorities [75 70 65 60 55]] (is (= 75 (determine-instance-priority allowed-priorities #{}))) (is (= 70 (determine-instance-priority allowed-priorities #{75}))) (is (= 65 (determine-instance-priority allowed-priorities #{75 70}))) (is (= 70 (determine-instance-priority allowed-priorities #{75 65}))) (is (= 60 (determine-instance-priority allowed-priorities #{75 70 65 55}))) (is (= 55 (determine-instance-priority allowed-priorities #{75 70 65 60}))) (is (= 55 (determine-instance-priority allowed-priorities #{75 70 65 60 55}))))) (deftest test-launch-jobs (let [posted-jobs-atom (atom [])] (with-redefs [create-job-description (fn [service-id _ _ _ instance-priority _] {:priority instance-priority :service-id service-id}) post-jobs (fn [_ job] (swap! posted-jobs-atom conj job))] (let [cook-api (Object.) service-id "test-service-id" service-description {} service-id->password-fn (constantly "<PASSWORD>") home-path-prefix "/home/path/" num-instances 3 allowed-priorities [75 70 65 60 55] reserved-priorities #{75 65} backend-port nil] (launch-jobs cook-api service-id service-description service-id->password-fn home-path-prefix num-instances allowed-priorities reserved-priorities backend-port) (is (= [{:priority 70 :service-id service-id} {:priority 60 :service-id service-id} {:priority 55 :service-id service-id}] @posted-jobs-atom)))))) (deftest test-retrieve-jobs (let [search-interval (t/days 1) service-id "test-service-id" test-user "test-user"] (with-redefs [get-jobs (fn [_ user states & {:as options}] (is (= test-user user)) (is (= ["running" "waiting"] states)) (is (= {:search-interval search-interval :service-id service-id} options)) [])] (retrieve-jobs (Object.) search-interval service-id {"run-as-user" test-user})))) (deftest test-job->service-instance (with-redefs [job-healthy? (constantly true)] (let [job-uuid (str (UUID/randomUUID)) start-time (System/currentTimeMillis) expected-instance {:cook/job-name "job-name" :cook/job-uuid job-uuid :cook/priority 75 :cook/task-id "task-id" :exit-code 0 :extra-ports [5678 7890] :flags #{} :health-check-status nil :healthy? true :host "hostname.localtest.me" :id "job-name_test-user_task-id" :log-directory "/sandbox/directory" :message "test reason" :port 1234 :service-id "service-id" :started-at (tc/from-long start-time)} actual-job {:instances [{:exit_code 0 :hostname "hostname.localtest.me" :ports [1234 5678 7890] :reason_string "test reason" :sandbox_directory "/sandbox/directory" :start_time start-time :task_id "task-id"}] :labels {:backend-proto "http" :health-check-port-index 1 :service-id "service-id" :user "test-user"} :name "job-name" :priority 75 :status "running" :uuid job-uuid}] (testing "basic job" (is (= (scheduler/make-ServiceInstance expected-instance) (job->service-instance actual-job)))) (testing "job with custom port" (let [expected-instance (assoc expected-instance :extra-ports [1234 5678 7890] :port 4321) actual-job (update actual-job :labels assoc :backend-port "4321")] (is (= (scheduler/make-ServiceInstance expected-instance) (job->service-instance actual-job)))))))) (deftest test-jobs->service (with-redefs [job-healthy? #(str/includes? (:name %) "healthy-")] (let [suffix (System/nanoTime) jobs [{:labels {:service-id "test-service-id"} :name (str "healthy-1." suffix) :status "running"} {:labels {:service-id "test-service-id"} :name (str "healthy-2." suffix) :status "running"} {:labels {:service-id "test-service-id"} :name (str "unhealthy." suffix) :status "running"} {:labels {:service-id "test-service-id"} :name (str "staging-1." suffix) :status "staging"}]] (is (= (scheduler/make-Service {:id "test-service-id" :instances 4 :task-count 4 :task-stats {:healthy 2 :running 3 :staged 1 :unhealthy 1}}) (jobs->service jobs)))))) (defn- parse-and-store-failed-instance! "Parses the failed instance response and adds it to the known set of failed instances." [service-id->failed-instances-transient-store service-id failed-instance] (when failed-instance (let [max-instances-to-keep 10] (scheduler/add-instance-to-buffered-collection! service-id->failed-instances-transient-store max-instances-to-keep service-id failed-instance (fn [] #{}) (fn [instances] (-> (scheduler/sort-instances instances) (rest) (set))))))) (deftest test-service-id->failed-instances-transient-store (let [health-check-url "/status" failed-instance-response-fn (fn [service-id instance-id] {:health-check-path health-check-url :host (str "10.141.141." instance-id) :id (str service-id "." instance-id) :message "Abnormal executor termination" :port 0 :service-id service-id :started-at (du/str-to-date "2014-09-12T23:23:41.711Z") :version "2014-09-12T23:28:21.737Z"}) service-id-1 "test-service-id-failed-instances-1" service-id-2 "test-service-id-failed-instances-2" service-id->failed-instances-transient-store (atom {})] (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store []) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 1 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 1 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "B") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "B") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "C") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "D") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 4 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store []) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 1 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "B") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "C") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "D") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "E") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "F") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "G") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "H") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "I") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 9 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-2)))) (->> (failed-instance-response-fn service-id-2 "X") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-2)) (->> (failed-instance-response-fn service-id-2 "Y") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-2)) (->> (failed-instance-response-fn service-id-2 "Z") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-2)) (remove-failed-instances-for-service! service-id->failed-instances-transient-store service-id-1) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-2)))) (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store [service-id-2]) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-2)))))) (deftest test-max-failed-instances-cache (let [current-time (t/now) current-time-str (du/date-to-str current-time) service-id->failed-instances-transient-store (atom {}) make-instance (fn [n] {:id (str "service-1." n) :service-id "service-1" :started-at (du/str-to-date current-time-str) :healthy? false :port 0})] (testing "test-max-failed-instances-cache" (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store []) (doseq [n (range 10 50)] (parse-and-store-failed-instance! service-id->failed-instances-transient-store "service-1" (make-instance n))) (let [actual-failed-instances (set (service-id->failed-instances service-id->failed-instances-transient-store "service-1"))] (is (= 10 (count actual-failed-instances))) (doseq [n (range 40 50)] (is (contains? actual-failed-instances (make-instance n)) (str "Failed instances does not contain instance service-1." n))))))) (deftest test-retrieve-log-url (let [host "agent-1.com" mesos-api (Object.)] (with-redefs [mesos/get-agent-state (fn [in-mesos-api in-host] (is (= mesos-api in-mesos-api)) (is (= host in-host)) {:frameworks [{:completed_executors [{:directory "/path/to/instance1/directory" :id "service-id-1.instance-id-1"}] :executors [{:directory "/path/to/instance2/directory" :id "service-id-1.instance-id-2"}] :role "cook"} {:completed_executors [{:directory "/marathon/instance1/directory" :id "service-id-1.instance-id-1"}] :executors [{:directory "/marathon/instance2/directory" :id "service-id-1.instance-id-2"}] :name "marathon"} {:completed_executors [{:directory "/path/to/instance3/directory" :id "service-id-1.instance-id-3"}] :executors [{:directory "/path/to/instance4/directory" :id "service-id-1.instance-id-4"}] :name "Cook-1.17.4" :role "*"}]})] (is (= "/path/to/instance1/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-1" host "cook"))) (is (= "/path/to/instance2/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-2" host "cook"))) (is (= "/path/to/instance3/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-3" host "cook"))) (is (= "/path/to/instance4/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-4" host "cook")))))) (defn create-cook-scheduler-helper [& {:as cook-config}] (-> {:allowed-priorities [60 55 50 45 40] :allowed-users #{"test-user"} :cook-api {} :home-path-prefix "/home/path/" :search-interval (t/minutes 10) ;; context :retrieve-syncer-state-fn (constantly {}) :scheduler-name "cook" :service-id->failed-instances-transient-store (atom {}) :service-id->password-fn #(str % <PASSWORD>") :service-id->service-description-fn (constantly {})} (merge cook-config) map->CookScheduler)) (deftest test-get-services->instances (let [{:keys [allowed-users cook-api search-interval service-id->failed-instances-transient-store] :as scheduler} (create-cook-scheduler-helper) suffix (System/nanoTime) jobs [{:labels {:service-id "S1"} :name (str "healthy-S1.1." suffix) :status "running"} {:labels {:service-id "S1"} :name (str "healthy-S1.2." suffix) :status "running"} {:labels {:service-id "S1"} :name (str "unhealthy-S1." suffix) :status "running"} {:labels {:service-id "S1"} :name (str "staging-S1.1." suffix) :status "staging"} {:labels {:service-id "S2"} :name (str "healthy-S2.1." suffix) :status "running"} {:labels {:service-id "S2"} :name (str "staging-S2.1." suffix) :status "staging"}]] (with-redefs [job-healthy? #(str/includes? (:name %) "healthy-") get-jobs (fn [cook-api _ states & {:keys [search-interval]}] (is (= (:cook-api scheduler) cook-api)) (is (= ["running" "waiting"] states)) (is (= (:search-interval scheduler) search-interval)) jobs) job->service-instance (fn [{:keys [name]}] {:id name})] (scheduler/add-instance-to-buffered-collection! service-id->failed-instances-transient-store 1 "S2" {:id (str "failed-S2.1." suffix) :service-id "S2"} (fn [] #{}) (fn [instances] (-> (scheduler/sort-instances instances) (rest) (set)))) (try (let [service-1 (scheduler/make-Service {:id "S1" :instances 4 :task-count 4 :task-stats {:healthy 3 :running 3 :staged 1 :unhealthy 0}}) service-1-instances {:active-instances [{:id (str "healthy-S1.1." suffix)} {:id (str "healthy-S1.2." suffix)} {:id (str "unhealthy-S1." suffix)} {:id (str "staging-S1.1." suffix)}] :failed-instances []} service-2 (scheduler/make-Service {:id "S2" :instances 2 :task-count 2 :task-stats {:healthy 1 :running 1 :staged 1 :unhealthy 0}}) service-2-instances {:active-instances [{:id (str "healthy-S2.1." suffix)} {:id (str "staging-S2.1." suffix)}] :failed-instances (service-id->failed-instances service-id->failed-instances-transient-store "S2")}] (is (seq (service-id->failed-instances service-id->failed-instances-transient-store "S2"))) (is (= {service-1 service-1-instances, service-2 service-2-instances} (get-service->instances cook-api allowed-users search-interval service-id->failed-instances-transient-store)))) (finally (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store [])))))) (deftest test-kill-instance (let [scheduler (create-cook-scheduler-helper) service-id "foo" test-instance {:cook/job-uuid "uuid-1" :id "foo.1A" :service-id service-id} current-time (t/now)] (with-redefs [retrieve-jobs (constantly [{:uuid "uuid-1"} {:uuid "uuid-2"} {:uuid "uuid-3"}]) t/now (constantly current-time)] (with-redefs [delete-jobs (constantly {:deploymentId 12345})] (is (= {:killed? true :message "Killed foo.1A" :result :killed :success true} (scheduler/kill-instance scheduler test-instance)))) (with-redefs [delete-jobs (constantly {})] (is (= {:killed? true :message "Killed foo.1A" :result :killed :success true} (scheduler/kill-instance scheduler test-instance)))) (with-redefs [delete-jobs (fn [_ _] (throw (ex-info "Delete error" {:status 400})))] (is (= {:killed? false :message "Unable to kill foo.1A" :result :failed :success false} (scheduler/kill-instance scheduler test-instance)))) (with-redefs [delete-jobs (constantly {}) retrieve-jobs (constantly nil)] (is (= {:message "foo does not exist!" :result :no-such-service-exists :success false} (scheduler/kill-instance scheduler test-instance))))))) (deftest test-create-instance (let [cook-api (Object.) test-user "test-user" cook-scheduler (create-cook-scheduler-helper :allowed-users #{test-user} :cook-api cook-api) service-id "foo" min-instances 4 descriptor {:service-description {"min-instances" min-instances "run-as-user" test-user} :service-id service-id}] (testing "create service - success" (let [updated-invoked-promise (promise)] (with-redefs [scheduler/service-exists? (constantly false) launch-jobs (fn [in-cook-api in-service-id _ _ _ num-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= min-instances num-instances)) true)] (is (= {:message "Created foo" :result :created :success true} (scheduler/create-service-if-new cook-scheduler descriptor))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "create service - failure" (let [updated-invoked-promise (promise)] (with-redefs [scheduler/service-exists? (constantly false) launch-jobs (fn [in-cook-api in-service-id _ _ _ num-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= min-instances num-instances)) (throw (ex-info "Failed" {})))] (is (= {:message "Unable to create foo" :result :failed :success false} (scheduler/create-service-if-new cook-scheduler descriptor))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "create service - service exists" (with-redefs [retrieve-jobs (fn [_ _ in-service-id & _] (= service-id in-service-id))] (is (scheduler/service-exists? cook-scheduler service-id)) (is (= {:message "foo already exists!" :result :already-exists :success false} (scheduler/create-service-if-new cook-scheduler descriptor))))))) (deftest test-delete-service (with-redefs [retrieve-jobs (constantly [{:uuid "uuid-1"} {:uuid "uuid-2"} {:uuid "uuid-3"}])] (let [scheduler (create-cook-scheduler-helper)] (with-redefs [delete-jobs (constantly {:deploymentId 12345})] (is (= {:message "Deleted foo" :result :deleted :success true} (scheduler/delete-service scheduler "foo")))) (with-redefs [delete-jobs (constantly {})] (is (= {:message "Deleted foo" :result :deleted :success true} (scheduler/delete-service scheduler "foo")))) (with-redefs [delete-jobs (fn [_ _] (throw (ex-info "Delete error" {:status 400})))] (is (= {:message "Unable to delete foo" :result :failed :success false} (scheduler/delete-service scheduler "foo")))) (with-redefs [delete-jobs (constantly {}) retrieve-jobs (constantly nil)] (is (= {:message "foo does not exist!" :result :no-such-service-exists :success false} (scheduler/delete-service scheduler "foo"))))))) (deftest test-scale-service (let [cook-api (Object.) cook-scheduler (create-cook-scheduler-helper :cook-api cook-api) service-id "test-service-id"] (testing "scale of service - no such service" (let [updated-invoked-promise (promise) instances 5] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) nil) launch-jobs (fn [in-cook-api in-service-id & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) true)] (is (= {:message "test-service-id does not exist!" :result :no-such-service-exists :success false} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :not-invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "scale of service - no-op" (let [updated-invoked-promise (promise) instances 5] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (for [n (range 10)] {:cook/job-uuid (str "uuid-" n) :id (str service-id "." n) :priority n :service-id service-id})) launch-jobs (fn [in-cook-api in-service-id _ _ _ extra-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= 20 extra-instances)) true)] (is (= {:message "Scaled test-service-id" :result :scaling-not-needed :success true} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :not-invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "scale of service - success" (let [updated-invoked-promise (promise) instances 30] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (for [n (range 10)] {:cook/job-uuid (str "uuid-" n) :id (str service-id "." n) :priority n :service-id service-id})) launch-jobs (fn [in-cook-api in-service-id _ _ _ extra-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= 20 extra-instances)) true)] (is (= {:message "Scaled test-service-id" :result :scaled :success true} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "scale of service - fail" (let [updated-invoked-promise (promise) instances 30] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (for [n (range 10)] {:cook/job-uuid (str "uuid-" n) :id (str service-id "." n) :priority n :service-id service-id})) launch-jobs (fn [in-cook-api in-service-id _ _ _ extra-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= 20 extra-instances)) (throw (ex-info "Launch failed!" {})))] (is (= {:message "Unable to scale test-service-id" :result :failed :success false} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))))) (deftest test-service-id->state (let [service-id "service-id" syncer-state-atom (atom {:last-update-time :time :service-id->health-check-context {}}) retrieve-syncer-state-fn (partial scheduler/retrieve-syncer-state @syncer-state-atom) cook-scheduler (create-cook-scheduler-helper :retrieve-syncer-state-fn retrieve-syncer-state-fn :service-id->failed-instances-transient-store (atom {service-id [:failed-instances]}))] (is (= {:failed-instances [:failed-instances] :syncer {:last-update-time :time}} (scheduler/service-id->state cook-scheduler service-id))) (is (= {:authorizer nil :service-id->failed-instances-transient-store {"service-id" [:failed-instances]} :syncer {:last-update-time :time :service-id->health-check-context {}}} (scheduler/state cook-scheduler))))) (deftest test-cook-scheduler (testing "Creating a CookScheduler" (let [valid-config {:allowed-users #{"test-user"} :authorizer {:kind :default :default {:factory-fn 'waiter.authorization/noop-authorizer}} :backend-port 7890 :cook-api {} :home-path-prefix "/home/path/" :instance-priorities {:delta 5 :max 70 :min 30} :search-interval-days 10 :scheduler-name "cook" :service-id->password-fn #(str % <PASSWORD>") :service-id->service-description-fn (constantly {})} cook-api (Object.) service-id->failed-instances-transient-store (atom {}) syncer-state-atom (atom {}) create-cook-scheduler-helper (fn create-cook-scheduler-helper [config] (create-cook-scheduler config cook-api service-id->failed-instances-transient-store syncer-state-atom))] (testing "should throw on invalid configuration" (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :allowed-users #{})))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :backend-port -5)))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :backend-port 0)))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :home-path-prefix nil)))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :instance-priorities {})))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :search-interval-days 0))))) (testing "should work with valid configuration" (is (instance? CookScheduler (create-cook-scheduler-helper valid-config)))) (testing "validate service - normal" (scheduler/validate-service (create-cook-scheduler-helper (assoc valid-config :service-id->service-description-fn (constantly {}))) nil)) (testing "validate service - test that image can't be set" (is (thrown? Throwable (scheduler/validate-service (create-cook-scheduler-helper (assoc valid-config :service-id->service-description-fn (constantly {"image" "twosigma/waiter-test-apps"}))) nil)))))))
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 waiter.scheduler.cook-test (:require [clj-time.coerce :as tc] [clj-time.core :as t] [clojure.string :as str] [clojure.test :refer :all] [waiter.config :as config] [waiter.scheduler.cook :refer :all] [waiter.mesos.mesos :as mesos] [waiter.scheduler :as scheduler] [waiter.util.date-utils :as du] [waiter.util.http-utils :as http-utils] [waiter.util.utils :as utils]) (:import (clojure.lang ExceptionInfo) (java.util UUID) (waiter.scheduler.cook CookScheduler))) (deftest test-post-jobs (let [http-client (Object.) cook-url "http://cook.localtest.me" job-description {:jobs [{:application {:name "test-service" :version "123456"} :command "test-command" :cpus 1 :labels {:user "test-user"} :mem 1536}]}] (testing "impersonation disabled" (let [cook-api {:http-client http-client :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/jobs") in-request-url)) (is (= {:accept "application/json" :body (utils/clj->json job-description) :content-type "application/json" :headers {} :request-method :post :spnego-auth "test-spnego-auth"} options)))] (post-jobs cook-api job-description)))) (testing "impersonation enabled" (let [cook-api {:http-client http-client :impersonate true :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/jobs") in-request-url)) (is (= {:accept "application/json" :body (utils/clj->json job-description) :content-type "application/json" :headers {"x-cook-impersonate" "test-user"} :request-method :post :spnego-auth "test-spnego-auth"} options)))] (post-jobs cook-api job-description)))))) (deftest test-delete-jobs (let [http-client (Object.) cook-url "http://cook.localtest.me" run-as-user "test-user" job-uuids ["uuid-1" "uuid-2" "uuid-3"]] (testing "impersonation disabled" (let [cook-api {:http-client http-client :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/rawscheduler") in-request-url)) (is (= {:accept "application/json" :content-type "application/json" :headers {} :query-string {:job job-uuids} :request-method :delete :spnego-auth "test-spnego-auth"} options)))] (delete-jobs cook-api run-as-user job-uuids)))) (testing "impersonation enabled" (let [cook-api {:http-client http-client :impersonate true :spnego-auth "test-spnego-auth" :url cook-url}] (with-redefs [http-utils/http-request (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/rawscheduler") in-request-url)) (is (= {:accept "application/json" :content-type "application/json" :headers {"x-cook-impersonate" "test-user"} :query-string {:job job-uuids} :request-method :delete :spnego-auth "test-spnego-auth"} options)))] (delete-jobs cook-api run-as-user job-uuids)))))) (deftest test-get-jobs (let [http-client (Object.) cook-url "http://cook.localtest.me" cook-api {:http-client http-client :spnego-auth "test-spnego-auth" :url cook-url} test-user "test-user" current-time (t/now) service-id "test-service-id" cook-job-1 {:application {:name "test-job" :version "123456"} :labels {:user test-user}} cook-job-2 {:application {:name "test-service-1" :version "123456"} :labels {:source "waiter" :user test-user}} cook-job-3 {:application {:name "test-service-3" :version "238723"} :labels {:source "waiter" :user test-user}} http-request-fn-factory (fn [expected-query-string] (fn [in-http-client in-request-url & {:as options}] (is (= http-client in-http-client)) (is (= (str cook-url "/jobs") in-request-url)) (is (= {:accept "application/json" :content-type "application/json" :query-string expected-query-string :request-method :get :spnego-auth "test-spnego-auth"} options)) [cook-job-1 cook-job-2 cook-job-3]))] (with-redefs [t/now (constantly current-time)] (testing "no optional arguments" (let [end-time current-time search-interval (t/days 7) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states)))))) (testing "only search interval argument" (let [end-time current-time search-interval (t/days 4) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :search-interval search-interval)))))) (testing "only end-time argument" (let [end-time (t/minus current-time (t/days 1)) search-interval (t/days 7) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :end-time end-time)))))) (testing "only service-id argument" (let [end-time current-time search-interval (t/days 7) start-time (t/minus end-time search-interval) states ["running"] query-string {:end (du/date-to-str end-time) :name (str service-id "*") :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :service-id service-id)))))) (testing "all arguments" (let [end-time current-time search-interval (t/days 2) start-time (t/minus end-time search-interval) states ["running" "waiting"] query-string {:end (du/date-to-str end-time) :start (du/date-to-str start-time) :state states :user test-user}] (with-redefs [http-utils/http-request (http-request-fn-factory query-string)] (is (= [cook-job-2 cook-job-3] (get-jobs cook-api test-user states :end-time end-time :start-time start-time))))))))) (deftest test-job-healthy? (with-redefs [http-utils/http-request (fn [_ in-health-check-url] (is (str/starts-with? in-health-check-url "http://www.hostname.com:1234/")) (when-not (str/includes? in-health-check-url "unhealthy") in-health-check-url))] (is (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [1234] :status "running" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/healthy"}})) (is (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [4567] :status "running" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-port "1234" :backend-proto "http" :health-check-url "/healthy"}})) (is (not (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [1234] :status "running" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/unhealthy"}}))) (is (not (job-healthy? {:status "running" :instances [{:hostname "www.hostname.com" :ports [1234] :status "failed" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/healthy"}}))) (is (not (job-healthy? {:status "completed" :instances [{:hostname "www.hostname.com" :ports [1234] :status "success" :task_id (str "task-" (System/nanoTime))}] :labels {:backend-proto "http" :health-check-url "/healthy"}}))))) (deftest test-create-job-description (with-redefs [config/retrieve-cluster-name (constantly "test-cluster")] (let [service-id->password-fn (fn [service-id] (str service-id "-password")) home-path-prefix "/home/path/" service-id "test-service-1" service-description {"backend-proto" "http" "cmd" "test-command" "concurrency-level" 1 "cpus" 1 "mem" 1536 "run-as-user" "test-user" "ports" 2 "restart-backoff-factor" 2 "grace-period-secs" 111 "health-check-interval-secs" 10 "health-check-max-consecutive-failures" 5 "health-check-port-index" 0 "health-check-url" "/health-check" "instance-expiry-mins" 3600 "env" {"FOO" "bar" "BAZ" "quux"} "name" "test-service" "version" "123456"} instance-priority 75 expected-job {:application {:name "test-service" :version "123456"} :command "test-command" :cpus 1 :disable-mea-culpa-retries true :env {"BAZ" "quux" "FOO" "bar" "HOME" "/home/path/test-user" "LOGNAME" "test-user" "USER" "test-user" "WAITER_CLUSTER" "test-cluster" "WAITER_CONCURRENCY_LEVEL" "1" "WAITER_CPUS" "1" "WAITER_MEM_MB" "1536" "WAITER_PASSWORD" "PI:PASSWORD:<PASSWORD>END_PI" "WAITER_SERVICE_ID" "test-service-1" "WAITER_USERNAME" "waiter"} :executor "cook" :labels {:backend-proto "http" :health-check-url "/health-check" :service-id "test-service-1" :source "waiter" :user "test-user"} :max-retries 1 :max-runtime 216300000 :mem 1536 :ports 2 :priority 75}] (testing "basic-test-with-defaults" (let [backend-port nil actual (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port) job-uuid (-> actual :jobs first :uuid) expected {:jobs [(assoc expected-job :name (str "test-service-1." job-uuid) :uuid job-uuid)]}] (is (= expected actual)))) (testing "basic-test-custom-port" (let [service-description service-description backend-port 4567 actual (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port) job-uuid (-> actual :jobs first :uuid) expected {:jobs [(-> expected-job (assoc :name (str "test-service-1." job-uuid) :uuid job-uuid) (update :labels assoc :backend-port "4567"))]}] (is (= expected actual)))) (testing "basic-test-with-docker-image" (let [service-description (assoc service-description "cmd-type" "docker" "version" "foo/bar:baz") backend-port nil actual (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port) job-uuid (-> actual :jobs first :uuid) expected {:jobs [(assoc expected-job :application {:name "test-service" :version "baz"} :container {:docker {:force-pull-image false :image "namespace:foo,name:bar,label:baz" :network "HOST"} :type "docker"} :name (str "test-service-1." job-uuid) :uuid job-uuid)]}] (is (= expected actual))) (is (thrown-with-msg? ExceptionInfo #"to use container support format version as namespace/name:label" (let [service-description (assoc service-description "cmd-type" "docker" "version" "foo/bar-baz") backend-port nil] (create-job-description service-id service-description service-id->password-fn home-path-prefix instance-priority backend-port)))))))) (deftest test-determine-instance-priority (let [allowed-priorities [75 70 65 60 55]] (is (= 75 (determine-instance-priority allowed-priorities #{}))) (is (= 70 (determine-instance-priority allowed-priorities #{75}))) (is (= 65 (determine-instance-priority allowed-priorities #{75 70}))) (is (= 70 (determine-instance-priority allowed-priorities #{75 65}))) (is (= 60 (determine-instance-priority allowed-priorities #{75 70 65 55}))) (is (= 55 (determine-instance-priority allowed-priorities #{75 70 65 60}))) (is (= 55 (determine-instance-priority allowed-priorities #{75 70 65 60 55}))))) (deftest test-launch-jobs (let [posted-jobs-atom (atom [])] (with-redefs [create-job-description (fn [service-id _ _ _ instance-priority _] {:priority instance-priority :service-id service-id}) post-jobs (fn [_ job] (swap! posted-jobs-atom conj job))] (let [cook-api (Object.) service-id "test-service-id" service-description {} service-id->password-fn (constantly "PI:PASSWORD:<PASSWORD>END_PI") home-path-prefix "/home/path/" num-instances 3 allowed-priorities [75 70 65 60 55] reserved-priorities #{75 65} backend-port nil] (launch-jobs cook-api service-id service-description service-id->password-fn home-path-prefix num-instances allowed-priorities reserved-priorities backend-port) (is (= [{:priority 70 :service-id service-id} {:priority 60 :service-id service-id} {:priority 55 :service-id service-id}] @posted-jobs-atom)))))) (deftest test-retrieve-jobs (let [search-interval (t/days 1) service-id "test-service-id" test-user "test-user"] (with-redefs [get-jobs (fn [_ user states & {:as options}] (is (= test-user user)) (is (= ["running" "waiting"] states)) (is (= {:search-interval search-interval :service-id service-id} options)) [])] (retrieve-jobs (Object.) search-interval service-id {"run-as-user" test-user})))) (deftest test-job->service-instance (with-redefs [job-healthy? (constantly true)] (let [job-uuid (str (UUID/randomUUID)) start-time (System/currentTimeMillis) expected-instance {:cook/job-name "job-name" :cook/job-uuid job-uuid :cook/priority 75 :cook/task-id "task-id" :exit-code 0 :extra-ports [5678 7890] :flags #{} :health-check-status nil :healthy? true :host "hostname.localtest.me" :id "job-name_test-user_task-id" :log-directory "/sandbox/directory" :message "test reason" :port 1234 :service-id "service-id" :started-at (tc/from-long start-time)} actual-job {:instances [{:exit_code 0 :hostname "hostname.localtest.me" :ports [1234 5678 7890] :reason_string "test reason" :sandbox_directory "/sandbox/directory" :start_time start-time :task_id "task-id"}] :labels {:backend-proto "http" :health-check-port-index 1 :service-id "service-id" :user "test-user"} :name "job-name" :priority 75 :status "running" :uuid job-uuid}] (testing "basic job" (is (= (scheduler/make-ServiceInstance expected-instance) (job->service-instance actual-job)))) (testing "job with custom port" (let [expected-instance (assoc expected-instance :extra-ports [1234 5678 7890] :port 4321) actual-job (update actual-job :labels assoc :backend-port "4321")] (is (= (scheduler/make-ServiceInstance expected-instance) (job->service-instance actual-job)))))))) (deftest test-jobs->service (with-redefs [job-healthy? #(str/includes? (:name %) "healthy-")] (let [suffix (System/nanoTime) jobs [{:labels {:service-id "test-service-id"} :name (str "healthy-1." suffix) :status "running"} {:labels {:service-id "test-service-id"} :name (str "healthy-2." suffix) :status "running"} {:labels {:service-id "test-service-id"} :name (str "unhealthy." suffix) :status "running"} {:labels {:service-id "test-service-id"} :name (str "staging-1." suffix) :status "staging"}]] (is (= (scheduler/make-Service {:id "test-service-id" :instances 4 :task-count 4 :task-stats {:healthy 2 :running 3 :staged 1 :unhealthy 1}}) (jobs->service jobs)))))) (defn- parse-and-store-failed-instance! "Parses the failed instance response and adds it to the known set of failed instances." [service-id->failed-instances-transient-store service-id failed-instance] (when failed-instance (let [max-instances-to-keep 10] (scheduler/add-instance-to-buffered-collection! service-id->failed-instances-transient-store max-instances-to-keep service-id failed-instance (fn [] #{}) (fn [instances] (-> (scheduler/sort-instances instances) (rest) (set))))))) (deftest test-service-id->failed-instances-transient-store (let [health-check-url "/status" failed-instance-response-fn (fn [service-id instance-id] {:health-check-path health-check-url :host (str "10.141.141." instance-id) :id (str service-id "." instance-id) :message "Abnormal executor termination" :port 0 :service-id service-id :started-at (du/str-to-date "2014-09-12T23:23:41.711Z") :version "2014-09-12T23:28:21.737Z"}) service-id-1 "test-service-id-failed-instances-1" service-id-2 "test-service-id-failed-instances-2" service-id->failed-instances-transient-store (atom {})] (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store []) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 1 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 1 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "B") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "B") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "C") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "D") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 4 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store []) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 1 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "B") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "A") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 2 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "C") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (->> (failed-instance-response-fn service-id-1 "D") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "E") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "F") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "G") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "H") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (->> (failed-instance-response-fn service-id-1 "I") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-1)) (is (= 9 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-2)))) (->> (failed-instance-response-fn service-id-2 "X") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-2)) (->> (failed-instance-response-fn service-id-2 "Y") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-2)) (->> (failed-instance-response-fn service-id-2 "Z") (parse-and-store-failed-instance! service-id->failed-instances-transient-store service-id-2)) (remove-failed-instances-for-service! service-id->failed-instances-transient-store service-id-1) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-2)))) (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store [service-id-2]) (is (= 0 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-1)))) (is (= 3 (count (service-id->failed-instances service-id->failed-instances-transient-store service-id-2)))))) (deftest test-max-failed-instances-cache (let [current-time (t/now) current-time-str (du/date-to-str current-time) service-id->failed-instances-transient-store (atom {}) make-instance (fn [n] {:id (str "service-1." n) :service-id "service-1" :started-at (du/str-to-date current-time-str) :healthy? false :port 0})] (testing "test-max-failed-instances-cache" (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store []) (doseq [n (range 10 50)] (parse-and-store-failed-instance! service-id->failed-instances-transient-store "service-1" (make-instance n))) (let [actual-failed-instances (set (service-id->failed-instances service-id->failed-instances-transient-store "service-1"))] (is (= 10 (count actual-failed-instances))) (doseq [n (range 40 50)] (is (contains? actual-failed-instances (make-instance n)) (str "Failed instances does not contain instance service-1." n))))))) (deftest test-retrieve-log-url (let [host "agent-1.com" mesos-api (Object.)] (with-redefs [mesos/get-agent-state (fn [in-mesos-api in-host] (is (= mesos-api in-mesos-api)) (is (= host in-host)) {:frameworks [{:completed_executors [{:directory "/path/to/instance1/directory" :id "service-id-1.instance-id-1"}] :executors [{:directory "/path/to/instance2/directory" :id "service-id-1.instance-id-2"}] :role "cook"} {:completed_executors [{:directory "/marathon/instance1/directory" :id "service-id-1.instance-id-1"}] :executors [{:directory "/marathon/instance2/directory" :id "service-id-1.instance-id-2"}] :name "marathon"} {:completed_executors [{:directory "/path/to/instance3/directory" :id "service-id-1.instance-id-3"}] :executors [{:directory "/path/to/instance4/directory" :id "service-id-1.instance-id-4"}] :name "Cook-1.17.4" :role "*"}]})] (is (= "/path/to/instance1/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-1" host "cook"))) (is (= "/path/to/instance2/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-2" host "cook"))) (is (= "/path/to/instance3/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-3" host "cook"))) (is (= "/path/to/instance4/directory" (mesos/retrieve-log-url mesos-api "service-id-1.instance-id-4" host "cook")))))) (defn create-cook-scheduler-helper [& {:as cook-config}] (-> {:allowed-priorities [60 55 50 45 40] :allowed-users #{"test-user"} :cook-api {} :home-path-prefix "/home/path/" :search-interval (t/minutes 10) ;; context :retrieve-syncer-state-fn (constantly {}) :scheduler-name "cook" :service-id->failed-instances-transient-store (atom {}) :service-id->password-fn #(str % PI:PASSWORD:<PASSWORD>END_PI") :service-id->service-description-fn (constantly {})} (merge cook-config) map->CookScheduler)) (deftest test-get-services->instances (let [{:keys [allowed-users cook-api search-interval service-id->failed-instances-transient-store] :as scheduler} (create-cook-scheduler-helper) suffix (System/nanoTime) jobs [{:labels {:service-id "S1"} :name (str "healthy-S1.1." suffix) :status "running"} {:labels {:service-id "S1"} :name (str "healthy-S1.2." suffix) :status "running"} {:labels {:service-id "S1"} :name (str "unhealthy-S1." suffix) :status "running"} {:labels {:service-id "S1"} :name (str "staging-S1.1." suffix) :status "staging"} {:labels {:service-id "S2"} :name (str "healthy-S2.1." suffix) :status "running"} {:labels {:service-id "S2"} :name (str "staging-S2.1." suffix) :status "staging"}]] (with-redefs [job-healthy? #(str/includes? (:name %) "healthy-") get-jobs (fn [cook-api _ states & {:keys [search-interval]}] (is (= (:cook-api scheduler) cook-api)) (is (= ["running" "waiting"] states)) (is (= (:search-interval scheduler) search-interval)) jobs) job->service-instance (fn [{:keys [name]}] {:id name})] (scheduler/add-instance-to-buffered-collection! service-id->failed-instances-transient-store 1 "S2" {:id (str "failed-S2.1." suffix) :service-id "S2"} (fn [] #{}) (fn [instances] (-> (scheduler/sort-instances instances) (rest) (set)))) (try (let [service-1 (scheduler/make-Service {:id "S1" :instances 4 :task-count 4 :task-stats {:healthy 3 :running 3 :staged 1 :unhealthy 0}}) service-1-instances {:active-instances [{:id (str "healthy-S1.1." suffix)} {:id (str "healthy-S1.2." suffix)} {:id (str "unhealthy-S1." suffix)} {:id (str "staging-S1.1." suffix)}] :failed-instances []} service-2 (scheduler/make-Service {:id "S2" :instances 2 :task-count 2 :task-stats {:healthy 1 :running 1 :staged 1 :unhealthy 0}}) service-2-instances {:active-instances [{:id (str "healthy-S2.1." suffix)} {:id (str "staging-S2.1." suffix)}] :failed-instances (service-id->failed-instances service-id->failed-instances-transient-store "S2")}] (is (seq (service-id->failed-instances service-id->failed-instances-transient-store "S2"))) (is (= {service-1 service-1-instances, service-2 service-2-instances} (get-service->instances cook-api allowed-users search-interval service-id->failed-instances-transient-store)))) (finally (preserve-only-failed-instances-for-services! service-id->failed-instances-transient-store [])))))) (deftest test-kill-instance (let [scheduler (create-cook-scheduler-helper) service-id "foo" test-instance {:cook/job-uuid "uuid-1" :id "foo.1A" :service-id service-id} current-time (t/now)] (with-redefs [retrieve-jobs (constantly [{:uuid "uuid-1"} {:uuid "uuid-2"} {:uuid "uuid-3"}]) t/now (constantly current-time)] (with-redefs [delete-jobs (constantly {:deploymentId 12345})] (is (= {:killed? true :message "Killed foo.1A" :result :killed :success true} (scheduler/kill-instance scheduler test-instance)))) (with-redefs [delete-jobs (constantly {})] (is (= {:killed? true :message "Killed foo.1A" :result :killed :success true} (scheduler/kill-instance scheduler test-instance)))) (with-redefs [delete-jobs (fn [_ _] (throw (ex-info "Delete error" {:status 400})))] (is (= {:killed? false :message "Unable to kill foo.1A" :result :failed :success false} (scheduler/kill-instance scheduler test-instance)))) (with-redefs [delete-jobs (constantly {}) retrieve-jobs (constantly nil)] (is (= {:message "foo does not exist!" :result :no-such-service-exists :success false} (scheduler/kill-instance scheduler test-instance))))))) (deftest test-create-instance (let [cook-api (Object.) test-user "test-user" cook-scheduler (create-cook-scheduler-helper :allowed-users #{test-user} :cook-api cook-api) service-id "foo" min-instances 4 descriptor {:service-description {"min-instances" min-instances "run-as-user" test-user} :service-id service-id}] (testing "create service - success" (let [updated-invoked-promise (promise)] (with-redefs [scheduler/service-exists? (constantly false) launch-jobs (fn [in-cook-api in-service-id _ _ _ num-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= min-instances num-instances)) true)] (is (= {:message "Created foo" :result :created :success true} (scheduler/create-service-if-new cook-scheduler descriptor))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "create service - failure" (let [updated-invoked-promise (promise)] (with-redefs [scheduler/service-exists? (constantly false) launch-jobs (fn [in-cook-api in-service-id _ _ _ num-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= min-instances num-instances)) (throw (ex-info "Failed" {})))] (is (= {:message "Unable to create foo" :result :failed :success false} (scheduler/create-service-if-new cook-scheduler descriptor))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "create service - service exists" (with-redefs [retrieve-jobs (fn [_ _ in-service-id & _] (= service-id in-service-id))] (is (scheduler/service-exists? cook-scheduler service-id)) (is (= {:message "foo already exists!" :result :already-exists :success false} (scheduler/create-service-if-new cook-scheduler descriptor))))))) (deftest test-delete-service (with-redefs [retrieve-jobs (constantly [{:uuid "uuid-1"} {:uuid "uuid-2"} {:uuid "uuid-3"}])] (let [scheduler (create-cook-scheduler-helper)] (with-redefs [delete-jobs (constantly {:deploymentId 12345})] (is (= {:message "Deleted foo" :result :deleted :success true} (scheduler/delete-service scheduler "foo")))) (with-redefs [delete-jobs (constantly {})] (is (= {:message "Deleted foo" :result :deleted :success true} (scheduler/delete-service scheduler "foo")))) (with-redefs [delete-jobs (fn [_ _] (throw (ex-info "Delete error" {:status 400})))] (is (= {:message "Unable to delete foo" :result :failed :success false} (scheduler/delete-service scheduler "foo")))) (with-redefs [delete-jobs (constantly {}) retrieve-jobs (constantly nil)] (is (= {:message "foo does not exist!" :result :no-such-service-exists :success false} (scheduler/delete-service scheduler "foo"))))))) (deftest test-scale-service (let [cook-api (Object.) cook-scheduler (create-cook-scheduler-helper :cook-api cook-api) service-id "test-service-id"] (testing "scale of service - no such service" (let [updated-invoked-promise (promise) instances 5] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) nil) launch-jobs (fn [in-cook-api in-service-id & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) true)] (is (= {:message "test-service-id does not exist!" :result :no-such-service-exists :success false} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :not-invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "scale of service - no-op" (let [updated-invoked-promise (promise) instances 5] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (for [n (range 10)] {:cook/job-uuid (str "uuid-" n) :id (str service-id "." n) :priority n :service-id service-id})) launch-jobs (fn [in-cook-api in-service-id _ _ _ extra-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= 20 extra-instances)) true)] (is (= {:message "Scaled test-service-id" :result :scaling-not-needed :success true} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :not-invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "scale of service - success" (let [updated-invoked-promise (promise) instances 30] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (for [n (range 10)] {:cook/job-uuid (str "uuid-" n) :id (str service-id "." n) :priority n :service-id service-id})) launch-jobs (fn [in-cook-api in-service-id _ _ _ extra-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= 20 extra-instances)) true)] (is (= {:message "Scaled test-service-id" :result :scaled :success true} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))) (testing "scale of service - fail" (let [updated-invoked-promise (promise) instances 30] (with-redefs [retrieve-jobs (fn [in-cook-api _ in-service-id _] (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (for [n (range 10)] {:cook/job-uuid (str "uuid-" n) :id (str service-id "." n) :priority n :service-id service-id})) launch-jobs (fn [in-cook-api in-service-id _ _ _ extra-instances & _] (deliver updated-invoked-promise :invoked) (is (= cook-api in-cook-api)) (is (= service-id in-service-id)) (is (= 20 extra-instances)) (throw (ex-info "Launch failed!" {})))] (is (= {:message "Unable to scale test-service-id" :result :failed :success false} (scheduler/scale-service cook-scheduler service-id instances false))) (is (= :invoked (deref updated-invoked-promise 0 :not-invoked)))))))) (deftest test-service-id->state (let [service-id "service-id" syncer-state-atom (atom {:last-update-time :time :service-id->health-check-context {}}) retrieve-syncer-state-fn (partial scheduler/retrieve-syncer-state @syncer-state-atom) cook-scheduler (create-cook-scheduler-helper :retrieve-syncer-state-fn retrieve-syncer-state-fn :service-id->failed-instances-transient-store (atom {service-id [:failed-instances]}))] (is (= {:failed-instances [:failed-instances] :syncer {:last-update-time :time}} (scheduler/service-id->state cook-scheduler service-id))) (is (= {:authorizer nil :service-id->failed-instances-transient-store {"service-id" [:failed-instances]} :syncer {:last-update-time :time :service-id->health-check-context {}}} (scheduler/state cook-scheduler))))) (deftest test-cook-scheduler (testing "Creating a CookScheduler" (let [valid-config {:allowed-users #{"test-user"} :authorizer {:kind :default :default {:factory-fn 'waiter.authorization/noop-authorizer}} :backend-port 7890 :cook-api {} :home-path-prefix "/home/path/" :instance-priorities {:delta 5 :max 70 :min 30} :search-interval-days 10 :scheduler-name "cook" :service-id->password-fn #(str % PI:PASSWORD:<PASSWORD>END_PI") :service-id->service-description-fn (constantly {})} cook-api (Object.) service-id->failed-instances-transient-store (atom {}) syncer-state-atom (atom {}) create-cook-scheduler-helper (fn create-cook-scheduler-helper [config] (create-cook-scheduler config cook-api service-id->failed-instances-transient-store syncer-state-atom))] (testing "should throw on invalid configuration" (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :allowed-users #{})))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :backend-port -5)))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :backend-port 0)))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :home-path-prefix nil)))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :instance-priorities {})))) (is (thrown? Throwable (create-cook-scheduler-helper (assoc valid-config :search-interval-days 0))))) (testing "should work with valid configuration" (is (instance? CookScheduler (create-cook-scheduler-helper valid-config)))) (testing "validate service - normal" (scheduler/validate-service (create-cook-scheduler-helper (assoc valid-config :service-id->service-description-fn (constantly {}))) nil)) (testing "validate service - test that image can't be set" (is (thrown? Throwable (scheduler/validate-service (create-cook-scheduler-helper (assoc valid-config :service-id->service-description-fn (constantly {"image" "twosigma/waiter-test-apps"}))) nil)))))))
[ { "context": " \"Base schema for a REDCap API request\"\n {:token HashCode128})\n\n(def ExportRecordsRequestParams\n (merge APIRe", "end": 539, "score": 0.9949520230293274, "start": 528, "tag": "PASSWORD", "value": "HashCode128" } ]
data/test/clojure/aa178f629eb9e5c7d9c0fa573edaee31a5745046core.clj
harshp8l/deep-learning-lang-detection
84
(ns bordeaux.core (:require [schema.core :as s] [org.httpkit.client :as http])) (def HashCode128 (s/both s/Str (s/pred #(= (count %) 32) 'length-of-32))) (def URL (letfn [(valid-url? [s] (try (do (java.net.URL. s) true) (catch java.net.MalformedURLException e false)))] (s/pred valid-url? 'valid-url?))) (def Format (s/enum "csv" "json" "xml")) (def APIRequestParams "Base schema for a REDCap API request" {:token HashCode128}) (def ExportRecordsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "record") (s/optional-key :format) Format (s/optional-key :type) (s/enum "flat" "eav" "record") (s/optional-key :records) [s/Str] (s/optional-key :fields) [s/Str] (s/optional-key :forms) [s/Str] ;; TODO replace spaces with underscores (s/optional-key :events) [s/Str] (s/optional-key :rawOrLabel) (s/enum "raw" "label") (s/optional-key :rawOrLabelHeaders) (s/enum "raw" "label") (s/optional-key :exportCheckboxLabel) s/Bool (s/optional-key :returnFormat) Format (s/optional-key :exportSurveyFields) s/Bool (s/optional-key :exportDataAccessGroups) s/Bool})) (def ExportReportsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "report") (s/optional-key :report_id) s/Num (s/optional-key :format) Format (s/optional-key :returnFormat) Format (s/optional-key :rawOrLabel) (s/enum "raw" "label") (s/optional-key :exportCheckboxLabel) s/Bool})) (def ImportRecordsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "record") (s/optional-key :format) Format (s/optional-key :type) (s/enum "flat" "eav" "record") (s/optional-key :overwriteBehavior) (s/enum "normal" "overwrite") (s/optional-key :data) s/Any (s/optional-key :dateFormat) (s/enum "MDY" "DMY" "YMD") (s/optional-key :returnContent) [s/Str] (s/optional-key :returnFormat) Format})) (def ExportMetadataRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "metadata") (s/optional-key :format) Format (s/optional-key :fields) [s/Str] (s/optional-key :forms) [s/Str] (s/optional-key :returnFormat) Format})) (def ExportFileRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "file") (s/optional-key :action) (s/eq "export") (s/optional-key :record) s/Num (s/optional-key :field) s/Str (s/optional-key :event) s/Str (s/optional-key :returnFormat) Format})) (def ImportFileRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "file") (s/optional-key :action) (s/eq "import") (s/optional-key :record) s/Str (s/optional-key :field) s/Str (s/optional-key :event) s/Str (s/optional-key :file) s/Any})) (def DeleteFileRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "file") (s/optional-key :action) (s/eq "delete") (s/optional-key :record) s/Str (s/optional-key :field) s/Str (s/optional-key :event) s/Str (s/optional-key :returnFormat) Format})) (def ExportInstrumentsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "instrument") (s/optional-key :format) Format})) (def ExportEventsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "event") (s/optional-key :format) Format (s/optional-key :arms) [s/Num] (s/optional-key :returnformat) Format})) (def ExportArmsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "arm") (s/optional-key :format) Format (s/optional-key :arms) [s/Num] (s/optional-key :returnFormat) Format})) (def ExportInstrumentEventMappingsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "formEventMapping") (s/optional-key :format) Format (s/optional-key :arms) [s/Num] (s/optional-key :returnFormat) Format})) (def ExportUsersRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "user") (s/optional-key :format) Format (s/optional-key :returnFormat) Format})) (def ExportREDCapVersionRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "version")})) (defn api-request [url params] (http/post url {:form-params params})) (s/defn export-records :- s/Any "Export a set of records for a project" [url :- URL params :- ExportRecordsRequestParams] (let [default-params {:content "record" :format "xml" :type "flat"}] (api-request url (merge default-params params)))) (s/defn import-records :- s/Any "Import a set of records for a project." [url :- URL params :- ImportRecordsRequestParams] (let [default-params {:content "record" :format "xml" :overwriteBehavior "normal"}] (api-request url (merge default-params params)))) (s/defn export-reports :- s/Any "Export the data set of a report created on a project's 'Data Exports, Reports, and Stats' page." [url :- URL params :- ExportReportsRequestParams] (let [default-params {:content "report" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-metadata :- s/Any "Export the metadata for a project" [url :- URL params :- ExportMetadataRequestParams] (let [default-params {:content "metadata" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-file :- s/Any "Export a document that has been attached to an individual record." [url :- URL params :- ExportFileRequestParams] (let [default-params {:content "file" :action "export"}] (api-request url (merge default-params params)))) (s/defn import-file :- s/Any "Import a document that will be attached to an individual record." [url :- URL params :- ImportFileRequestParams] (let [default-params {:content "file" :action "import"}] (api-request url (merge default-params params)))) (s/defn delete-file :- s/Any "Delete a document that has been attached to an invidual record." [url :- URL params :- DeleteFileRequestParams] (let [default-params {:content "file" :action "delete"}] (api-request url (merge default-params params)))) (s/defn export-instruments :- s/Any "Export a list of the data collection instruments for a project." [url :- URL params :- ExportInstrumentsRequestParams] (let [default-params {:content "instrument" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-events :- s/Any "Export the events for a project." [url :- URL params :- ExportEventsRequestParams] (let [default-params {:content "event" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-arms :- s/Any "Export the arms for a project." [url :- URL params :- ExportArmsRequestParams] (let [default-params {:content "arm" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-instrument-event-mappings :- s/Any "Export the instrument-event mappings for a project." [url :- URL params :- ExportInstrumentEventMappingsRequestParams] (let [default-params {:content "formEventMapping" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-users :- s/Any "Export the users for a project." [url :- URL params :- ExportUsersRequestParams] (let [default-params {:content "user" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-redcap-version :- s/Any "Returns the current REDCap version number." [url :- URL params :- ExportREDCapVersionRequestParams] (let [default-params {:content "version"}] (api-request url (merge default-params params))))
8559
(ns bordeaux.core (:require [schema.core :as s] [org.httpkit.client :as http])) (def HashCode128 (s/both s/Str (s/pred #(= (count %) 32) 'length-of-32))) (def URL (letfn [(valid-url? [s] (try (do (java.net.URL. s) true) (catch java.net.MalformedURLException e false)))] (s/pred valid-url? 'valid-url?))) (def Format (s/enum "csv" "json" "xml")) (def APIRequestParams "Base schema for a REDCap API request" {:token <PASSWORD>}) (def ExportRecordsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "record") (s/optional-key :format) Format (s/optional-key :type) (s/enum "flat" "eav" "record") (s/optional-key :records) [s/Str] (s/optional-key :fields) [s/Str] (s/optional-key :forms) [s/Str] ;; TODO replace spaces with underscores (s/optional-key :events) [s/Str] (s/optional-key :rawOrLabel) (s/enum "raw" "label") (s/optional-key :rawOrLabelHeaders) (s/enum "raw" "label") (s/optional-key :exportCheckboxLabel) s/Bool (s/optional-key :returnFormat) Format (s/optional-key :exportSurveyFields) s/Bool (s/optional-key :exportDataAccessGroups) s/Bool})) (def ExportReportsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "report") (s/optional-key :report_id) s/Num (s/optional-key :format) Format (s/optional-key :returnFormat) Format (s/optional-key :rawOrLabel) (s/enum "raw" "label") (s/optional-key :exportCheckboxLabel) s/Bool})) (def ImportRecordsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "record") (s/optional-key :format) Format (s/optional-key :type) (s/enum "flat" "eav" "record") (s/optional-key :overwriteBehavior) (s/enum "normal" "overwrite") (s/optional-key :data) s/Any (s/optional-key :dateFormat) (s/enum "MDY" "DMY" "YMD") (s/optional-key :returnContent) [s/Str] (s/optional-key :returnFormat) Format})) (def ExportMetadataRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "metadata") (s/optional-key :format) Format (s/optional-key :fields) [s/Str] (s/optional-key :forms) [s/Str] (s/optional-key :returnFormat) Format})) (def ExportFileRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "file") (s/optional-key :action) (s/eq "export") (s/optional-key :record) s/Num (s/optional-key :field) s/Str (s/optional-key :event) s/Str (s/optional-key :returnFormat) Format})) (def ImportFileRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "file") (s/optional-key :action) (s/eq "import") (s/optional-key :record) s/Str (s/optional-key :field) s/Str (s/optional-key :event) s/Str (s/optional-key :file) s/Any})) (def DeleteFileRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "file") (s/optional-key :action) (s/eq "delete") (s/optional-key :record) s/Str (s/optional-key :field) s/Str (s/optional-key :event) s/Str (s/optional-key :returnFormat) Format})) (def ExportInstrumentsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "instrument") (s/optional-key :format) Format})) (def ExportEventsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "event") (s/optional-key :format) Format (s/optional-key :arms) [s/Num] (s/optional-key :returnformat) Format})) (def ExportArmsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "arm") (s/optional-key :format) Format (s/optional-key :arms) [s/Num] (s/optional-key :returnFormat) Format})) (def ExportInstrumentEventMappingsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "formEventMapping") (s/optional-key :format) Format (s/optional-key :arms) [s/Num] (s/optional-key :returnFormat) Format})) (def ExportUsersRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "user") (s/optional-key :format) Format (s/optional-key :returnFormat) Format})) (def ExportREDCapVersionRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "version")})) (defn api-request [url params] (http/post url {:form-params params})) (s/defn export-records :- s/Any "Export a set of records for a project" [url :- URL params :- ExportRecordsRequestParams] (let [default-params {:content "record" :format "xml" :type "flat"}] (api-request url (merge default-params params)))) (s/defn import-records :- s/Any "Import a set of records for a project." [url :- URL params :- ImportRecordsRequestParams] (let [default-params {:content "record" :format "xml" :overwriteBehavior "normal"}] (api-request url (merge default-params params)))) (s/defn export-reports :- s/Any "Export the data set of a report created on a project's 'Data Exports, Reports, and Stats' page." [url :- URL params :- ExportReportsRequestParams] (let [default-params {:content "report" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-metadata :- s/Any "Export the metadata for a project" [url :- URL params :- ExportMetadataRequestParams] (let [default-params {:content "metadata" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-file :- s/Any "Export a document that has been attached to an individual record." [url :- URL params :- ExportFileRequestParams] (let [default-params {:content "file" :action "export"}] (api-request url (merge default-params params)))) (s/defn import-file :- s/Any "Import a document that will be attached to an individual record." [url :- URL params :- ImportFileRequestParams] (let [default-params {:content "file" :action "import"}] (api-request url (merge default-params params)))) (s/defn delete-file :- s/Any "Delete a document that has been attached to an invidual record." [url :- URL params :- DeleteFileRequestParams] (let [default-params {:content "file" :action "delete"}] (api-request url (merge default-params params)))) (s/defn export-instruments :- s/Any "Export a list of the data collection instruments for a project." [url :- URL params :- ExportInstrumentsRequestParams] (let [default-params {:content "instrument" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-events :- s/Any "Export the events for a project." [url :- URL params :- ExportEventsRequestParams] (let [default-params {:content "event" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-arms :- s/Any "Export the arms for a project." [url :- URL params :- ExportArmsRequestParams] (let [default-params {:content "arm" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-instrument-event-mappings :- s/Any "Export the instrument-event mappings for a project." [url :- URL params :- ExportInstrumentEventMappingsRequestParams] (let [default-params {:content "formEventMapping" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-users :- s/Any "Export the users for a project." [url :- URL params :- ExportUsersRequestParams] (let [default-params {:content "user" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-redcap-version :- s/Any "Returns the current REDCap version number." [url :- URL params :- ExportREDCapVersionRequestParams] (let [default-params {:content "version"}] (api-request url (merge default-params params))))
true
(ns bordeaux.core (:require [schema.core :as s] [org.httpkit.client :as http])) (def HashCode128 (s/both s/Str (s/pred #(= (count %) 32) 'length-of-32))) (def URL (letfn [(valid-url? [s] (try (do (java.net.URL. s) true) (catch java.net.MalformedURLException e false)))] (s/pred valid-url? 'valid-url?))) (def Format (s/enum "csv" "json" "xml")) (def APIRequestParams "Base schema for a REDCap API request" {:token PI:PASSWORD:<PASSWORD>END_PI}) (def ExportRecordsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "record") (s/optional-key :format) Format (s/optional-key :type) (s/enum "flat" "eav" "record") (s/optional-key :records) [s/Str] (s/optional-key :fields) [s/Str] (s/optional-key :forms) [s/Str] ;; TODO replace spaces with underscores (s/optional-key :events) [s/Str] (s/optional-key :rawOrLabel) (s/enum "raw" "label") (s/optional-key :rawOrLabelHeaders) (s/enum "raw" "label") (s/optional-key :exportCheckboxLabel) s/Bool (s/optional-key :returnFormat) Format (s/optional-key :exportSurveyFields) s/Bool (s/optional-key :exportDataAccessGroups) s/Bool})) (def ExportReportsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "report") (s/optional-key :report_id) s/Num (s/optional-key :format) Format (s/optional-key :returnFormat) Format (s/optional-key :rawOrLabel) (s/enum "raw" "label") (s/optional-key :exportCheckboxLabel) s/Bool})) (def ImportRecordsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "record") (s/optional-key :format) Format (s/optional-key :type) (s/enum "flat" "eav" "record") (s/optional-key :overwriteBehavior) (s/enum "normal" "overwrite") (s/optional-key :data) s/Any (s/optional-key :dateFormat) (s/enum "MDY" "DMY" "YMD") (s/optional-key :returnContent) [s/Str] (s/optional-key :returnFormat) Format})) (def ExportMetadataRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "metadata") (s/optional-key :format) Format (s/optional-key :fields) [s/Str] (s/optional-key :forms) [s/Str] (s/optional-key :returnFormat) Format})) (def ExportFileRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "file") (s/optional-key :action) (s/eq "export") (s/optional-key :record) s/Num (s/optional-key :field) s/Str (s/optional-key :event) s/Str (s/optional-key :returnFormat) Format})) (def ImportFileRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "file") (s/optional-key :action) (s/eq "import") (s/optional-key :record) s/Str (s/optional-key :field) s/Str (s/optional-key :event) s/Str (s/optional-key :file) s/Any})) (def DeleteFileRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "file") (s/optional-key :action) (s/eq "delete") (s/optional-key :record) s/Str (s/optional-key :field) s/Str (s/optional-key :event) s/Str (s/optional-key :returnFormat) Format})) (def ExportInstrumentsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "instrument") (s/optional-key :format) Format})) (def ExportEventsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "event") (s/optional-key :format) Format (s/optional-key :arms) [s/Num] (s/optional-key :returnformat) Format})) (def ExportArmsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "arm") (s/optional-key :format) Format (s/optional-key :arms) [s/Num] (s/optional-key :returnFormat) Format})) (def ExportInstrumentEventMappingsRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "formEventMapping") (s/optional-key :format) Format (s/optional-key :arms) [s/Num] (s/optional-key :returnFormat) Format})) (def ExportUsersRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "user") (s/optional-key :format) Format (s/optional-key :returnFormat) Format})) (def ExportREDCapVersionRequestParams (merge APIRequestParams {(s/optional-key :content) (s/eq "version")})) (defn api-request [url params] (http/post url {:form-params params})) (s/defn export-records :- s/Any "Export a set of records for a project" [url :- URL params :- ExportRecordsRequestParams] (let [default-params {:content "record" :format "xml" :type "flat"}] (api-request url (merge default-params params)))) (s/defn import-records :- s/Any "Import a set of records for a project." [url :- URL params :- ImportRecordsRequestParams] (let [default-params {:content "record" :format "xml" :overwriteBehavior "normal"}] (api-request url (merge default-params params)))) (s/defn export-reports :- s/Any "Export the data set of a report created on a project's 'Data Exports, Reports, and Stats' page." [url :- URL params :- ExportReportsRequestParams] (let [default-params {:content "report" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-metadata :- s/Any "Export the metadata for a project" [url :- URL params :- ExportMetadataRequestParams] (let [default-params {:content "metadata" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-file :- s/Any "Export a document that has been attached to an individual record." [url :- URL params :- ExportFileRequestParams] (let [default-params {:content "file" :action "export"}] (api-request url (merge default-params params)))) (s/defn import-file :- s/Any "Import a document that will be attached to an individual record." [url :- URL params :- ImportFileRequestParams] (let [default-params {:content "file" :action "import"}] (api-request url (merge default-params params)))) (s/defn delete-file :- s/Any "Delete a document that has been attached to an invidual record." [url :- URL params :- DeleteFileRequestParams] (let [default-params {:content "file" :action "delete"}] (api-request url (merge default-params params)))) (s/defn export-instruments :- s/Any "Export a list of the data collection instruments for a project." [url :- URL params :- ExportInstrumentsRequestParams] (let [default-params {:content "instrument" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-events :- s/Any "Export the events for a project." [url :- URL params :- ExportEventsRequestParams] (let [default-params {:content "event" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-arms :- s/Any "Export the arms for a project." [url :- URL params :- ExportArmsRequestParams] (let [default-params {:content "arm" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-instrument-event-mappings :- s/Any "Export the instrument-event mappings for a project." [url :- URL params :- ExportInstrumentEventMappingsRequestParams] (let [default-params {:content "formEventMapping" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-users :- s/Any "Export the users for a project." [url :- URL params :- ExportUsersRequestParams] (let [default-params {:content "user" :format "xml"}] (api-request url (merge default-params params)))) (s/defn export-redcap-version :- s/Any "Returns the current REDCap version number." [url :- URL params :- ExportREDCapVersionRequestParams] (let [default-params {:content "version"}] (api-request url (merge default-params params))))
[ { "context": ")\n;;=> {:crux.db/id :manifest,\n;; :pilot-name \"Johanna\",\n;; :id/rocket \"SB002-sol\",\n;; :id/employe", "end": 2768, "score": 0.9991089701652527, "start": 2761, "tag": "NAME", "value": "Johanna" } ]
tutorials.crux/src/tutorials/crux/pluto.clj
johantonelli/tutorials
1
(ns tutorials.crux.pluto (:require [crux.api :as crux] [tutorials.crux.earth :refer [manifest]])) ;; Start node (def node (crux/start-node {})) ;; tag::submit[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :commodity/Pu :common-name "Plutonium" :type :element/metal :density 19.816 :radioactive true}] [:crux.tx/put {:crux.db/id :commodity/N :common-name "Nitrogen" :type :element/gas :density 1.2506 :radioactive false}] [:crux.tx/put {:crux.db/id :commodity/CH4 :common-name "Methane" :type :molecule/gas :density 0.717 :radioactive false}]]) ;;=> #:crux.tx{:tx-id 0, :tx-time #inst "2020-06-18T14:11:51.087-00:00"} ;; end::submit[] ;; Submit valid time data ;; tag::submit-valid[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 21} #inst "2115-02-13T18"] ;; valid-time [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 23} #inst "2115-02-14T18"] [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 22.2} #inst "2115-02-15T18"] [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 24} #inst "2115-02-18T18"] [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 24.9} #inst "2115-02-19T18"]]) ;;=> #:crux.tx{:tx-id 1, :tx-time #inst "2020-06-18T14:14:08.347-00:00"} ;; end::submit-valid[] ;; tag::submit-more[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :stock/N :commod :commodity/N :weight-ton 3} #inst "2115-02-13T18" ;; start valid-time #inst "2115-02-19T18"] ;; end valid-time [:crux.tx/put {:crux.db/id :stock/CH4 :commod :commodity/CH4 :weight-ton 92} #inst "2115-02-15T18" #inst "2115-02-19T18"]]) ;;=> #:crux.tx{:tx-id 2, :tx-time #inst "2020-06-18T14:15:19.716-00:00"} ;; end::submit-more[] ;; tag::check[] (crux/entity (crux/db node #inst "2115-02-14") :stock/Pu) ;;=> {:crux.db/id :stock/Pu, :commod :commodity/Pu, :weight-ton 21} (crux/entity (crux/db node #inst "2115-02-18") :stock/Pu) ;;=> {:crux.db/id :stock/Pu, :commod :commodity/Pu, :weight-ton 22.2} ;; end::check[] ;; tag::easy-ingest[] (defn easy-ingest "Uses Crux put transaction to add a vector of documents to a specified node" [node docs] (crux/submit-tx node (mapv (fn [doc] [:crux.tx/put doc]) docs))) ;; end::easy-ingest[] ;; tag::manifest[] (crux/submit-tx node [[:crux.tx/put (assoc manifest :badges ["SETUP" "PUT"])]]) ;;=> #:crux.tx{:tx-id 3, :tx-time #inst "2020-06-18T14:20:31.602-00:00"} ;; end::manifest[] ;; tag::check-manifest[] (crux/entity (crux/db node) :manifest) ;;=> {:crux.db/id :manifest, ;; :pilot-name "Johanna", ;; :id/rocket "SB002-sol", ;; :id/employee "22910x2", ;; :badges ["SETUP" "PUT"], ;; :cargo ["stereo" "gold fish" "slippers" "secret note"]} ;; end::check-manifest[]
108623
(ns tutorials.crux.pluto (:require [crux.api :as crux] [tutorials.crux.earth :refer [manifest]])) ;; Start node (def node (crux/start-node {})) ;; tag::submit[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :commodity/Pu :common-name "Plutonium" :type :element/metal :density 19.816 :radioactive true}] [:crux.tx/put {:crux.db/id :commodity/N :common-name "Nitrogen" :type :element/gas :density 1.2506 :radioactive false}] [:crux.tx/put {:crux.db/id :commodity/CH4 :common-name "Methane" :type :molecule/gas :density 0.717 :radioactive false}]]) ;;=> #:crux.tx{:tx-id 0, :tx-time #inst "2020-06-18T14:11:51.087-00:00"} ;; end::submit[] ;; Submit valid time data ;; tag::submit-valid[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 21} #inst "2115-02-13T18"] ;; valid-time [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 23} #inst "2115-02-14T18"] [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 22.2} #inst "2115-02-15T18"] [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 24} #inst "2115-02-18T18"] [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 24.9} #inst "2115-02-19T18"]]) ;;=> #:crux.tx{:tx-id 1, :tx-time #inst "2020-06-18T14:14:08.347-00:00"} ;; end::submit-valid[] ;; tag::submit-more[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :stock/N :commod :commodity/N :weight-ton 3} #inst "2115-02-13T18" ;; start valid-time #inst "2115-02-19T18"] ;; end valid-time [:crux.tx/put {:crux.db/id :stock/CH4 :commod :commodity/CH4 :weight-ton 92} #inst "2115-02-15T18" #inst "2115-02-19T18"]]) ;;=> #:crux.tx{:tx-id 2, :tx-time #inst "2020-06-18T14:15:19.716-00:00"} ;; end::submit-more[] ;; tag::check[] (crux/entity (crux/db node #inst "2115-02-14") :stock/Pu) ;;=> {:crux.db/id :stock/Pu, :commod :commodity/Pu, :weight-ton 21} (crux/entity (crux/db node #inst "2115-02-18") :stock/Pu) ;;=> {:crux.db/id :stock/Pu, :commod :commodity/Pu, :weight-ton 22.2} ;; end::check[] ;; tag::easy-ingest[] (defn easy-ingest "Uses Crux put transaction to add a vector of documents to a specified node" [node docs] (crux/submit-tx node (mapv (fn [doc] [:crux.tx/put doc]) docs))) ;; end::easy-ingest[] ;; tag::manifest[] (crux/submit-tx node [[:crux.tx/put (assoc manifest :badges ["SETUP" "PUT"])]]) ;;=> #:crux.tx{:tx-id 3, :tx-time #inst "2020-06-18T14:20:31.602-00:00"} ;; end::manifest[] ;; tag::check-manifest[] (crux/entity (crux/db node) :manifest) ;;=> {:crux.db/id :manifest, ;; :pilot-name "<NAME>", ;; :id/rocket "SB002-sol", ;; :id/employee "22910x2", ;; :badges ["SETUP" "PUT"], ;; :cargo ["stereo" "gold fish" "slippers" "secret note"]} ;; end::check-manifest[]
true
(ns tutorials.crux.pluto (:require [crux.api :as crux] [tutorials.crux.earth :refer [manifest]])) ;; Start node (def node (crux/start-node {})) ;; tag::submit[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :commodity/Pu :common-name "Plutonium" :type :element/metal :density 19.816 :radioactive true}] [:crux.tx/put {:crux.db/id :commodity/N :common-name "Nitrogen" :type :element/gas :density 1.2506 :radioactive false}] [:crux.tx/put {:crux.db/id :commodity/CH4 :common-name "Methane" :type :molecule/gas :density 0.717 :radioactive false}]]) ;;=> #:crux.tx{:tx-id 0, :tx-time #inst "2020-06-18T14:11:51.087-00:00"} ;; end::submit[] ;; Submit valid time data ;; tag::submit-valid[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 21} #inst "2115-02-13T18"] ;; valid-time [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 23} #inst "2115-02-14T18"] [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 22.2} #inst "2115-02-15T18"] [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 24} #inst "2115-02-18T18"] [:crux.tx/put {:crux.db/id :stock/Pu :commod :commodity/Pu :weight-ton 24.9} #inst "2115-02-19T18"]]) ;;=> #:crux.tx{:tx-id 1, :tx-time #inst "2020-06-18T14:14:08.347-00:00"} ;; end::submit-valid[] ;; tag::submit-more[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :stock/N :commod :commodity/N :weight-ton 3} #inst "2115-02-13T18" ;; start valid-time #inst "2115-02-19T18"] ;; end valid-time [:crux.tx/put {:crux.db/id :stock/CH4 :commod :commodity/CH4 :weight-ton 92} #inst "2115-02-15T18" #inst "2115-02-19T18"]]) ;;=> #:crux.tx{:tx-id 2, :tx-time #inst "2020-06-18T14:15:19.716-00:00"} ;; end::submit-more[] ;; tag::check[] (crux/entity (crux/db node #inst "2115-02-14") :stock/Pu) ;;=> {:crux.db/id :stock/Pu, :commod :commodity/Pu, :weight-ton 21} (crux/entity (crux/db node #inst "2115-02-18") :stock/Pu) ;;=> {:crux.db/id :stock/Pu, :commod :commodity/Pu, :weight-ton 22.2} ;; end::check[] ;; tag::easy-ingest[] (defn easy-ingest "Uses Crux put transaction to add a vector of documents to a specified node" [node docs] (crux/submit-tx node (mapv (fn [doc] [:crux.tx/put doc]) docs))) ;; end::easy-ingest[] ;; tag::manifest[] (crux/submit-tx node [[:crux.tx/put (assoc manifest :badges ["SETUP" "PUT"])]]) ;;=> #:crux.tx{:tx-id 3, :tx-time #inst "2020-06-18T14:20:31.602-00:00"} ;; end::manifest[] ;; tag::check-manifest[] (crux/entity (crux/db node) :manifest) ;;=> {:crux.db/id :manifest, ;; :pilot-name "PI:NAME:<NAME>END_PI", ;; :id/rocket "SB002-sol", ;; :id/employee "22910x2", ;; :badges ["SETUP" "PUT"], ;; :cargo ["stereo" "gold fish" "slippers" "secret note"]} ;; end::check-manifest[]
[ { "context": " [1 2 3 4]))\n 4)))\n\n; TODO(Richo): The functions in this namespace rely on the pro", "end": 460, "score": 0.9945526123046875, "start": 455, "tag": "NAME", "value": "Richo" }, { "context": "ram global]\n (if (contains? global :name) ; TODO(Richo): This sucks!\n (index-of-variable program (:na", "end": 2571, "score": 0.5246124863624573, "start": 2566, "tag": "NAME", "value": "Richo" } ]
middleware/server/src/middleware/compiler/utils/program.clj
kristiank/PhysicalBits
0
(ns middleware.compiler.utils.program (:require [middleware.compiler.emitter :as emit])) (defn value-size "Return the number of bytes necessary to encode this value. If the value is negative or float then the size is 4 bytes. Also, the max number of bytes is 4." [value] (if (or (float? value) (neg? value)) 4 (or (first (filter (fn [size] (< value (Math/pow 2 (* 8 size)))) [1 2 3 4])) 4))) ; TODO(Richo): The functions in this namespace rely on the program having its globals ; sorted. That means that I need to remember to call this function before using any ; of them. Of course, I should just change the compiler to emit the program with its ; variables already sorted and avoid this problem. However, in order to do that I need ; to fix a lot of tests first, and it's kind of a pain in the ass. So first, I will ; make it work by calling this function in the correct places and then I'll refactor ; the compiler. (defn sort-globals [program] (let [sorted-globals (sort-by (fn [global] (assoc global :size (value-size (:value global)))) (fn [{a-name :name, a-value :value, a-size :size} {b-name :name, b-value :value, b-size :size}] (if (= a-size b-size) (if (= a-value b-value) (compare (or a-name "") (or b-name "")) (< a-value b-value)) (< a-size b-size))) (:globals program))] (assoc program :globals (vec sorted-globals)))) (def default-globals "This values are *always* first in the global list, whether they are used or not. The VM knows about this already so we don't need to encode them." (map emit/constant [0 1 -1])) (defn all-globals [program] "Returns all the globals in the program in the correct order" (concat default-globals (filter (complement (set default-globals)) (:globals program)))) (defn index-of-constant [program value] (.indexOf (all-globals program) (emit/constant value))) (defn index-of-variable ([program name] (.indexOf (map :name (all-globals program)) name)) ([program name not-found] (let [index (index-of-variable program name)] (if (= -1 index) not-found index)))) (defn index-of-global [program global] (if (contains? global :name) ; TODO(Richo): This sucks! (index-of-variable program (:name global)) (index-of-constant program (:value global)))) (defn index-of-local [script variable] (.indexOf (map :name (concat (:arguments script) (:locals script))) (:name variable)))
79840
(ns middleware.compiler.utils.program (:require [middleware.compiler.emitter :as emit])) (defn value-size "Return the number of bytes necessary to encode this value. If the value is negative or float then the size is 4 bytes. Also, the max number of bytes is 4." [value] (if (or (float? value) (neg? value)) 4 (or (first (filter (fn [size] (< value (Math/pow 2 (* 8 size)))) [1 2 3 4])) 4))) ; TODO(<NAME>): The functions in this namespace rely on the program having its globals ; sorted. That means that I need to remember to call this function before using any ; of them. Of course, I should just change the compiler to emit the program with its ; variables already sorted and avoid this problem. However, in order to do that I need ; to fix a lot of tests first, and it's kind of a pain in the ass. So first, I will ; make it work by calling this function in the correct places and then I'll refactor ; the compiler. (defn sort-globals [program] (let [sorted-globals (sort-by (fn [global] (assoc global :size (value-size (:value global)))) (fn [{a-name :name, a-value :value, a-size :size} {b-name :name, b-value :value, b-size :size}] (if (= a-size b-size) (if (= a-value b-value) (compare (or a-name "") (or b-name "")) (< a-value b-value)) (< a-size b-size))) (:globals program))] (assoc program :globals (vec sorted-globals)))) (def default-globals "This values are *always* first in the global list, whether they are used or not. The VM knows about this already so we don't need to encode them." (map emit/constant [0 1 -1])) (defn all-globals [program] "Returns all the globals in the program in the correct order" (concat default-globals (filter (complement (set default-globals)) (:globals program)))) (defn index-of-constant [program value] (.indexOf (all-globals program) (emit/constant value))) (defn index-of-variable ([program name] (.indexOf (map :name (all-globals program)) name)) ([program name not-found] (let [index (index-of-variable program name)] (if (= -1 index) not-found index)))) (defn index-of-global [program global] (if (contains? global :name) ; TODO(<NAME>): This sucks! (index-of-variable program (:name global)) (index-of-constant program (:value global)))) (defn index-of-local [script variable] (.indexOf (map :name (concat (:arguments script) (:locals script))) (:name variable)))
true
(ns middleware.compiler.utils.program (:require [middleware.compiler.emitter :as emit])) (defn value-size "Return the number of bytes necessary to encode this value. If the value is negative or float then the size is 4 bytes. Also, the max number of bytes is 4." [value] (if (or (float? value) (neg? value)) 4 (or (first (filter (fn [size] (< value (Math/pow 2 (* 8 size)))) [1 2 3 4])) 4))) ; TODO(PI:NAME:<NAME>END_PI): The functions in this namespace rely on the program having its globals ; sorted. That means that I need to remember to call this function before using any ; of them. Of course, I should just change the compiler to emit the program with its ; variables already sorted and avoid this problem. However, in order to do that I need ; to fix a lot of tests first, and it's kind of a pain in the ass. So first, I will ; make it work by calling this function in the correct places and then I'll refactor ; the compiler. (defn sort-globals [program] (let [sorted-globals (sort-by (fn [global] (assoc global :size (value-size (:value global)))) (fn [{a-name :name, a-value :value, a-size :size} {b-name :name, b-value :value, b-size :size}] (if (= a-size b-size) (if (= a-value b-value) (compare (or a-name "") (or b-name "")) (< a-value b-value)) (< a-size b-size))) (:globals program))] (assoc program :globals (vec sorted-globals)))) (def default-globals "This values are *always* first in the global list, whether they are used or not. The VM knows about this already so we don't need to encode them." (map emit/constant [0 1 -1])) (defn all-globals [program] "Returns all the globals in the program in the correct order" (concat default-globals (filter (complement (set default-globals)) (:globals program)))) (defn index-of-constant [program value] (.indexOf (all-globals program) (emit/constant value))) (defn index-of-variable ([program name] (.indexOf (map :name (all-globals program)) name)) ([program name not-found] (let [index (index-of-variable program name)] (if (= -1 index) not-found index)))) (defn index-of-global [program global] (if (contains? global :name) ; TODO(PI:NAME:<NAME>END_PI): This sucks! (index-of-variable program (:name global)) (index-of-constant program (:value global)))) (defn index-of-local [script variable] (.indexOf (map :name (concat (:arguments script) (:locals script))) (:name variable)))
[ { "context": "(ns effectivejava.find ^{:author \"Federico Tomassetti\"\n :doc \"This namespace contains methods t", "end": 53, "score": 0.9998680949211121, "start": 34, "tag": "NAME", "value": "Federico Tomassetti" } ]
src/effectivejava/find.clj
davidor/effectivejava
555
(ns effectivejava.find ^{:author "Federico Tomassetti" :doc "This namespace contains methods to find elements in a collection of compilation units"} (:use [effectivejava.model.protocols]) (:use [effectivejava.model.javaparser]) (:use [effectivejava.javaparser.navigation]) (:use [effectivejava.operations]) (:use [effectivejava.itemsOnLifecycle]) (:use [effectivejava.symbol_solver.type_solver]) (:use [effectivejava.symbol_solver.scope]) (:use [effectivejava.utils]) (:require [instaparse.core :as insta]) (:import [effectivejava.operations Operation])) (defn type-exact-match? [type-ref1 type-ref2] (and (= (nil? type-ref1) (nil? type-ref2)) (if (or (nil? type-ref1) (nil? type-ref2)) ; if we have some nulls we do not want to perform the other checks ; just the previous check will count (both of them have to be nil) true (and (= (array? type-ref1) (array? type-ref2)) (= (primitive? type-ref1) (primitive? type-ref2)) (= (reference-type? type-ref1) (reference-type? type-ref2)) ; if the type is primitive the typeName must be the same (or (not (primitive? type-ref1)) (not (primitive? type-ref2)) (= (typeName type-ref1) (typeName type-ref2))) (or (not (reference-type? type-ref1)) (not (reference-type? type-ref2)) (let [referred-type1 (solveClass (context type-ref1) nil (typeName type-ref1)) referred-type2 (solveClass (context type-ref2) nil (typeName type-ref2))] ; unresolved types do not match (and referred-type1 referred-type2 (= referred-type1 referred-type2)))) (or (and (nil? (baseType type-ref1)) (nil? (baseType type-ref2))) (and (baseType type-ref1) (baseType type-ref2) (type-exact-match? (baseType type-ref1) (baseType type-ref2)))))))) (defn param-match-type? [pair] (let [[param expected-type] pair paramType (.getType param)] (type-exact-match? paramType expected-type))) (defn method-match-exactly-parameters? [param-expected-types method] (let [params (.getParameters method) pairs (map vector params param-expected-types)] (and (= (count params) (count param-expected-types)) (every? param-match-type? pairs)))) (defn find-methods-by-name "Find all the methods in the given CUs which has the given name" [cus name] (let [ all-types (flatten (map allTypes cus)) all-methods (flatten (map getMethods all-types)) methods (filter (fn [m] (= name (.getName m))) all-methods)] methods)) (defn find-methods-by-qname "Find all the methods in the given CUs which has the given QName name (e.g., japa.parser.ast.Node.equals)" [cus name] (let [ all-types (flatten (map allTypes cus)) all-methods (flatten (map getMethods all-types)) methods (filter (fn [m] (= name (getQName m))) all-methods)] methods)) (defn find-methods-by-signature "Find all the methods in the given CUs which has the given name and have parameter types exactly equals to the one given" [cus name param-types] (let [ methods (find-methods-by-name cus name) methods' (filter (partial method-match-exactly-parameters? param-types) methods)] methods'))
69284
(ns effectivejava.find ^{:author "<NAME>" :doc "This namespace contains methods to find elements in a collection of compilation units"} (:use [effectivejava.model.protocols]) (:use [effectivejava.model.javaparser]) (:use [effectivejava.javaparser.navigation]) (:use [effectivejava.operations]) (:use [effectivejava.itemsOnLifecycle]) (:use [effectivejava.symbol_solver.type_solver]) (:use [effectivejava.symbol_solver.scope]) (:use [effectivejava.utils]) (:require [instaparse.core :as insta]) (:import [effectivejava.operations Operation])) (defn type-exact-match? [type-ref1 type-ref2] (and (= (nil? type-ref1) (nil? type-ref2)) (if (or (nil? type-ref1) (nil? type-ref2)) ; if we have some nulls we do not want to perform the other checks ; just the previous check will count (both of them have to be nil) true (and (= (array? type-ref1) (array? type-ref2)) (= (primitive? type-ref1) (primitive? type-ref2)) (= (reference-type? type-ref1) (reference-type? type-ref2)) ; if the type is primitive the typeName must be the same (or (not (primitive? type-ref1)) (not (primitive? type-ref2)) (= (typeName type-ref1) (typeName type-ref2))) (or (not (reference-type? type-ref1)) (not (reference-type? type-ref2)) (let [referred-type1 (solveClass (context type-ref1) nil (typeName type-ref1)) referred-type2 (solveClass (context type-ref2) nil (typeName type-ref2))] ; unresolved types do not match (and referred-type1 referred-type2 (= referred-type1 referred-type2)))) (or (and (nil? (baseType type-ref1)) (nil? (baseType type-ref2))) (and (baseType type-ref1) (baseType type-ref2) (type-exact-match? (baseType type-ref1) (baseType type-ref2)))))))) (defn param-match-type? [pair] (let [[param expected-type] pair paramType (.getType param)] (type-exact-match? paramType expected-type))) (defn method-match-exactly-parameters? [param-expected-types method] (let [params (.getParameters method) pairs (map vector params param-expected-types)] (and (= (count params) (count param-expected-types)) (every? param-match-type? pairs)))) (defn find-methods-by-name "Find all the methods in the given CUs which has the given name" [cus name] (let [ all-types (flatten (map allTypes cus)) all-methods (flatten (map getMethods all-types)) methods (filter (fn [m] (= name (.getName m))) all-methods)] methods)) (defn find-methods-by-qname "Find all the methods in the given CUs which has the given QName name (e.g., japa.parser.ast.Node.equals)" [cus name] (let [ all-types (flatten (map allTypes cus)) all-methods (flatten (map getMethods all-types)) methods (filter (fn [m] (= name (getQName m))) all-methods)] methods)) (defn find-methods-by-signature "Find all the methods in the given CUs which has the given name and have parameter types exactly equals to the one given" [cus name param-types] (let [ methods (find-methods-by-name cus name) methods' (filter (partial method-match-exactly-parameters? param-types) methods)] methods'))
true
(ns effectivejava.find ^{:author "PI:NAME:<NAME>END_PI" :doc "This namespace contains methods to find elements in a collection of compilation units"} (:use [effectivejava.model.protocols]) (:use [effectivejava.model.javaparser]) (:use [effectivejava.javaparser.navigation]) (:use [effectivejava.operations]) (:use [effectivejava.itemsOnLifecycle]) (:use [effectivejava.symbol_solver.type_solver]) (:use [effectivejava.symbol_solver.scope]) (:use [effectivejava.utils]) (:require [instaparse.core :as insta]) (:import [effectivejava.operations Operation])) (defn type-exact-match? [type-ref1 type-ref2] (and (= (nil? type-ref1) (nil? type-ref2)) (if (or (nil? type-ref1) (nil? type-ref2)) ; if we have some nulls we do not want to perform the other checks ; just the previous check will count (both of them have to be nil) true (and (= (array? type-ref1) (array? type-ref2)) (= (primitive? type-ref1) (primitive? type-ref2)) (= (reference-type? type-ref1) (reference-type? type-ref2)) ; if the type is primitive the typeName must be the same (or (not (primitive? type-ref1)) (not (primitive? type-ref2)) (= (typeName type-ref1) (typeName type-ref2))) (or (not (reference-type? type-ref1)) (not (reference-type? type-ref2)) (let [referred-type1 (solveClass (context type-ref1) nil (typeName type-ref1)) referred-type2 (solveClass (context type-ref2) nil (typeName type-ref2))] ; unresolved types do not match (and referred-type1 referred-type2 (= referred-type1 referred-type2)))) (or (and (nil? (baseType type-ref1)) (nil? (baseType type-ref2))) (and (baseType type-ref1) (baseType type-ref2) (type-exact-match? (baseType type-ref1) (baseType type-ref2)))))))) (defn param-match-type? [pair] (let [[param expected-type] pair paramType (.getType param)] (type-exact-match? paramType expected-type))) (defn method-match-exactly-parameters? [param-expected-types method] (let [params (.getParameters method) pairs (map vector params param-expected-types)] (and (= (count params) (count param-expected-types)) (every? param-match-type? pairs)))) (defn find-methods-by-name "Find all the methods in the given CUs which has the given name" [cus name] (let [ all-types (flatten (map allTypes cus)) all-methods (flatten (map getMethods all-types)) methods (filter (fn [m] (= name (.getName m))) all-methods)] methods)) (defn find-methods-by-qname "Find all the methods in the given CUs which has the given QName name (e.g., japa.parser.ast.Node.equals)" [cus name] (let [ all-types (flatten (map allTypes cus)) all-methods (flatten (map getMethods all-types)) methods (filter (fn [m] (= name (getQName m))) all-methods)] methods)) (defn find-methods-by-signature "Find all the methods in the given CUs which has the given name and have parameter types exactly equals to the one given" [cus name param-types] (let [ methods (find-methods-by-name cus name) methods' (filter (partial method-match-exactly-parameters? param-types) methods)] methods'))
[ { "context": "3557252d7807\")\n(def ^:private fake-hashed-password \"$2a$10$owKjTym0ZGEEZOpxM0UyjekSvt66y1VvmOJddkAaMB37e0VAIVOX2\")\n\n(s/defn ^:private ldap-login :- (s/maybe {:id ", "end": 4354, "score": 0.9994180202484131, "start": 4293, "tag": "PASSWORD", "value": "\"$2a$10$owKjTym0ZGEEZOpxM0UyjekSvt66y1VvmOJddkAaMB37e0VAIVOX2" } ]
c#-metabase/src/metabase/api/session.clj
hanakhry/Crime_Admin
0
(ns metabase.api.session "/api/session endpoints" (:require [cemerick.friend.credentials :as creds] [clojure.tools.logging :as log] [compojure.core :refer [DELETE GET POST]] [metabase.api.common :as api] [metabase.config :as config] [metabase.email.messages :as email] [metabase.events :as events] [metabase.integrations.google :as google] [metabase.integrations.ldap :as ldap] [metabase.models.login-history :refer [LoginHistory]] [metabase.models.session :refer [Session]] [metabase.models.setting :as setting] [metabase.models.user :as user :refer [User]] [metabase.public-settings :as public-settings] [metabase.server.middleware.session :as mw.session] [metabase.server.request.util :as request.u] [metabase.util :as u] [metabase.util.i18n :as ui18n :refer [deferred-tru trs tru]] [metabase.util.password :as pass] [metabase.util.schema :as su] [schema.core :as s] [throttle.core :as throttle] [toucan.db :as db] [toucan.models :as t.models]) (:import com.unboundid.util.LDAPSDKException java.util.UUID)) (s/defn ^:private record-login-history! [session-id :- UUID user-id :- su/IntGreaterThanZero device-info :- request.u/DeviceInfo] (db/insert! LoginHistory (merge {:user_id user-id :session_id (str session-id)} device-info))) (defmulti create-session! "Generate a new Session for a User. `session-type` is the currently either `:password` (for email + password login) or `:sso` (for other login types). Returns the newly generated Session." {:arglists '(^java.util.UUID [session-type user device-info])} (fn [session-type & _] session-type)) (def ^:private CreateSessionUserInfo {:id su/IntGreaterThanZero :last_login s/Any s/Keyword s/Any}) (s/defmethod create-session! :sso :- {:id UUID, :type (s/enum :normal :full-app-embed) s/Keyword s/Any} [_ user :- CreateSessionUserInfo device-info :- request.u/DeviceInfo] (let [session-uuid (UUID/randomUUID) session (or (db/insert! Session :id (str session-uuid) :user_id (u/the-id user)) ;; HACK !!! For some reason `db/insert` doesn't seem to be working correctly for Session. (t.models/post-insert (Session (str session-uuid))))] (assert (map? session)) (events/publish-event! :user-login {:user_id (u/the-id user), :session_id (str session-uuid), :first_login (nil? (:last_login user))}) (record-login-history! session-uuid (u/the-id user) device-info) (assoc session :id session-uuid))) (s/defmethod create-session! :password :- {:id UUID, :type (s/enum :normal :full-app-embed), s/Keyword s/Any} [session-type user :- CreateSessionUserInfo device-info :- request.u/DeviceInfo] ;; this is actually the same as `create-session!` for `:sso` but we check whether password login is enabled. (when-not (public-settings/enable-password-login) (throw (ex-info (str (tru "Password login is disabled for this instance.")) {:status-code 400}))) ((get-method create-session! :sso) session-type user device-info)) ;;; ## API Endpoints (def ^:private login-throttlers {:username (throttle/make-throttler :username) ;; IP Address doesn't have an actual UI field so just show error by username :ip-address (throttle/make-throttler :username, :attempts-threshold 50)}) (def ^:private password-fail-message (deferred-tru "Password did not match stored password.")) (def ^:private password-fail-snippet (deferred-tru "did not match stored password")) (def ^:private disabled-account-message (deferred-tru "Your account is disabled. Please contact your administrator.")) (def ^:private disabled-account-snippet (deferred-tru "Your account is disabled.")) ;; Fake salt & hash used to run bcrypt hash if user doesn't exist, to avoid timing attacks (Metaboat #134) (def ^:private fake-salt "ee169694-5eb6-4010-a145-3557252d7807") (def ^:private fake-hashed-password "$2a$10$owKjTym0ZGEEZOpxM0UyjekSvt66y1VvmOJddkAaMB37e0VAIVOX2") (s/defn ^:private ldap-login :- (s/maybe {:id UUID, s/Keyword s/Any}) "If LDAP is enabled and a matching user exists return a new Session for them, or `nil` if they couldn't be authenticated." [username password device-info :- request.u/DeviceInfo] (when (ldap/ldap-configured?) (try (when-let [user-info (ldap/find-user username)] (when-not (ldap/verify-password user-info password) ;; Since LDAP knows about the user, fail here to prevent the local strategy to be tried with a possibly ;; outdated password (throw (ex-info (str password-fail-message) {:status-code 401 :errors {:password password-fail-snippet}}))) ;; password is ok, return new session if user is not deactivated (let [user (ldap/fetch-or-create-user! user-info)] (if (:is_active user) (create-session! :sso (ldap/fetch-or-create-user! user-info) device-info) (throw (ex-info (str disabled-account-message) {:status-code 401 :errors {:_error disabled-account-snippet}}))))) (catch LDAPSDKException e (log/error e (trs "Problem connecting to LDAP server, will fall back to local authentication")))))) (s/defn ^:private email-login :- (s/maybe {:id UUID, s/Keyword s/Any}) "Find a matching `User` if one exists and return a new Session for them, or `nil` if they couldn't be authenticated." [username password device-info :- request.u/DeviceInfo] (if-let [user (db/select-one [User :id :password_salt :password :last_login :is_active], :%lower.email (u/lower-case-en username))] (when (pass/verify-password password (:password_salt user) (:password user)) (if (:is_active user) (create-session! :password user device-info) (throw (ex-info (str disabled-account-message) {:status-code 401 :errors {:_error disabled-account-snippet}})))) (do ;; User doesn't exist; run bcrypt hash anyway to avoid leaking account existence in request timing (pass/verify-password password fake-salt fake-hashed-password) nil))) (def ^:private throttling-disabled? (config/config-bool :mb-disable-session-throttle)) (defn- throttle-check "Pass through to `throttle/check` but will not check if `throttling-disabled?` is true" [throttler throttle-key] (when-not throttling-disabled? (throttle/check throttler throttle-key))) (s/defn ^:private login :- {:id UUID, :type (s/enum :normal :full-app-embed), s/Keyword s/Any} "Attempt to login with different avaialable methods with `username` and `password`, returning new Session ID or throwing an Exception if login could not be completed." [username :- su/NonBlankString password :- su/NonBlankString device-info :- request.u/DeviceInfo] ;; Primitive "strategy implementation", should be reworked for modular providers in #3210 (or (ldap-login username password device-info) ; First try LDAP if it's enabled (email-login username password device-info) ; Then try local authentication ;; If nothing succeeded complain about it ;; Don't leak whether the account doesn't exist or the password was incorrect (throw (ex-info (str password-fail-message) {:status-code 401 :errors {:password password-fail-snippet}})))) (defn- do-http-401-on-error [f] (try (f) (catch clojure.lang.ExceptionInfo e (throw (ex-info (ex-message e) (assoc (ex-data e) :status-code 401)))))) (defmacro http-401-on-error "Add `{:status-code 401}` to exception data thrown by `body`." [& body] `(do-http-401-on-error (fn [] ~@body))) (api/defendpoint POST "/" "Login." [:as {{:keys [username password]} :body, :as request}] {username su/NonBlankString password su/NonBlankString} (let [ip-address (request.u/ip-address request) do-login (fn [] (let [{session-uuid :id, :as session} (login username password (request.u/device-info request)) response {:id (str session-uuid)}] (mw.session/set-session-cookie request response session)))] (if throttling-disabled? (do-login) (http-401-on-error (throttle/with-throttling [(login-throttlers :ip-address) ip-address (login-throttlers :username) username] (do-login)))))) (api/defendpoint DELETE "/" "Logout." [:as {:keys [metabase-session-id]}] (api/check-exists? Session metabase-session-id) (db/delete! Session :id metabase-session-id) (mw.session/clear-session-cookie api/generic-204-no-content)) ;; Reset tokens: We need some way to match a plaintext token with the a user since the token stored in the DB is ;; hashed. So we'll make the plaintext token in the format USER-ID_RANDOM-UUID, e.g. ;; "100_8a266560-e3a8-4dc1-9cd1-b4471dcd56d7", before hashing it. "Leaking" the ID this way is ok because the ;; plaintext token is only sent in the password reset email to the user in question. ;; ;; There's also no need to salt the token because it's already random <3 (def ^:private forgot-password-throttlers {:email (throttle/make-throttler :email) :ip-address (throttle/make-throttler :email, :attempts-threshold 50)}) (defn- forgot-password-impl [email server-name] (future (when-let [{user-id :id, google-auth? :google_auth, is-active? :is_active} (db/select-one [User :id :google_auth :is_active] :%lower.email (u/lower-case-en email))] (let [reset-token (user/set-password-reset-token! user-id) password-reset-url (str (public-settings/site-url) "/auth/reset_password/" reset-token)] (log/info password-reset-url) (email/send-password-reset-email! email google-auth? server-name password-reset-url is-active?))))) (api/defendpoint POST "/forgot_password" "Send a reset email when user has forgotten their password." [:as {:keys [server-name] {:keys [email]} :body, :as request}] {email su/Email} ;; Don't leak whether the account doesn't exist, just pretend everything is ok (let [request-source (request.u/ip-address request)] (throttle-check (forgot-password-throttlers :ip-address) request-source)) (throttle-check (forgot-password-throttlers :email) email) (forgot-password-impl email server-name) api/generic-204-no-content) (def ^:private ^:const reset-token-ttl-ms "Number of milliseconds a password reset is considered valid." (* 48 60 60 1000)) ; token considered valid for 48 hours (defn- valid-reset-token->user "Check if a password reset token is valid. If so, return the `User` ID it corresponds to." [^String token] (when-let [[_ user-id] (re-matches #"(^\d+)_.+$" token)] (let [user-id (Integer/parseInt user-id)] (when-let [{:keys [reset_token reset_triggered], :as user} (db/select-one [User :id :last_login :reset_triggered :reset_token] :id user-id, :is_active true)] ;; Make sure the plaintext token matches up with the hashed one for this user (when (u/ignore-exceptions (creds/bcrypt-verify token reset_token)) ;; check that the reset was triggered within the last 48 HOURS, after that the token is considered expired (let [token-age (- (System/currentTimeMillis) reset_triggered)] (when (< token-age reset-token-ttl-ms) user))))))) (api/defendpoint POST "/reset_password" "Reset password with a reset token." [:as {{:keys [token password]} :body, :as request}] {token su/NonBlankString password su/ValidPassword} (or (when-let [{user-id :id, :as user} (valid-reset-token->user token)] (user/set-password! user-id password) ;; if this is the first time the user has logged in it means that they're just accepted their Metabase invite. ;; Send all the active admins an email :D (when-not (:last_login user) (email/send-user-joined-admin-notification-email! (User user-id))) ;; after a successful password update go ahead and offer the client a new session that they can use (let [{session-uuid :id, :as session} (create-session! :password user (request.u/device-info request)) response {:success true :session_id (str session-uuid)}] (mw.session/set-session-cookie request response session))) (api/throw-invalid-param-exception :password (tru "Invalid reset token")))) (api/defendpoint GET "/password_reset_token_valid" "Check is a password reset token is valid and isn't expired." [token] {token s/Str} {:valid (boolean (valid-reset-token->user token))}) (api/defendpoint GET "/properties" "Get all global properties and their values. These are the specific `Settings` which are meant to be public." [] (merge (setting/properties :public) (when @api/*current-user* (setting/properties :authenticated)) (when api/*is-superuser?* (setting/properties :admin)))) (api/defendpoint POST "/google_auth" "Login with Google Auth." [:as {{:keys [token]} :body, :as request}] {token su/NonBlankString} (when-not (google/google-auth-client-id) (throw (ex-info "Google Auth is disabled." {:status-code 400}))) ;; Verify the token is valid with Google (if throttling-disabled? (google/do-google-auth request) (http-401-on-error (throttle/with-throttling [(login-throttlers :ip-address) (request.u/ip-address request)] (let [user (google/do-google-auth request) {session-uuid :id, :as session} (create-session! :sso user (request.u/device-info request)) response {:id (str session-uuid)} user (db/select-one [User :id :is_active], :email (:email user))] (if (and user (:is_active user)) (mw.session/set-session-cookie request response session) (throw (ex-info (str disabled-account-message) {:status-code 401 :errors {:account disabled-account-snippet}})))))))) (defn- +log-all-request-failures [handler] (fn [request respond raise] (try (handler request respond raise) (catch Throwable e (log/error e (trs "Authentication endpoint error")) (throw e))))) (api/define-routes +log-all-request-failures)
119831
(ns metabase.api.session "/api/session endpoints" (:require [cemerick.friend.credentials :as creds] [clojure.tools.logging :as log] [compojure.core :refer [DELETE GET POST]] [metabase.api.common :as api] [metabase.config :as config] [metabase.email.messages :as email] [metabase.events :as events] [metabase.integrations.google :as google] [metabase.integrations.ldap :as ldap] [metabase.models.login-history :refer [LoginHistory]] [metabase.models.session :refer [Session]] [metabase.models.setting :as setting] [metabase.models.user :as user :refer [User]] [metabase.public-settings :as public-settings] [metabase.server.middleware.session :as mw.session] [metabase.server.request.util :as request.u] [metabase.util :as u] [metabase.util.i18n :as ui18n :refer [deferred-tru trs tru]] [metabase.util.password :as pass] [metabase.util.schema :as su] [schema.core :as s] [throttle.core :as throttle] [toucan.db :as db] [toucan.models :as t.models]) (:import com.unboundid.util.LDAPSDKException java.util.UUID)) (s/defn ^:private record-login-history! [session-id :- UUID user-id :- su/IntGreaterThanZero device-info :- request.u/DeviceInfo] (db/insert! LoginHistory (merge {:user_id user-id :session_id (str session-id)} device-info))) (defmulti create-session! "Generate a new Session for a User. `session-type` is the currently either `:password` (for email + password login) or `:sso` (for other login types). Returns the newly generated Session." {:arglists '(^java.util.UUID [session-type user device-info])} (fn [session-type & _] session-type)) (def ^:private CreateSessionUserInfo {:id su/IntGreaterThanZero :last_login s/Any s/Keyword s/Any}) (s/defmethod create-session! :sso :- {:id UUID, :type (s/enum :normal :full-app-embed) s/Keyword s/Any} [_ user :- CreateSessionUserInfo device-info :- request.u/DeviceInfo] (let [session-uuid (UUID/randomUUID) session (or (db/insert! Session :id (str session-uuid) :user_id (u/the-id user)) ;; HACK !!! For some reason `db/insert` doesn't seem to be working correctly for Session. (t.models/post-insert (Session (str session-uuid))))] (assert (map? session)) (events/publish-event! :user-login {:user_id (u/the-id user), :session_id (str session-uuid), :first_login (nil? (:last_login user))}) (record-login-history! session-uuid (u/the-id user) device-info) (assoc session :id session-uuid))) (s/defmethod create-session! :password :- {:id UUID, :type (s/enum :normal :full-app-embed), s/Keyword s/Any} [session-type user :- CreateSessionUserInfo device-info :- request.u/DeviceInfo] ;; this is actually the same as `create-session!` for `:sso` but we check whether password login is enabled. (when-not (public-settings/enable-password-login) (throw (ex-info (str (tru "Password login is disabled for this instance.")) {:status-code 400}))) ((get-method create-session! :sso) session-type user device-info)) ;;; ## API Endpoints (def ^:private login-throttlers {:username (throttle/make-throttler :username) ;; IP Address doesn't have an actual UI field so just show error by username :ip-address (throttle/make-throttler :username, :attempts-threshold 50)}) (def ^:private password-fail-message (deferred-tru "Password did not match stored password.")) (def ^:private password-fail-snippet (deferred-tru "did not match stored password")) (def ^:private disabled-account-message (deferred-tru "Your account is disabled. Please contact your administrator.")) (def ^:private disabled-account-snippet (deferred-tru "Your account is disabled.")) ;; Fake salt & hash used to run bcrypt hash if user doesn't exist, to avoid timing attacks (Metaboat #134) (def ^:private fake-salt "ee169694-5eb6-4010-a145-3557252d7807") (def ^:private fake-hashed-password <PASSWORD>") (s/defn ^:private ldap-login :- (s/maybe {:id UUID, s/Keyword s/Any}) "If LDAP is enabled and a matching user exists return a new Session for them, or `nil` if they couldn't be authenticated." [username password device-info :- request.u/DeviceInfo] (when (ldap/ldap-configured?) (try (when-let [user-info (ldap/find-user username)] (when-not (ldap/verify-password user-info password) ;; Since LDAP knows about the user, fail here to prevent the local strategy to be tried with a possibly ;; outdated password (throw (ex-info (str password-fail-message) {:status-code 401 :errors {:password password-fail-snippet}}))) ;; password is ok, return new session if user is not deactivated (let [user (ldap/fetch-or-create-user! user-info)] (if (:is_active user) (create-session! :sso (ldap/fetch-or-create-user! user-info) device-info) (throw (ex-info (str disabled-account-message) {:status-code 401 :errors {:_error disabled-account-snippet}}))))) (catch LDAPSDKException e (log/error e (trs "Problem connecting to LDAP server, will fall back to local authentication")))))) (s/defn ^:private email-login :- (s/maybe {:id UUID, s/Keyword s/Any}) "Find a matching `User` if one exists and return a new Session for them, or `nil` if they couldn't be authenticated." [username password device-info :- request.u/DeviceInfo] (if-let [user (db/select-one [User :id :password_salt :password :last_login :is_active], :%lower.email (u/lower-case-en username))] (when (pass/verify-password password (:password_salt user) (:password user)) (if (:is_active user) (create-session! :password user device-info) (throw (ex-info (str disabled-account-message) {:status-code 401 :errors {:_error disabled-account-snippet}})))) (do ;; User doesn't exist; run bcrypt hash anyway to avoid leaking account existence in request timing (pass/verify-password password fake-salt fake-hashed-password) nil))) (def ^:private throttling-disabled? (config/config-bool :mb-disable-session-throttle)) (defn- throttle-check "Pass through to `throttle/check` but will not check if `throttling-disabled?` is true" [throttler throttle-key] (when-not throttling-disabled? (throttle/check throttler throttle-key))) (s/defn ^:private login :- {:id UUID, :type (s/enum :normal :full-app-embed), s/Keyword s/Any} "Attempt to login with different avaialable methods with `username` and `password`, returning new Session ID or throwing an Exception if login could not be completed." [username :- su/NonBlankString password :- su/NonBlankString device-info :- request.u/DeviceInfo] ;; Primitive "strategy implementation", should be reworked for modular providers in #3210 (or (ldap-login username password device-info) ; First try LDAP if it's enabled (email-login username password device-info) ; Then try local authentication ;; If nothing succeeded complain about it ;; Don't leak whether the account doesn't exist or the password was incorrect (throw (ex-info (str password-fail-message) {:status-code 401 :errors {:password password-fail-snippet}})))) (defn- do-http-401-on-error [f] (try (f) (catch clojure.lang.ExceptionInfo e (throw (ex-info (ex-message e) (assoc (ex-data e) :status-code 401)))))) (defmacro http-401-on-error "Add `{:status-code 401}` to exception data thrown by `body`." [& body] `(do-http-401-on-error (fn [] ~@body))) (api/defendpoint POST "/" "Login." [:as {{:keys [username password]} :body, :as request}] {username su/NonBlankString password su/NonBlankString} (let [ip-address (request.u/ip-address request) do-login (fn [] (let [{session-uuid :id, :as session} (login username password (request.u/device-info request)) response {:id (str session-uuid)}] (mw.session/set-session-cookie request response session)))] (if throttling-disabled? (do-login) (http-401-on-error (throttle/with-throttling [(login-throttlers :ip-address) ip-address (login-throttlers :username) username] (do-login)))))) (api/defendpoint DELETE "/" "Logout." [:as {:keys [metabase-session-id]}] (api/check-exists? Session metabase-session-id) (db/delete! Session :id metabase-session-id) (mw.session/clear-session-cookie api/generic-204-no-content)) ;; Reset tokens: We need some way to match a plaintext token with the a user since the token stored in the DB is ;; hashed. So we'll make the plaintext token in the format USER-ID_RANDOM-UUID, e.g. ;; "100_8a266560-e3a8-4dc1-9cd1-b4471dcd56d7", before hashing it. "Leaking" the ID this way is ok because the ;; plaintext token is only sent in the password reset email to the user in question. ;; ;; There's also no need to salt the token because it's already random <3 (def ^:private forgot-password-throttlers {:email (throttle/make-throttler :email) :ip-address (throttle/make-throttler :email, :attempts-threshold 50)}) (defn- forgot-password-impl [email server-name] (future (when-let [{user-id :id, google-auth? :google_auth, is-active? :is_active} (db/select-one [User :id :google_auth :is_active] :%lower.email (u/lower-case-en email))] (let [reset-token (user/set-password-reset-token! user-id) password-reset-url (str (public-settings/site-url) "/auth/reset_password/" reset-token)] (log/info password-reset-url) (email/send-password-reset-email! email google-auth? server-name password-reset-url is-active?))))) (api/defendpoint POST "/forgot_password" "Send a reset email when user has forgotten their password." [:as {:keys [server-name] {:keys [email]} :body, :as request}] {email su/Email} ;; Don't leak whether the account doesn't exist, just pretend everything is ok (let [request-source (request.u/ip-address request)] (throttle-check (forgot-password-throttlers :ip-address) request-source)) (throttle-check (forgot-password-throttlers :email) email) (forgot-password-impl email server-name) api/generic-204-no-content) (def ^:private ^:const reset-token-ttl-ms "Number of milliseconds a password reset is considered valid." (* 48 60 60 1000)) ; token considered valid for 48 hours (defn- valid-reset-token->user "Check if a password reset token is valid. If so, return the `User` ID it corresponds to." [^String token] (when-let [[_ user-id] (re-matches #"(^\d+)_.+$" token)] (let [user-id (Integer/parseInt user-id)] (when-let [{:keys [reset_token reset_triggered], :as user} (db/select-one [User :id :last_login :reset_triggered :reset_token] :id user-id, :is_active true)] ;; Make sure the plaintext token matches up with the hashed one for this user (when (u/ignore-exceptions (creds/bcrypt-verify token reset_token)) ;; check that the reset was triggered within the last 48 HOURS, after that the token is considered expired (let [token-age (- (System/currentTimeMillis) reset_triggered)] (when (< token-age reset-token-ttl-ms) user))))))) (api/defendpoint POST "/reset_password" "Reset password with a reset token." [:as {{:keys [token password]} :body, :as request}] {token su/NonBlankString password su/ValidPassword} (or (when-let [{user-id :id, :as user} (valid-reset-token->user token)] (user/set-password! user-id password) ;; if this is the first time the user has logged in it means that they're just accepted their Metabase invite. ;; Send all the active admins an email :D (when-not (:last_login user) (email/send-user-joined-admin-notification-email! (User user-id))) ;; after a successful password update go ahead and offer the client a new session that they can use (let [{session-uuid :id, :as session} (create-session! :password user (request.u/device-info request)) response {:success true :session_id (str session-uuid)}] (mw.session/set-session-cookie request response session))) (api/throw-invalid-param-exception :password (tru "Invalid reset token")))) (api/defendpoint GET "/password_reset_token_valid" "Check is a password reset token is valid and isn't expired." [token] {token s/Str} {:valid (boolean (valid-reset-token->user token))}) (api/defendpoint GET "/properties" "Get all global properties and their values. These are the specific `Settings` which are meant to be public." [] (merge (setting/properties :public) (when @api/*current-user* (setting/properties :authenticated)) (when api/*is-superuser?* (setting/properties :admin)))) (api/defendpoint POST "/google_auth" "Login with Google Auth." [:as {{:keys [token]} :body, :as request}] {token su/NonBlankString} (when-not (google/google-auth-client-id) (throw (ex-info "Google Auth is disabled." {:status-code 400}))) ;; Verify the token is valid with Google (if throttling-disabled? (google/do-google-auth request) (http-401-on-error (throttle/with-throttling [(login-throttlers :ip-address) (request.u/ip-address request)] (let [user (google/do-google-auth request) {session-uuid :id, :as session} (create-session! :sso user (request.u/device-info request)) response {:id (str session-uuid)} user (db/select-one [User :id :is_active], :email (:email user))] (if (and user (:is_active user)) (mw.session/set-session-cookie request response session) (throw (ex-info (str disabled-account-message) {:status-code 401 :errors {:account disabled-account-snippet}})))))))) (defn- +log-all-request-failures [handler] (fn [request respond raise] (try (handler request respond raise) (catch Throwable e (log/error e (trs "Authentication endpoint error")) (throw e))))) (api/define-routes +log-all-request-failures)
true
(ns metabase.api.session "/api/session endpoints" (:require [cemerick.friend.credentials :as creds] [clojure.tools.logging :as log] [compojure.core :refer [DELETE GET POST]] [metabase.api.common :as api] [metabase.config :as config] [metabase.email.messages :as email] [metabase.events :as events] [metabase.integrations.google :as google] [metabase.integrations.ldap :as ldap] [metabase.models.login-history :refer [LoginHistory]] [metabase.models.session :refer [Session]] [metabase.models.setting :as setting] [metabase.models.user :as user :refer [User]] [metabase.public-settings :as public-settings] [metabase.server.middleware.session :as mw.session] [metabase.server.request.util :as request.u] [metabase.util :as u] [metabase.util.i18n :as ui18n :refer [deferred-tru trs tru]] [metabase.util.password :as pass] [metabase.util.schema :as su] [schema.core :as s] [throttle.core :as throttle] [toucan.db :as db] [toucan.models :as t.models]) (:import com.unboundid.util.LDAPSDKException java.util.UUID)) (s/defn ^:private record-login-history! [session-id :- UUID user-id :- su/IntGreaterThanZero device-info :- request.u/DeviceInfo] (db/insert! LoginHistory (merge {:user_id user-id :session_id (str session-id)} device-info))) (defmulti create-session! "Generate a new Session for a User. `session-type` is the currently either `:password` (for email + password login) or `:sso` (for other login types). Returns the newly generated Session." {:arglists '(^java.util.UUID [session-type user device-info])} (fn [session-type & _] session-type)) (def ^:private CreateSessionUserInfo {:id su/IntGreaterThanZero :last_login s/Any s/Keyword s/Any}) (s/defmethod create-session! :sso :- {:id UUID, :type (s/enum :normal :full-app-embed) s/Keyword s/Any} [_ user :- CreateSessionUserInfo device-info :- request.u/DeviceInfo] (let [session-uuid (UUID/randomUUID) session (or (db/insert! Session :id (str session-uuid) :user_id (u/the-id user)) ;; HACK !!! For some reason `db/insert` doesn't seem to be working correctly for Session. (t.models/post-insert (Session (str session-uuid))))] (assert (map? session)) (events/publish-event! :user-login {:user_id (u/the-id user), :session_id (str session-uuid), :first_login (nil? (:last_login user))}) (record-login-history! session-uuid (u/the-id user) device-info) (assoc session :id session-uuid))) (s/defmethod create-session! :password :- {:id UUID, :type (s/enum :normal :full-app-embed), s/Keyword s/Any} [session-type user :- CreateSessionUserInfo device-info :- request.u/DeviceInfo] ;; this is actually the same as `create-session!` for `:sso` but we check whether password login is enabled. (when-not (public-settings/enable-password-login) (throw (ex-info (str (tru "Password login is disabled for this instance.")) {:status-code 400}))) ((get-method create-session! :sso) session-type user device-info)) ;;; ## API Endpoints (def ^:private login-throttlers {:username (throttle/make-throttler :username) ;; IP Address doesn't have an actual UI field so just show error by username :ip-address (throttle/make-throttler :username, :attempts-threshold 50)}) (def ^:private password-fail-message (deferred-tru "Password did not match stored password.")) (def ^:private password-fail-snippet (deferred-tru "did not match stored password")) (def ^:private disabled-account-message (deferred-tru "Your account is disabled. Please contact your administrator.")) (def ^:private disabled-account-snippet (deferred-tru "Your account is disabled.")) ;; Fake salt & hash used to run bcrypt hash if user doesn't exist, to avoid timing attacks (Metaboat #134) (def ^:private fake-salt "ee169694-5eb6-4010-a145-3557252d7807") (def ^:private fake-hashed-password PI:PASSWORD:<PASSWORD>END_PI") (s/defn ^:private ldap-login :- (s/maybe {:id UUID, s/Keyword s/Any}) "If LDAP is enabled and a matching user exists return a new Session for them, or `nil` if they couldn't be authenticated." [username password device-info :- request.u/DeviceInfo] (when (ldap/ldap-configured?) (try (when-let [user-info (ldap/find-user username)] (when-not (ldap/verify-password user-info password) ;; Since LDAP knows about the user, fail here to prevent the local strategy to be tried with a possibly ;; outdated password (throw (ex-info (str password-fail-message) {:status-code 401 :errors {:password password-fail-snippet}}))) ;; password is ok, return new session if user is not deactivated (let [user (ldap/fetch-or-create-user! user-info)] (if (:is_active user) (create-session! :sso (ldap/fetch-or-create-user! user-info) device-info) (throw (ex-info (str disabled-account-message) {:status-code 401 :errors {:_error disabled-account-snippet}}))))) (catch LDAPSDKException e (log/error e (trs "Problem connecting to LDAP server, will fall back to local authentication")))))) (s/defn ^:private email-login :- (s/maybe {:id UUID, s/Keyword s/Any}) "Find a matching `User` if one exists and return a new Session for them, or `nil` if they couldn't be authenticated." [username password device-info :- request.u/DeviceInfo] (if-let [user (db/select-one [User :id :password_salt :password :last_login :is_active], :%lower.email (u/lower-case-en username))] (when (pass/verify-password password (:password_salt user) (:password user)) (if (:is_active user) (create-session! :password user device-info) (throw (ex-info (str disabled-account-message) {:status-code 401 :errors {:_error disabled-account-snippet}})))) (do ;; User doesn't exist; run bcrypt hash anyway to avoid leaking account existence in request timing (pass/verify-password password fake-salt fake-hashed-password) nil))) (def ^:private throttling-disabled? (config/config-bool :mb-disable-session-throttle)) (defn- throttle-check "Pass through to `throttle/check` but will not check if `throttling-disabled?` is true" [throttler throttle-key] (when-not throttling-disabled? (throttle/check throttler throttle-key))) (s/defn ^:private login :- {:id UUID, :type (s/enum :normal :full-app-embed), s/Keyword s/Any} "Attempt to login with different avaialable methods with `username` and `password`, returning new Session ID or throwing an Exception if login could not be completed." [username :- su/NonBlankString password :- su/NonBlankString device-info :- request.u/DeviceInfo] ;; Primitive "strategy implementation", should be reworked for modular providers in #3210 (or (ldap-login username password device-info) ; First try LDAP if it's enabled (email-login username password device-info) ; Then try local authentication ;; If nothing succeeded complain about it ;; Don't leak whether the account doesn't exist or the password was incorrect (throw (ex-info (str password-fail-message) {:status-code 401 :errors {:password password-fail-snippet}})))) (defn- do-http-401-on-error [f] (try (f) (catch clojure.lang.ExceptionInfo e (throw (ex-info (ex-message e) (assoc (ex-data e) :status-code 401)))))) (defmacro http-401-on-error "Add `{:status-code 401}` to exception data thrown by `body`." [& body] `(do-http-401-on-error (fn [] ~@body))) (api/defendpoint POST "/" "Login." [:as {{:keys [username password]} :body, :as request}] {username su/NonBlankString password su/NonBlankString} (let [ip-address (request.u/ip-address request) do-login (fn [] (let [{session-uuid :id, :as session} (login username password (request.u/device-info request)) response {:id (str session-uuid)}] (mw.session/set-session-cookie request response session)))] (if throttling-disabled? (do-login) (http-401-on-error (throttle/with-throttling [(login-throttlers :ip-address) ip-address (login-throttlers :username) username] (do-login)))))) (api/defendpoint DELETE "/" "Logout." [:as {:keys [metabase-session-id]}] (api/check-exists? Session metabase-session-id) (db/delete! Session :id metabase-session-id) (mw.session/clear-session-cookie api/generic-204-no-content)) ;; Reset tokens: We need some way to match a plaintext token with the a user since the token stored in the DB is ;; hashed. So we'll make the plaintext token in the format USER-ID_RANDOM-UUID, e.g. ;; "100_8a266560-e3a8-4dc1-9cd1-b4471dcd56d7", before hashing it. "Leaking" the ID this way is ok because the ;; plaintext token is only sent in the password reset email to the user in question. ;; ;; There's also no need to salt the token because it's already random <3 (def ^:private forgot-password-throttlers {:email (throttle/make-throttler :email) :ip-address (throttle/make-throttler :email, :attempts-threshold 50)}) (defn- forgot-password-impl [email server-name] (future (when-let [{user-id :id, google-auth? :google_auth, is-active? :is_active} (db/select-one [User :id :google_auth :is_active] :%lower.email (u/lower-case-en email))] (let [reset-token (user/set-password-reset-token! user-id) password-reset-url (str (public-settings/site-url) "/auth/reset_password/" reset-token)] (log/info password-reset-url) (email/send-password-reset-email! email google-auth? server-name password-reset-url is-active?))))) (api/defendpoint POST "/forgot_password" "Send a reset email when user has forgotten their password." [:as {:keys [server-name] {:keys [email]} :body, :as request}] {email su/Email} ;; Don't leak whether the account doesn't exist, just pretend everything is ok (let [request-source (request.u/ip-address request)] (throttle-check (forgot-password-throttlers :ip-address) request-source)) (throttle-check (forgot-password-throttlers :email) email) (forgot-password-impl email server-name) api/generic-204-no-content) (def ^:private ^:const reset-token-ttl-ms "Number of milliseconds a password reset is considered valid." (* 48 60 60 1000)) ; token considered valid for 48 hours (defn- valid-reset-token->user "Check if a password reset token is valid. If so, return the `User` ID it corresponds to." [^String token] (when-let [[_ user-id] (re-matches #"(^\d+)_.+$" token)] (let [user-id (Integer/parseInt user-id)] (when-let [{:keys [reset_token reset_triggered], :as user} (db/select-one [User :id :last_login :reset_triggered :reset_token] :id user-id, :is_active true)] ;; Make sure the plaintext token matches up with the hashed one for this user (when (u/ignore-exceptions (creds/bcrypt-verify token reset_token)) ;; check that the reset was triggered within the last 48 HOURS, after that the token is considered expired (let [token-age (- (System/currentTimeMillis) reset_triggered)] (when (< token-age reset-token-ttl-ms) user))))))) (api/defendpoint POST "/reset_password" "Reset password with a reset token." [:as {{:keys [token password]} :body, :as request}] {token su/NonBlankString password su/ValidPassword} (or (when-let [{user-id :id, :as user} (valid-reset-token->user token)] (user/set-password! user-id password) ;; if this is the first time the user has logged in it means that they're just accepted their Metabase invite. ;; Send all the active admins an email :D (when-not (:last_login user) (email/send-user-joined-admin-notification-email! (User user-id))) ;; after a successful password update go ahead and offer the client a new session that they can use (let [{session-uuid :id, :as session} (create-session! :password user (request.u/device-info request)) response {:success true :session_id (str session-uuid)}] (mw.session/set-session-cookie request response session))) (api/throw-invalid-param-exception :password (tru "Invalid reset token")))) (api/defendpoint GET "/password_reset_token_valid" "Check is a password reset token is valid and isn't expired." [token] {token s/Str} {:valid (boolean (valid-reset-token->user token))}) (api/defendpoint GET "/properties" "Get all global properties and their values. These are the specific `Settings` which are meant to be public." [] (merge (setting/properties :public) (when @api/*current-user* (setting/properties :authenticated)) (when api/*is-superuser?* (setting/properties :admin)))) (api/defendpoint POST "/google_auth" "Login with Google Auth." [:as {{:keys [token]} :body, :as request}] {token su/NonBlankString} (when-not (google/google-auth-client-id) (throw (ex-info "Google Auth is disabled." {:status-code 400}))) ;; Verify the token is valid with Google (if throttling-disabled? (google/do-google-auth request) (http-401-on-error (throttle/with-throttling [(login-throttlers :ip-address) (request.u/ip-address request)] (let [user (google/do-google-auth request) {session-uuid :id, :as session} (create-session! :sso user (request.u/device-info request)) response {:id (str session-uuid)} user (db/select-one [User :id :is_active], :email (:email user))] (if (and user (:is_active user)) (mw.session/set-session-cookie request response session) (throw (ex-info (str disabled-account-message) {:status-code 401 :errors {:account disabled-account-snippet}})))))))) (defn- +log-all-request-failures [handler] (fn [request respond raise] (try (handler request respond raise) (catch Throwable e (log/error e (trs "Authentication endpoint error")) (throw e))))) (api/define-routes +log-all-request-failures)
[ { "context": "\n\n; https://graph.facebook.com/v2.7/?access_token=656701554388983|fqJuiXLWOJR6kIvzpijiJgZlUxU&ids=https://example.com1,https://example.com2,htt", "end": 601, "score": 0.9735721349716187, "start": 558, "tag": "KEY", "value": "656701554388983|fqJuiXLWOJR6kIvzpijiJgZlUxU" } ]
src/event_data_facebook_agent/core.clj
CrossRef/event-data-facebook-agent
0
(ns event-data-facebook-agent.core (:require [clojure.tools.logging :as l] [clojure.java.io :refer [reader writer]] [clojure.set :refer [map-invert]] [clojure.data.json :as json]) (:require [org.httpkit.client :as http] [clj-time.format :as f] [clj-time.core :as clj-time] [crossref.util.doi :as cr-doi] [robert.bruce :refer [try-try-again]]) (:import [java.net URLEncoder] [java.util UUID]) (:gen-class)) ; https://graph.facebook.com/v2.7/?access_token=656701554388983|fqJuiXLWOJR6kIvzpijiJgZlUxU&ids=https://example.com1,https://example.com2,https://example.com3,https://example.com4,https://example.com5,https://example.com6,https://example.com7,https://example.com8,https://example.com9,https://example.com10 ; Maxmum per Facebook API. (def chunk-size 20) (def facebook-endpoint "https://graph.facebook.com/v2.7/") (def api-token (atom nil)) (def source-token (atom nil)) (defn new-uuid [] (.toString (UUID/randomUUID))) (defn extract-events "Extract a facebook result into a list of event deposits." [facebook-result url-doi-mapping subj-url time-str] (mapcat (fn [[url value]] (let [doi (url-doi-mapping url)] ; DOI should be found. But if FB gives us something back that we didn't recognise we can't. (if (not doi) (do (l/error "Couldn't reverse" url) []) [{:uuid (new-uuid) :source_token @source-token :subj_id subj-url :subj {:pid subj-url :URL "https://facebook.com" :title (str "Facebook activity at " time-str) :type "webpage" :issued time-str} :obj_id (cr-doi/normalise-doi doi) :relation_type_id "discusses" :source_id "facebook" :occurred_at time-str :total (get-in value ["share" "comment_count"] 0)} {:uuid (new-uuid) :source_token @source-token :subj_id subj-url :subj {:pid subj-url :URL "https://facebook.com" :title (str "Facebook activity at " time-str) :type "webpage" :issued time-str} :obj_id (cr-doi/normalise-doi doi) :relation_type_id "bookmarks" :source_id "facebook" :occurred_at time-str :total (get-in value ["share" "share_count"] 0)}]))) facebook-result)) (def facebook-url-date-formatter (f/formatter "yyyy/MM")) (defn fetch "For a URL token and map of url-doi, retrieve all data. Return Evidence Log items." [url-dois] (let [urls (map first url-dois) ; escaped-urls (map #(URLEncoder/encode % "UTF-8") urls) ids-query (clojure.string/join "," urls) result (try-try-again {:sleep 5000 :tries 10} #(deref (http/get facebook-endpoint {:as :text :query-params {"ids" ids-query "access_token" @api-token}}))) now (clj-time/now) subj-url (str "https://facebook.com/" (f/unparse facebook-url-date-formatter now)) ; If there's no body, report that. Status code will also be returned. status (:status result) body (:body result) ok (and body (= status 200)) ; Sometimes non-JSON is sent. If we can't parse return nil. We still record the status and input body. parsed-body (when ok (try (json/read-str body) (catch Exception e nil))) events (when body (extract-events parsed-body url-dois subj-url (str now))) evidence-log {:input-status status :input-headers (:headers result) :input-body body :events events}] evidence-log)) (defn fetch-partition "Fetch chunk of 'doi \n url \n' lines" [counter lines] (let [doi-urls (apply hash-map lines) url-dois (map-invert doi-urls)] (swap! counter #(+ chunk-size %)) ; (l/info "Fetched" @counter) (when (zero? (mod @counter 1)) (l/info "Fetched" @counter)) (fetch url-dois))) (defn -main "I don't do a whole lot ... yet." [& args] (let [api-token-input (first args) url-file (second args) output-file (nth args 2) source-token-input (nth args 3) counter (atom 0)] (reset! api-token api-token-input) (reset! source-token source-token-input) (l/info "URL File " url-file) (l/info "Output file" output-file) (l/info "Source token" source-token) (with-open [rdr (reader url-file)] ; Lines are pairs of "doi \n url \n" ; They are ALWAYS 1-1 mapping so it's OK to invert the map. (let [lines (partition-all (* chunk-size 2) (line-seq rdr)) results (lazy-cat (pmap (partial fetch-partition counter) lines))] (with-open [wrt (writer output-file)] (json/write results wrt)) ; (doseq [result results] ; (prn result)) ))) (shutdown-agents) )
17512
(ns event-data-facebook-agent.core (:require [clojure.tools.logging :as l] [clojure.java.io :refer [reader writer]] [clojure.set :refer [map-invert]] [clojure.data.json :as json]) (:require [org.httpkit.client :as http] [clj-time.format :as f] [clj-time.core :as clj-time] [crossref.util.doi :as cr-doi] [robert.bruce :refer [try-try-again]]) (:import [java.net URLEncoder] [java.util UUID]) (:gen-class)) ; https://graph.facebook.com/v2.7/?access_token=<KEY>&ids=https://example.com1,https://example.com2,https://example.com3,https://example.com4,https://example.com5,https://example.com6,https://example.com7,https://example.com8,https://example.com9,https://example.com10 ; Maxmum per Facebook API. (def chunk-size 20) (def facebook-endpoint "https://graph.facebook.com/v2.7/") (def api-token (atom nil)) (def source-token (atom nil)) (defn new-uuid [] (.toString (UUID/randomUUID))) (defn extract-events "Extract a facebook result into a list of event deposits." [facebook-result url-doi-mapping subj-url time-str] (mapcat (fn [[url value]] (let [doi (url-doi-mapping url)] ; DOI should be found. But if FB gives us something back that we didn't recognise we can't. (if (not doi) (do (l/error "Couldn't reverse" url) []) [{:uuid (new-uuid) :source_token @source-token :subj_id subj-url :subj {:pid subj-url :URL "https://facebook.com" :title (str "Facebook activity at " time-str) :type "webpage" :issued time-str} :obj_id (cr-doi/normalise-doi doi) :relation_type_id "discusses" :source_id "facebook" :occurred_at time-str :total (get-in value ["share" "comment_count"] 0)} {:uuid (new-uuid) :source_token @source-token :subj_id subj-url :subj {:pid subj-url :URL "https://facebook.com" :title (str "Facebook activity at " time-str) :type "webpage" :issued time-str} :obj_id (cr-doi/normalise-doi doi) :relation_type_id "bookmarks" :source_id "facebook" :occurred_at time-str :total (get-in value ["share" "share_count"] 0)}]))) facebook-result)) (def facebook-url-date-formatter (f/formatter "yyyy/MM")) (defn fetch "For a URL token and map of url-doi, retrieve all data. Return Evidence Log items." [url-dois] (let [urls (map first url-dois) ; escaped-urls (map #(URLEncoder/encode % "UTF-8") urls) ids-query (clojure.string/join "," urls) result (try-try-again {:sleep 5000 :tries 10} #(deref (http/get facebook-endpoint {:as :text :query-params {"ids" ids-query "access_token" @api-token}}))) now (clj-time/now) subj-url (str "https://facebook.com/" (f/unparse facebook-url-date-formatter now)) ; If there's no body, report that. Status code will also be returned. status (:status result) body (:body result) ok (and body (= status 200)) ; Sometimes non-JSON is sent. If we can't parse return nil. We still record the status and input body. parsed-body (when ok (try (json/read-str body) (catch Exception e nil))) events (when body (extract-events parsed-body url-dois subj-url (str now))) evidence-log {:input-status status :input-headers (:headers result) :input-body body :events events}] evidence-log)) (defn fetch-partition "Fetch chunk of 'doi \n url \n' lines" [counter lines] (let [doi-urls (apply hash-map lines) url-dois (map-invert doi-urls)] (swap! counter #(+ chunk-size %)) ; (l/info "Fetched" @counter) (when (zero? (mod @counter 1)) (l/info "Fetched" @counter)) (fetch url-dois))) (defn -main "I don't do a whole lot ... yet." [& args] (let [api-token-input (first args) url-file (second args) output-file (nth args 2) source-token-input (nth args 3) counter (atom 0)] (reset! api-token api-token-input) (reset! source-token source-token-input) (l/info "URL File " url-file) (l/info "Output file" output-file) (l/info "Source token" source-token) (with-open [rdr (reader url-file)] ; Lines are pairs of "doi \n url \n" ; They are ALWAYS 1-1 mapping so it's OK to invert the map. (let [lines (partition-all (* chunk-size 2) (line-seq rdr)) results (lazy-cat (pmap (partial fetch-partition counter) lines))] (with-open [wrt (writer output-file)] (json/write results wrt)) ; (doseq [result results] ; (prn result)) ))) (shutdown-agents) )
true
(ns event-data-facebook-agent.core (:require [clojure.tools.logging :as l] [clojure.java.io :refer [reader writer]] [clojure.set :refer [map-invert]] [clojure.data.json :as json]) (:require [org.httpkit.client :as http] [clj-time.format :as f] [clj-time.core :as clj-time] [crossref.util.doi :as cr-doi] [robert.bruce :refer [try-try-again]]) (:import [java.net URLEncoder] [java.util UUID]) (:gen-class)) ; https://graph.facebook.com/v2.7/?access_token=PI:KEY:<KEY>END_PI&ids=https://example.com1,https://example.com2,https://example.com3,https://example.com4,https://example.com5,https://example.com6,https://example.com7,https://example.com8,https://example.com9,https://example.com10 ; Maxmum per Facebook API. (def chunk-size 20) (def facebook-endpoint "https://graph.facebook.com/v2.7/") (def api-token (atom nil)) (def source-token (atom nil)) (defn new-uuid [] (.toString (UUID/randomUUID))) (defn extract-events "Extract a facebook result into a list of event deposits." [facebook-result url-doi-mapping subj-url time-str] (mapcat (fn [[url value]] (let [doi (url-doi-mapping url)] ; DOI should be found. But if FB gives us something back that we didn't recognise we can't. (if (not doi) (do (l/error "Couldn't reverse" url) []) [{:uuid (new-uuid) :source_token @source-token :subj_id subj-url :subj {:pid subj-url :URL "https://facebook.com" :title (str "Facebook activity at " time-str) :type "webpage" :issued time-str} :obj_id (cr-doi/normalise-doi doi) :relation_type_id "discusses" :source_id "facebook" :occurred_at time-str :total (get-in value ["share" "comment_count"] 0)} {:uuid (new-uuid) :source_token @source-token :subj_id subj-url :subj {:pid subj-url :URL "https://facebook.com" :title (str "Facebook activity at " time-str) :type "webpage" :issued time-str} :obj_id (cr-doi/normalise-doi doi) :relation_type_id "bookmarks" :source_id "facebook" :occurred_at time-str :total (get-in value ["share" "share_count"] 0)}]))) facebook-result)) (def facebook-url-date-formatter (f/formatter "yyyy/MM")) (defn fetch "For a URL token and map of url-doi, retrieve all data. Return Evidence Log items." [url-dois] (let [urls (map first url-dois) ; escaped-urls (map #(URLEncoder/encode % "UTF-8") urls) ids-query (clojure.string/join "," urls) result (try-try-again {:sleep 5000 :tries 10} #(deref (http/get facebook-endpoint {:as :text :query-params {"ids" ids-query "access_token" @api-token}}))) now (clj-time/now) subj-url (str "https://facebook.com/" (f/unparse facebook-url-date-formatter now)) ; If there's no body, report that. Status code will also be returned. status (:status result) body (:body result) ok (and body (= status 200)) ; Sometimes non-JSON is sent. If we can't parse return nil. We still record the status and input body. parsed-body (when ok (try (json/read-str body) (catch Exception e nil))) events (when body (extract-events parsed-body url-dois subj-url (str now))) evidence-log {:input-status status :input-headers (:headers result) :input-body body :events events}] evidence-log)) (defn fetch-partition "Fetch chunk of 'doi \n url \n' lines" [counter lines] (let [doi-urls (apply hash-map lines) url-dois (map-invert doi-urls)] (swap! counter #(+ chunk-size %)) ; (l/info "Fetched" @counter) (when (zero? (mod @counter 1)) (l/info "Fetched" @counter)) (fetch url-dois))) (defn -main "I don't do a whole lot ... yet." [& args] (let [api-token-input (first args) url-file (second args) output-file (nth args 2) source-token-input (nth args 3) counter (atom 0)] (reset! api-token api-token-input) (reset! source-token source-token-input) (l/info "URL File " url-file) (l/info "Output file" output-file) (l/info "Source token" source-token) (with-open [rdr (reader url-file)] ; Lines are pairs of "doi \n url \n" ; They are ALWAYS 1-1 mapping so it's OK to invert the map. (let [lines (partition-all (* chunk-size 2) (line-seq rdr)) results (lazy-cat (pmap (partial fetch-partition counter) lines))] (with-open [wrt (writer output-file)] (json/write results wrt)) ; (doseq [result results] ; (prn result)) ))) (shutdown-agents) )
[ { "context": "y number scaling and rounding fns\"\n :author \"Sam Aaron\"}\n overtone.algo.scaling)\n\n(defn closest-to\n \"R", "end": 79, "score": 0.9998869895935059, "start": 70, "tag": "NAME", "value": "Sam Aaron" } ]
src/overtone/algo/scaling.clj
ABaldwinHunter/overtone
3,870
(ns ^{:doc "Handy number scaling and rounding fns" :author "Sam Aaron"} overtone.algo.scaling) (defn closest-to "Returns either low or hi depending on which is numerically closer to n. (closest-to 4.7 4 6) ;=> 4 (4.7 is closer to 4 than 6" [n low hi] (let [low-diff (- n low) hi-diff (- hi n)] (if (< low-diff hi-diff) low hi))) (defn round-to "Rounds n to the nearest multiple of div (round-to 4.7 1) ;=> 5 (round-to 4.7 2) ;=> 4 (4.7 is closer to 4 than 6)" [n div] (let [n (float n) div (float div) remainder (rem n div) low (- n remainder) hi (+ low div)] (closest-to n low hi))) (defn scale-range "Scales a given input value within the specified input range to a corresponding value in the specified output range using the formula: (out-max - out-min) (x - in-min) f (x) = -------------------------------- + out-min in-max - in-min " [x in-min in-max out-min out-max] (+ (/ (* (- out-max out-min) (- x in-min)) (- in-max in-min)) out-min))
43699
(ns ^{:doc "Handy number scaling and rounding fns" :author "<NAME>"} overtone.algo.scaling) (defn closest-to "Returns either low or hi depending on which is numerically closer to n. (closest-to 4.7 4 6) ;=> 4 (4.7 is closer to 4 than 6" [n low hi] (let [low-diff (- n low) hi-diff (- hi n)] (if (< low-diff hi-diff) low hi))) (defn round-to "Rounds n to the nearest multiple of div (round-to 4.7 1) ;=> 5 (round-to 4.7 2) ;=> 4 (4.7 is closer to 4 than 6)" [n div] (let [n (float n) div (float div) remainder (rem n div) low (- n remainder) hi (+ low div)] (closest-to n low hi))) (defn scale-range "Scales a given input value within the specified input range to a corresponding value in the specified output range using the formula: (out-max - out-min) (x - in-min) f (x) = -------------------------------- + out-min in-max - in-min " [x in-min in-max out-min out-max] (+ (/ (* (- out-max out-min) (- x in-min)) (- in-max in-min)) out-min))
true
(ns ^{:doc "Handy number scaling and rounding fns" :author "PI:NAME:<NAME>END_PI"} overtone.algo.scaling) (defn closest-to "Returns either low or hi depending on which is numerically closer to n. (closest-to 4.7 4 6) ;=> 4 (4.7 is closer to 4 than 6" [n low hi] (let [low-diff (- n low) hi-diff (- hi n)] (if (< low-diff hi-diff) low hi))) (defn round-to "Rounds n to the nearest multiple of div (round-to 4.7 1) ;=> 5 (round-to 4.7 2) ;=> 4 (4.7 is closer to 4 than 6)" [n div] (let [n (float n) div (float div) remainder (rem n div) low (- n remainder) hi (+ low div)] (closest-to n low hi))) (defn scale-range "Scales a given input value within the specified input range to a corresponding value in the specified output range using the formula: (out-max - out-min) (x - in-min) f (x) = -------------------------------- + out-min in-max - in-min " [x in-min in-max out-min out-max] (+ (/ (* (- out-max out-min) (- x in-min)) (- in-max in-min)) out-min))
[ { "context": "reating functions and calling them.\"\n\n {:author \"Adam Helinski\"}\n\n (:require [clojure.test.check.properties :as", "end": 101, "score": 0.9987894892692566, "start": 88, "tag": "NAME", "value": "Adam Helinski" } ]
project/break/src/clj/test/convex/test/break/fn.clj
rosejn/convex.cljc
30
(ns convex.test.break.fn "Testing creating functions and calling them." {:author "Adam Helinski"} (:require [clojure.test.check.properties :as TC.prop] [convex.break] [convex.clj.eval :as $.clj.eval] [convex.clj :as $.clj] [convex.clj.gen :as $.clj.gen] [helins.mprop :as mprop])) ;;;;;;;;;; Suites (defn suite-fn? "Tests is `form` evaluates to a function." [form] (mprop/check "`fn?`" ($.clj.eval/result* (fn? ~form)))) (defn suite-fn-call "Tests different ways of calling `form` as a function with `arg+` and ensuring it always returns `ret`." [form arg+ ret] (let [ctx ($.clj.eval/ctx* (def ret ~ret))] (mprop/check "Calling a function" (mprop/mult "Direct call" ($.clj.eval/result* ctx (= ret (~form ~@arg+))) "After def" (let [ctx-2 ($.clj.eval/ctx* ctx (def f ~form))] (mprop/mult "`fn?`" ($.clj.eval/result ctx-2 '(fn? f)) "Calling" ($.clj.eval/result* ctx-2 (= ret (f ~@arg+))))) "From `let`, `fn?`" ($.clj.eval/result* ctx (let [f ~form] (fn? f))) "From `let`, calling" ($.clj.eval/result* ctx (let [f ~form] (= ret (f ~@arg+)))))))) ;;;;;;;;;; Tests (mprop/deftest fn--arg-0 ;; Calling no-arg functions. {:ratio-num 10} (TC.prop/for-all [x $.clj.gen/any] (let [fn-form ($.clj/templ* (fn [] ~x))] (mprop/and (suite-fn? fn-form) (suite-fn-call fn-form nil x))))) (mprop/deftest fn--arg-fixed ;; Calling functions with a fixed number of arguments. {:ratio-num 3} (TC.prop/for-all [binding+ ($.clj.gen/binding+ 1 16)] (let [arg+ (mapv second binding+) sym+ (mapv first binding+) fn-form ($.clj/templ* (fn ~sym+ ~sym+))] (mprop/and (suite-fn? fn-form) (suite-fn-call fn-form arg+ arg+))))) (mprop/deftest fn--variadic ;; Calling functions with a variadic number of arguments. {:ratio-num 3} (TC.prop/for-all [binding+ ($.clj.gen/binding+ 1 16)] (let [arg+ (mapv second binding+) binding+ (mapv first binding+) pos-amper (rand-int (count binding+)) binding-2+ (vec (concat (take pos-amper binding+) ['&] (drop pos-amper binding+))) fn-form ($.clj/templ* (fn ~binding-2+ ~binding+))] (mprop/mult "Right number of arguments" (mprop/and (suite-fn? fn-form) (suite-fn-call fn-form arg+ (update arg+ pos-amper vector))) "1 argument less" (suite-fn-call fn-form (vec (concat (take pos-amper arg+) (drop (inc pos-amper) arg+))) (assoc arg+ pos-amper [])) "Extra argument" (suite-fn-call fn-form (vec (concat (take pos-amper arg+) [42] (drop pos-amper arg+))) (update arg+ pos-amper #(vector 42 %)))))))
124756
(ns convex.test.break.fn "Testing creating functions and calling them." {:author "<NAME>"} (:require [clojure.test.check.properties :as TC.prop] [convex.break] [convex.clj.eval :as $.clj.eval] [convex.clj :as $.clj] [convex.clj.gen :as $.clj.gen] [helins.mprop :as mprop])) ;;;;;;;;;; Suites (defn suite-fn? "Tests is `form` evaluates to a function." [form] (mprop/check "`fn?`" ($.clj.eval/result* (fn? ~form)))) (defn suite-fn-call "Tests different ways of calling `form` as a function with `arg+` and ensuring it always returns `ret`." [form arg+ ret] (let [ctx ($.clj.eval/ctx* (def ret ~ret))] (mprop/check "Calling a function" (mprop/mult "Direct call" ($.clj.eval/result* ctx (= ret (~form ~@arg+))) "After def" (let [ctx-2 ($.clj.eval/ctx* ctx (def f ~form))] (mprop/mult "`fn?`" ($.clj.eval/result ctx-2 '(fn? f)) "Calling" ($.clj.eval/result* ctx-2 (= ret (f ~@arg+))))) "From `let`, `fn?`" ($.clj.eval/result* ctx (let [f ~form] (fn? f))) "From `let`, calling" ($.clj.eval/result* ctx (let [f ~form] (= ret (f ~@arg+)))))))) ;;;;;;;;;; Tests (mprop/deftest fn--arg-0 ;; Calling no-arg functions. {:ratio-num 10} (TC.prop/for-all [x $.clj.gen/any] (let [fn-form ($.clj/templ* (fn [] ~x))] (mprop/and (suite-fn? fn-form) (suite-fn-call fn-form nil x))))) (mprop/deftest fn--arg-fixed ;; Calling functions with a fixed number of arguments. {:ratio-num 3} (TC.prop/for-all [binding+ ($.clj.gen/binding+ 1 16)] (let [arg+ (mapv second binding+) sym+ (mapv first binding+) fn-form ($.clj/templ* (fn ~sym+ ~sym+))] (mprop/and (suite-fn? fn-form) (suite-fn-call fn-form arg+ arg+))))) (mprop/deftest fn--variadic ;; Calling functions with a variadic number of arguments. {:ratio-num 3} (TC.prop/for-all [binding+ ($.clj.gen/binding+ 1 16)] (let [arg+ (mapv second binding+) binding+ (mapv first binding+) pos-amper (rand-int (count binding+)) binding-2+ (vec (concat (take pos-amper binding+) ['&] (drop pos-amper binding+))) fn-form ($.clj/templ* (fn ~binding-2+ ~binding+))] (mprop/mult "Right number of arguments" (mprop/and (suite-fn? fn-form) (suite-fn-call fn-form arg+ (update arg+ pos-amper vector))) "1 argument less" (suite-fn-call fn-form (vec (concat (take pos-amper arg+) (drop (inc pos-amper) arg+))) (assoc arg+ pos-amper [])) "Extra argument" (suite-fn-call fn-form (vec (concat (take pos-amper arg+) [42] (drop pos-amper arg+))) (update arg+ pos-amper #(vector 42 %)))))))
true
(ns convex.test.break.fn "Testing creating functions and calling them." {:author "PI:NAME:<NAME>END_PI"} (:require [clojure.test.check.properties :as TC.prop] [convex.break] [convex.clj.eval :as $.clj.eval] [convex.clj :as $.clj] [convex.clj.gen :as $.clj.gen] [helins.mprop :as mprop])) ;;;;;;;;;; Suites (defn suite-fn? "Tests is `form` evaluates to a function." [form] (mprop/check "`fn?`" ($.clj.eval/result* (fn? ~form)))) (defn suite-fn-call "Tests different ways of calling `form` as a function with `arg+` and ensuring it always returns `ret`." [form arg+ ret] (let [ctx ($.clj.eval/ctx* (def ret ~ret))] (mprop/check "Calling a function" (mprop/mult "Direct call" ($.clj.eval/result* ctx (= ret (~form ~@arg+))) "After def" (let [ctx-2 ($.clj.eval/ctx* ctx (def f ~form))] (mprop/mult "`fn?`" ($.clj.eval/result ctx-2 '(fn? f)) "Calling" ($.clj.eval/result* ctx-2 (= ret (f ~@arg+))))) "From `let`, `fn?`" ($.clj.eval/result* ctx (let [f ~form] (fn? f))) "From `let`, calling" ($.clj.eval/result* ctx (let [f ~form] (= ret (f ~@arg+)))))))) ;;;;;;;;;; Tests (mprop/deftest fn--arg-0 ;; Calling no-arg functions. {:ratio-num 10} (TC.prop/for-all [x $.clj.gen/any] (let [fn-form ($.clj/templ* (fn [] ~x))] (mprop/and (suite-fn? fn-form) (suite-fn-call fn-form nil x))))) (mprop/deftest fn--arg-fixed ;; Calling functions with a fixed number of arguments. {:ratio-num 3} (TC.prop/for-all [binding+ ($.clj.gen/binding+ 1 16)] (let [arg+ (mapv second binding+) sym+ (mapv first binding+) fn-form ($.clj/templ* (fn ~sym+ ~sym+))] (mprop/and (suite-fn? fn-form) (suite-fn-call fn-form arg+ arg+))))) (mprop/deftest fn--variadic ;; Calling functions with a variadic number of arguments. {:ratio-num 3} (TC.prop/for-all [binding+ ($.clj.gen/binding+ 1 16)] (let [arg+ (mapv second binding+) binding+ (mapv first binding+) pos-amper (rand-int (count binding+)) binding-2+ (vec (concat (take pos-amper binding+) ['&] (drop pos-amper binding+))) fn-form ($.clj/templ* (fn ~binding-2+ ~binding+))] (mprop/mult "Right number of arguments" (mprop/and (suite-fn? fn-form) (suite-fn-call fn-form arg+ (update arg+ pos-amper vector))) "1 argument less" (suite-fn-call fn-form (vec (concat (take pos-amper arg+) (drop (inc pos-amper) arg+))) (assoc arg+ pos-amper [])) "Extra argument" (suite-fn-call fn-form (vec (concat (take pos-amper arg+) [42] (drop pos-amper arg+))) (update arg+ pos-amper #(vector 42 %)))))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998136162757874, "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.9998243451118469, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/gviz.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.gviz (:require [dynamo.graph :as g] [clojure.java.io :as io] [clojure.string :as string] [editor.ui :as ui] [editor.fs :as fs]) (:import [java.io File BufferedWriter StringWriter IOException])) (set! *warn-on-reflection* true) (defn installed? [] (try (let [p (.exec (Runtime/getRuntime) "dot -V")] (.waitFor p) (= 0 (.exitValue p))) (catch IOException e false))) (defn- source [[source _ _ _]] source) (defn- target [[_ _ target _]] target) (defn- gen-file [ext] (fs/create-temp-file! "graph" ext)) (defonce ^:private ^:dynamic ^File *dot-file* (gen-file ".dot")) (defonce ^:private ^:dynamic ^File *png-file* (gen-file ".png")) (defn- writer ^BufferedWriter [] (BufferedWriter. (try (io/writer *dot-file*) (catch Throwable t (alter-var-root #'*dot-file* (fn [_] (gen-file ".png"))) (io/writer *dot-file*))))) (defn- write [^BufferedWriter w ^String s] (.write w s) (.newLine w)) (defn- node-type-name [basis node-id] (when-let [t (g/node-type* basis node-id)] (:name @t))) (defn- flatten-arcs [arcs] (mapcat (fn [[nid label-arc]] (mapcat second label-arc)) arcs)) (defn- nodes->arcs [basis nodes] (let [nodes (set nodes)] (seq (into #{} (mapcat (fn [[_ graph]] (->> (concat (filter (fn [a] (or (nodes (:source-id a)) (nodes (:target-id a)))) (flatten-arcs (:sarcs graph))) (filter #(or (nodes (:source-id %)) (nodes (:target-id %))) (flatten-arcs (:tarcs graph)))) (map (fn [a] [(:source-id a) (:source-label a) (:target-id a) (:target-label a)])))) (:graphs basis)))))) (defn escape-field-label [label] (-> label (string/replace " " "\\ ") (string/replace "<" "\\<") (string/replace ">" "\\>") (string/replace "|" "\\|"))) (defn write-node [w basis node-id color inputs outputs] (let [inputs (map name (set (inputs node-id))) outputs (map name (set (outputs node-id))) node-label (node-type-name basis node-id) color (if node-label color "red") node-label (or node-label "Unknown") label (let [input-fields (string/join "|" (map (fn [x] (format "<_in-%s>%s" (escape-field-label x) (escape-field-label x))) inputs)) input-fields (when-not (string/blank? input-fields) (str "{" input-fields "}")) output-fields (string/join "|" (map (fn [x] (format "<_out-%s>%s" (escape-field-label x) (escape-field-label x))) outputs)) output-fields (when-not (string/blank? output-fields) (str "{" output-fields "}")) fields (string/join "|" (remove string/blank? [input-fields output-fields])) fields (when-not (string/blank? fields) (str "{" fields "}"))] (str node-label "|<_nid>" node-id (when-not (string/blank? fields) "|") fields))] (write w (format "%s [shape=record, label=\"%s\", color=\"%s\", fontcolor=\"%s\"];" node-id label color color)))) (defn- include-overrides [basis nodes] (let [child-fn (partial g/overrides basis)] (mapcat #(tree-seq (constantly true) child-fn %) nodes))) (defn- extract-nodes [basis opts] (->> (if (:root-id opts) (let [root-id (:root-id opts) input-fn (:input-fn opts (constantly false)) output-fn (:output-fn opts (constantly false))] (mapcat (fn [[f arcs-fn key]] (g/pre-traverse basis [root-id] (fn [basis node-id] (map key (filter f (arcs-fn basis node-id)))))) [[input-fn g/inputs first] [output-fn g/outputs (comp last butlast)]])) (mapcat (comp keys :nodes second) (:graphs basis))) (include-overrides basis))) (defn subgraph->dot ^String [basis & {:keys [root-id input-fn output-fn] :or {root-id nil} :as opts}] (let [nodes (extract-nodes basis opts) arcs (nodes->arcs basis nodes) inputs (reduce (fn [inputs [s sl t tl]] (update inputs t conj tl)) {} arcs) outputs (reduce (fn [outputs [s sl t tl]] (update outputs s conj sl)) {} arcs) sw (StringWriter.) node-set (set nodes) all-nodes (set (mapcat (comp keys :nodes second) (:graphs basis))) referred-nodes (mapcat (fn [[s _ t _]] [s t]) arcs) excluded-nodes (set (filter (complement node-set) referred-nodes))] (with-open [w (BufferedWriter. sw)] (write w "digraph G {") (write w "rankdir=LR") (doseq [[gid node-ids] (group-by g/node-id->graph-id (concat nodes excluded-nodes))] (write w (format "subgraph %d {" gid)) (doseq [node-id node-ids :let [color (if (excluded-nodes node-id) "grey" "black")]] (write-node w basis node-id color inputs outputs)) (write w "}")) (doseq [[source source-label target target-label] arcs] (let [color (if (or (not (all-nodes source)) (not (all-nodes target))) "red" (if (or (excluded-nodes source) (excluded-nodes target)) "grey" "black"))] (write w (format "%s:\"_out-%s\" -> %s:\"_in-%s\" [color=\"%s\"];" source (name source-label) target (name target-label) color)))) (doseq [node-id nodes] (when-let [original (g/override-original basis node-id)] (write w (format "%s:\"_nid\" -> %s:\"_nid\" [style=dashed];" node-id original)))) (write w "}")) (.toString sw))) (defn dot->image ^File [^String dot] (with-open [w (writer)] (.write w dot)) (let [p (.exec (Runtime/getRuntime) (format "dot %s -Tpng -o%s" *dot-file* *png-file*))] (.waitFor p) (when (= 0 (.exitValue p)) *png-file*))) (defn show [basis & {:keys [root-id input-fn output-fn] :or {root-id nil} :as opts}] (let [f (-> (apply subgraph->dot basis (mapcat identity opts)) (dot->image))] (when f (ui/open-file f))))
72319
;; 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.gviz (:require [dynamo.graph :as g] [clojure.java.io :as io] [clojure.string :as string] [editor.ui :as ui] [editor.fs :as fs]) (:import [java.io File BufferedWriter StringWriter IOException])) (set! *warn-on-reflection* true) (defn installed? [] (try (let [p (.exec (Runtime/getRuntime) "dot -V")] (.waitFor p) (= 0 (.exitValue p))) (catch IOException e false))) (defn- source [[source _ _ _]] source) (defn- target [[_ _ target _]] target) (defn- gen-file [ext] (fs/create-temp-file! "graph" ext)) (defonce ^:private ^:dynamic ^File *dot-file* (gen-file ".dot")) (defonce ^:private ^:dynamic ^File *png-file* (gen-file ".png")) (defn- writer ^BufferedWriter [] (BufferedWriter. (try (io/writer *dot-file*) (catch Throwable t (alter-var-root #'*dot-file* (fn [_] (gen-file ".png"))) (io/writer *dot-file*))))) (defn- write [^BufferedWriter w ^String s] (.write w s) (.newLine w)) (defn- node-type-name [basis node-id] (when-let [t (g/node-type* basis node-id)] (:name @t))) (defn- flatten-arcs [arcs] (mapcat (fn [[nid label-arc]] (mapcat second label-arc)) arcs)) (defn- nodes->arcs [basis nodes] (let [nodes (set nodes)] (seq (into #{} (mapcat (fn [[_ graph]] (->> (concat (filter (fn [a] (or (nodes (:source-id a)) (nodes (:target-id a)))) (flatten-arcs (:sarcs graph))) (filter #(or (nodes (:source-id %)) (nodes (:target-id %))) (flatten-arcs (:tarcs graph)))) (map (fn [a] [(:source-id a) (:source-label a) (:target-id a) (:target-label a)])))) (:graphs basis)))))) (defn escape-field-label [label] (-> label (string/replace " " "\\ ") (string/replace "<" "\\<") (string/replace ">" "\\>") (string/replace "|" "\\|"))) (defn write-node [w basis node-id color inputs outputs] (let [inputs (map name (set (inputs node-id))) outputs (map name (set (outputs node-id))) node-label (node-type-name basis node-id) color (if node-label color "red") node-label (or node-label "Unknown") label (let [input-fields (string/join "|" (map (fn [x] (format "<_in-%s>%s" (escape-field-label x) (escape-field-label x))) inputs)) input-fields (when-not (string/blank? input-fields) (str "{" input-fields "}")) output-fields (string/join "|" (map (fn [x] (format "<_out-%s>%s" (escape-field-label x) (escape-field-label x))) outputs)) output-fields (when-not (string/blank? output-fields) (str "{" output-fields "}")) fields (string/join "|" (remove string/blank? [input-fields output-fields])) fields (when-not (string/blank? fields) (str "{" fields "}"))] (str node-label "|<_nid>" node-id (when-not (string/blank? fields) "|") fields))] (write w (format "%s [shape=record, label=\"%s\", color=\"%s\", fontcolor=\"%s\"];" node-id label color color)))) (defn- include-overrides [basis nodes] (let [child-fn (partial g/overrides basis)] (mapcat #(tree-seq (constantly true) child-fn %) nodes))) (defn- extract-nodes [basis opts] (->> (if (:root-id opts) (let [root-id (:root-id opts) input-fn (:input-fn opts (constantly false)) output-fn (:output-fn opts (constantly false))] (mapcat (fn [[f arcs-fn key]] (g/pre-traverse basis [root-id] (fn [basis node-id] (map key (filter f (arcs-fn basis node-id)))))) [[input-fn g/inputs first] [output-fn g/outputs (comp last butlast)]])) (mapcat (comp keys :nodes second) (:graphs basis))) (include-overrides basis))) (defn subgraph->dot ^String [basis & {:keys [root-id input-fn output-fn] :or {root-id nil} :as opts}] (let [nodes (extract-nodes basis opts) arcs (nodes->arcs basis nodes) inputs (reduce (fn [inputs [s sl t tl]] (update inputs t conj tl)) {} arcs) outputs (reduce (fn [outputs [s sl t tl]] (update outputs s conj sl)) {} arcs) sw (StringWriter.) node-set (set nodes) all-nodes (set (mapcat (comp keys :nodes second) (:graphs basis))) referred-nodes (mapcat (fn [[s _ t _]] [s t]) arcs) excluded-nodes (set (filter (complement node-set) referred-nodes))] (with-open [w (BufferedWriter. sw)] (write w "digraph G {") (write w "rankdir=LR") (doseq [[gid node-ids] (group-by g/node-id->graph-id (concat nodes excluded-nodes))] (write w (format "subgraph %d {" gid)) (doseq [node-id node-ids :let [color (if (excluded-nodes node-id) "grey" "black")]] (write-node w basis node-id color inputs outputs)) (write w "}")) (doseq [[source source-label target target-label] arcs] (let [color (if (or (not (all-nodes source)) (not (all-nodes target))) "red" (if (or (excluded-nodes source) (excluded-nodes target)) "grey" "black"))] (write w (format "%s:\"_out-%s\" -> %s:\"_in-%s\" [color=\"%s\"];" source (name source-label) target (name target-label) color)))) (doseq [node-id nodes] (when-let [original (g/override-original basis node-id)] (write w (format "%s:\"_nid\" -> %s:\"_nid\" [style=dashed];" node-id original)))) (write w "}")) (.toString sw))) (defn dot->image ^File [^String dot] (with-open [w (writer)] (.write w dot)) (let [p (.exec (Runtime/getRuntime) (format "dot %s -Tpng -o%s" *dot-file* *png-file*))] (.waitFor p) (when (= 0 (.exitValue p)) *png-file*))) (defn show [basis & {:keys [root-id input-fn output-fn] :or {root-id nil} :as opts}] (let [f (-> (apply subgraph->dot basis (mapcat identity opts)) (dot->image))] (when f (ui/open-file f))))
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.gviz (:require [dynamo.graph :as g] [clojure.java.io :as io] [clojure.string :as string] [editor.ui :as ui] [editor.fs :as fs]) (:import [java.io File BufferedWriter StringWriter IOException])) (set! *warn-on-reflection* true) (defn installed? [] (try (let [p (.exec (Runtime/getRuntime) "dot -V")] (.waitFor p) (= 0 (.exitValue p))) (catch IOException e false))) (defn- source [[source _ _ _]] source) (defn- target [[_ _ target _]] target) (defn- gen-file [ext] (fs/create-temp-file! "graph" ext)) (defonce ^:private ^:dynamic ^File *dot-file* (gen-file ".dot")) (defonce ^:private ^:dynamic ^File *png-file* (gen-file ".png")) (defn- writer ^BufferedWriter [] (BufferedWriter. (try (io/writer *dot-file*) (catch Throwable t (alter-var-root #'*dot-file* (fn [_] (gen-file ".png"))) (io/writer *dot-file*))))) (defn- write [^BufferedWriter w ^String s] (.write w s) (.newLine w)) (defn- node-type-name [basis node-id] (when-let [t (g/node-type* basis node-id)] (:name @t))) (defn- flatten-arcs [arcs] (mapcat (fn [[nid label-arc]] (mapcat second label-arc)) arcs)) (defn- nodes->arcs [basis nodes] (let [nodes (set nodes)] (seq (into #{} (mapcat (fn [[_ graph]] (->> (concat (filter (fn [a] (or (nodes (:source-id a)) (nodes (:target-id a)))) (flatten-arcs (:sarcs graph))) (filter #(or (nodes (:source-id %)) (nodes (:target-id %))) (flatten-arcs (:tarcs graph)))) (map (fn [a] [(:source-id a) (:source-label a) (:target-id a) (:target-label a)])))) (:graphs basis)))))) (defn escape-field-label [label] (-> label (string/replace " " "\\ ") (string/replace "<" "\\<") (string/replace ">" "\\>") (string/replace "|" "\\|"))) (defn write-node [w basis node-id color inputs outputs] (let [inputs (map name (set (inputs node-id))) outputs (map name (set (outputs node-id))) node-label (node-type-name basis node-id) color (if node-label color "red") node-label (or node-label "Unknown") label (let [input-fields (string/join "|" (map (fn [x] (format "<_in-%s>%s" (escape-field-label x) (escape-field-label x))) inputs)) input-fields (when-not (string/blank? input-fields) (str "{" input-fields "}")) output-fields (string/join "|" (map (fn [x] (format "<_out-%s>%s" (escape-field-label x) (escape-field-label x))) outputs)) output-fields (when-not (string/blank? output-fields) (str "{" output-fields "}")) fields (string/join "|" (remove string/blank? [input-fields output-fields])) fields (when-not (string/blank? fields) (str "{" fields "}"))] (str node-label "|<_nid>" node-id (when-not (string/blank? fields) "|") fields))] (write w (format "%s [shape=record, label=\"%s\", color=\"%s\", fontcolor=\"%s\"];" node-id label color color)))) (defn- include-overrides [basis nodes] (let [child-fn (partial g/overrides basis)] (mapcat #(tree-seq (constantly true) child-fn %) nodes))) (defn- extract-nodes [basis opts] (->> (if (:root-id opts) (let [root-id (:root-id opts) input-fn (:input-fn opts (constantly false)) output-fn (:output-fn opts (constantly false))] (mapcat (fn [[f arcs-fn key]] (g/pre-traverse basis [root-id] (fn [basis node-id] (map key (filter f (arcs-fn basis node-id)))))) [[input-fn g/inputs first] [output-fn g/outputs (comp last butlast)]])) (mapcat (comp keys :nodes second) (:graphs basis))) (include-overrides basis))) (defn subgraph->dot ^String [basis & {:keys [root-id input-fn output-fn] :or {root-id nil} :as opts}] (let [nodes (extract-nodes basis opts) arcs (nodes->arcs basis nodes) inputs (reduce (fn [inputs [s sl t tl]] (update inputs t conj tl)) {} arcs) outputs (reduce (fn [outputs [s sl t tl]] (update outputs s conj sl)) {} arcs) sw (StringWriter.) node-set (set nodes) all-nodes (set (mapcat (comp keys :nodes second) (:graphs basis))) referred-nodes (mapcat (fn [[s _ t _]] [s t]) arcs) excluded-nodes (set (filter (complement node-set) referred-nodes))] (with-open [w (BufferedWriter. sw)] (write w "digraph G {") (write w "rankdir=LR") (doseq [[gid node-ids] (group-by g/node-id->graph-id (concat nodes excluded-nodes))] (write w (format "subgraph %d {" gid)) (doseq [node-id node-ids :let [color (if (excluded-nodes node-id) "grey" "black")]] (write-node w basis node-id color inputs outputs)) (write w "}")) (doseq [[source source-label target target-label] arcs] (let [color (if (or (not (all-nodes source)) (not (all-nodes target))) "red" (if (or (excluded-nodes source) (excluded-nodes target)) "grey" "black"))] (write w (format "%s:\"_out-%s\" -> %s:\"_in-%s\" [color=\"%s\"];" source (name source-label) target (name target-label) color)))) (doseq [node-id nodes] (when-let [original (g/override-original basis node-id)] (write w (format "%s:\"_nid\" -> %s:\"_nid\" [style=dashed];" node-id original)))) (write w "}")) (.toString sw))) (defn dot->image ^File [^String dot] (with-open [w (writer)] (.write w dot)) (let [p (.exec (Runtime/getRuntime) (format "dot %s -Tpng -o%s" *dot-file* *png-file*))] (.waitFor p) (when (= 0 (.exitValue p)) *png-file*))) (defn show [basis & {:keys [root-id input-fn output-fn] :or {root-id nil} :as opts}] (let [f (-> (apply subgraph->dot basis (mapcat identity opts)) (dot->image))] (when f (ui/open-file f))))
[ { "context": ";; Copyright 2013-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li", "end": 36, "score": 0.999882698059082, "start": 23, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright 2013-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version", "end": 50, "score": 0.9999317526817322, "start": 38, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/buddy/auth/backends/token.clj
eipplusone/buddy-auth
292
;; Copyright 2013-2016 Andrey Antukh <niwi@niwi.nz> ;; ;; 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 buddy.auth.backends.token "The token based authentication and authorization backend." (:require [buddy.auth.protocols :as proto] [buddy.auth.http :as http] [buddy.auth :refer [authenticated?]] [buddy.sign.jwt :as jwt])) (defn- handle-unauthorized-default "A default response constructor for an unauthorized request." [request] (if (authenticated? request) {:status 403 :headers {} :body "Permission denied"} {:status 401 :headers {} :body "Unauthorized"})) (defn- parse-header [request token-name] (some->> (http/-get-header request "authorization") (re-find (re-pattern (str "^" token-name " (.+)$"))) (second))) (defn jws-backend [{:keys [secret authfn unauthorized-handler options token-name on-error] :or {authfn identity token-name "Token"}}] {:pre [(ifn? authfn)]} (reify proto/IAuthentication (-parse [_ request] (parse-header request token-name)) (-authenticate [_ request data] (try (authfn (jwt/unsign data secret options)) (catch clojure.lang.ExceptionInfo e (let [data (ex-data e)] (when (fn? on-error) (on-error request e)) nil)))) proto/IAuthorization (-handle-unauthorized [_ request metadata] (if unauthorized-handler (unauthorized-handler request metadata) (handle-unauthorized-default request))))) (defn jwe-backend [{:keys [secret authfn unauthorized-handler options token-name on-error] :or {authfn identity token-name "Token"}}] {:pre [(ifn? authfn)]} (reify proto/IAuthentication (-parse [_ request] (parse-header request token-name)) (-authenticate [_ request data] (try (authfn (jwt/decrypt data secret options)) (catch clojure.lang.ExceptionInfo e (when (fn? on-error) (on-error request e)) nil))) proto/IAuthorization (-handle-unauthorized [_ request metadata] (if unauthorized-handler (unauthorized-handler request metadata) (handle-unauthorized-default request))))) (defn token-backend [{:keys [authfn unauthorized-handler token-name] :or {token-name "Token"}}] {:pre [(ifn? authfn)]} (reify proto/IAuthentication (-parse [_ request] (parse-header request token-name)) (-authenticate [_ request token] (authfn request token)) proto/IAuthorization (-handle-unauthorized [_ request metadata] (if unauthorized-handler (unauthorized-handler request metadata) (handle-unauthorized-default request)))))
46217
;; Copyright 2013-2016 <NAME> <<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 buddy.auth.backends.token "The token based authentication and authorization backend." (:require [buddy.auth.protocols :as proto] [buddy.auth.http :as http] [buddy.auth :refer [authenticated?]] [buddy.sign.jwt :as jwt])) (defn- handle-unauthorized-default "A default response constructor for an unauthorized request." [request] (if (authenticated? request) {:status 403 :headers {} :body "Permission denied"} {:status 401 :headers {} :body "Unauthorized"})) (defn- parse-header [request token-name] (some->> (http/-get-header request "authorization") (re-find (re-pattern (str "^" token-name " (.+)$"))) (second))) (defn jws-backend [{:keys [secret authfn unauthorized-handler options token-name on-error] :or {authfn identity token-name "Token"}}] {:pre [(ifn? authfn)]} (reify proto/IAuthentication (-parse [_ request] (parse-header request token-name)) (-authenticate [_ request data] (try (authfn (jwt/unsign data secret options)) (catch clojure.lang.ExceptionInfo e (let [data (ex-data e)] (when (fn? on-error) (on-error request e)) nil)))) proto/IAuthorization (-handle-unauthorized [_ request metadata] (if unauthorized-handler (unauthorized-handler request metadata) (handle-unauthorized-default request))))) (defn jwe-backend [{:keys [secret authfn unauthorized-handler options token-name on-error] :or {authfn identity token-name "Token"}}] {:pre [(ifn? authfn)]} (reify proto/IAuthentication (-parse [_ request] (parse-header request token-name)) (-authenticate [_ request data] (try (authfn (jwt/decrypt data secret options)) (catch clojure.lang.ExceptionInfo e (when (fn? on-error) (on-error request e)) nil))) proto/IAuthorization (-handle-unauthorized [_ request metadata] (if unauthorized-handler (unauthorized-handler request metadata) (handle-unauthorized-default request))))) (defn token-backend [{:keys [authfn unauthorized-handler token-name] :or {token-name "Token"}}] {:pre [(ifn? authfn)]} (reify proto/IAuthentication (-parse [_ request] (parse-header request token-name)) (-authenticate [_ request token] (authfn request token)) proto/IAuthorization (-handle-unauthorized [_ request metadata] (if unauthorized-handler (unauthorized-handler request metadata) (handle-unauthorized-default request)))))
true
;; Copyright 2013-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns buddy.auth.backends.token "The token based authentication and authorization backend." (:require [buddy.auth.protocols :as proto] [buddy.auth.http :as http] [buddy.auth :refer [authenticated?]] [buddy.sign.jwt :as jwt])) (defn- handle-unauthorized-default "A default response constructor for an unauthorized request." [request] (if (authenticated? request) {:status 403 :headers {} :body "Permission denied"} {:status 401 :headers {} :body "Unauthorized"})) (defn- parse-header [request token-name] (some->> (http/-get-header request "authorization") (re-find (re-pattern (str "^" token-name " (.+)$"))) (second))) (defn jws-backend [{:keys [secret authfn unauthorized-handler options token-name on-error] :or {authfn identity token-name "Token"}}] {:pre [(ifn? authfn)]} (reify proto/IAuthentication (-parse [_ request] (parse-header request token-name)) (-authenticate [_ request data] (try (authfn (jwt/unsign data secret options)) (catch clojure.lang.ExceptionInfo e (let [data (ex-data e)] (when (fn? on-error) (on-error request e)) nil)))) proto/IAuthorization (-handle-unauthorized [_ request metadata] (if unauthorized-handler (unauthorized-handler request metadata) (handle-unauthorized-default request))))) (defn jwe-backend [{:keys [secret authfn unauthorized-handler options token-name on-error] :or {authfn identity token-name "Token"}}] {:pre [(ifn? authfn)]} (reify proto/IAuthentication (-parse [_ request] (parse-header request token-name)) (-authenticate [_ request data] (try (authfn (jwt/decrypt data secret options)) (catch clojure.lang.ExceptionInfo e (when (fn? on-error) (on-error request e)) nil))) proto/IAuthorization (-handle-unauthorized [_ request metadata] (if unauthorized-handler (unauthorized-handler request metadata) (handle-unauthorized-default request))))) (defn token-backend [{:keys [authfn unauthorized-handler token-name] :or {token-name "Token"}}] {:pre [(ifn? authfn)]} (reify proto/IAuthentication (-parse [_ request] (parse-header request token-name)) (-authenticate [_ request token] (authfn request token)) proto/IAuthorization (-handle-unauthorized [_ request metadata] (if unauthorized-handler (unauthorized-handler request metadata) (handle-unauthorized-default request)))))
[ { "context": "MQ$Poller]))\n\n;;\n;; Simple request-reply broker\n;; Isaiah Peng <issaria@gmail.com>\n;;\n\n(defn -main []\n (let [ct", "end": 165, "score": 0.9998581409454346, "start": 154, "tag": "NAME", "value": "Isaiah Peng" }, { "context": ";;\n;; Simple request-reply broker\n;; Isaiah Peng <issaria@gmail.com>\n;;\n\n(defn -main []\n (let [ctx (mq/context 1)\n ", "end": 184, "score": 0.9999260902404785, "start": 167, "tag": "EMAIL", "value": "issaria@gmail.com" } ]
docs/zeroMQ-guide2/examples/Clojure/rrbroker.clj
krattai/noo-ebs
2
(ns rrbroker (:refer-clojure :exclude [send]) (:require [zhelpers :as mq]) (:import [org.zeromq ZMQ$Poller])) ;; ;; Simple request-reply broker ;; Isaiah Peng <issaria@gmail.com> ;; (defn -main [] (let [ctx (mq/context 1) frontend (mq/socket ctx mq/router) backend (mq/socket ctx mq/dealer) items (.poller ctx 2)] (mq/bind frontend "tcp://*:5559") (mq/bind backend "tcp://*:5560") (.register items frontend ZMQ$Poller/POLLIN) (.register items backend ZMQ$Poller/POLLIN) (while (not (.isInterrupted (Thread/currentThread))) (.poll items 250000) (if (.pollin items 0) (loop [#^String message (mq/recv-str frontend)] (let [more (.hasReceiveMore frontend)] (if more (do (mq/send-more backend message) (recur (mq/recv-str frontend))) (mq/send backend message))))) (if (.pollin items 1) (loop [#^String message (mq/recv-str backend)] (let [more (.hasReceiveMore backend)] (if more (do (mq/send-more frontend message) (recur (mq/recv-str backend))) (mq/send frontend message)))))) (.close frontend) (.close backend) (.term ctx)))
111621
(ns rrbroker (:refer-clojure :exclude [send]) (:require [zhelpers :as mq]) (:import [org.zeromq ZMQ$Poller])) ;; ;; Simple request-reply broker ;; <NAME> <<EMAIL>> ;; (defn -main [] (let [ctx (mq/context 1) frontend (mq/socket ctx mq/router) backend (mq/socket ctx mq/dealer) items (.poller ctx 2)] (mq/bind frontend "tcp://*:5559") (mq/bind backend "tcp://*:5560") (.register items frontend ZMQ$Poller/POLLIN) (.register items backend ZMQ$Poller/POLLIN) (while (not (.isInterrupted (Thread/currentThread))) (.poll items 250000) (if (.pollin items 0) (loop [#^String message (mq/recv-str frontend)] (let [more (.hasReceiveMore frontend)] (if more (do (mq/send-more backend message) (recur (mq/recv-str frontend))) (mq/send backend message))))) (if (.pollin items 1) (loop [#^String message (mq/recv-str backend)] (let [more (.hasReceiveMore backend)] (if more (do (mq/send-more frontend message) (recur (mq/recv-str backend))) (mq/send frontend message)))))) (.close frontend) (.close backend) (.term ctx)))
true
(ns rrbroker (:refer-clojure :exclude [send]) (:require [zhelpers :as mq]) (:import [org.zeromq ZMQ$Poller])) ;; ;; Simple request-reply broker ;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; (defn -main [] (let [ctx (mq/context 1) frontend (mq/socket ctx mq/router) backend (mq/socket ctx mq/dealer) items (.poller ctx 2)] (mq/bind frontend "tcp://*:5559") (mq/bind backend "tcp://*:5560") (.register items frontend ZMQ$Poller/POLLIN) (.register items backend ZMQ$Poller/POLLIN) (while (not (.isInterrupted (Thread/currentThread))) (.poll items 250000) (if (.pollin items 0) (loop [#^String message (mq/recv-str frontend)] (let [more (.hasReceiveMore frontend)] (if more (do (mq/send-more backend message) (recur (mq/recv-str frontend))) (mq/send backend message))))) (if (.pollin items 1) (loop [#^String message (mq/recv-str backend)] (let [more (.hasReceiveMore backend)] (if more (do (mq/send-more frontend message) (recur (mq/recv-str backend))) (mq/send frontend message)))))) (.close frontend) (.close backend) (.term ctx)))
[ { "context": "tgresql://localhost:60600/test?user=test&password=test\")\n(def last-query-result (atom nil))\n\n(defn displ", "end": 299, "score": 0.9986065030097961, "start": 295, "tag": "PASSWORD", "value": "test" } ]
src/clj/sql/executor.clj
jussijartamo/sql
0
(ns sql.executor (:require [clojure.core.match :refer [match]] [clojure.pprint :as pp] [sql.schema :refer [metadata->schema]]) (:import ;(org.postgresql.util PGobject) (java.sql DriverManager))) (def url "jdbc:postgresql://localhost:60600/test?user=test&password=test") (def last-query-result (atom nil)) (defn display-schema [] (with-open [conn (DriverManager/getConnection url)] (doall (metadata->schema conn)))) (defn transform-value [v] (str v)) (defn transform-values [v] (map transform-value v)) (defn query [sql uuid] (with-open [conn (DriverManager/getConnection url)] (if-let [a (resultset-seq (-> conn .createStatement (.executeQuery sql)))] (let [only-values (doall (mapv #(vec (vals %)) a))] (reset! last-query-result {:uuid uuid :result only-values}) (if a {:columns (keys (first a)) :rows (doall (map transform-values only-values))})) {:columns [] :rows []}))) (defn execute [command] (match command {:command "schema"} (display-schema) {:command "query" :sql sql :uuid uuid} (query sql uuid)))
68104
(ns sql.executor (:require [clojure.core.match :refer [match]] [clojure.pprint :as pp] [sql.schema :refer [metadata->schema]]) (:import ;(org.postgresql.util PGobject) (java.sql DriverManager))) (def url "jdbc:postgresql://localhost:60600/test?user=test&password=<PASSWORD>") (def last-query-result (atom nil)) (defn display-schema [] (with-open [conn (DriverManager/getConnection url)] (doall (metadata->schema conn)))) (defn transform-value [v] (str v)) (defn transform-values [v] (map transform-value v)) (defn query [sql uuid] (with-open [conn (DriverManager/getConnection url)] (if-let [a (resultset-seq (-> conn .createStatement (.executeQuery sql)))] (let [only-values (doall (mapv #(vec (vals %)) a))] (reset! last-query-result {:uuid uuid :result only-values}) (if a {:columns (keys (first a)) :rows (doall (map transform-values only-values))})) {:columns [] :rows []}))) (defn execute [command] (match command {:command "schema"} (display-schema) {:command "query" :sql sql :uuid uuid} (query sql uuid)))
true
(ns sql.executor (:require [clojure.core.match :refer [match]] [clojure.pprint :as pp] [sql.schema :refer [metadata->schema]]) (:import ;(org.postgresql.util PGobject) (java.sql DriverManager))) (def url "jdbc:postgresql://localhost:60600/test?user=test&password=PI:PASSWORD:<PASSWORD>END_PI") (def last-query-result (atom nil)) (defn display-schema [] (with-open [conn (DriverManager/getConnection url)] (doall (metadata->schema conn)))) (defn transform-value [v] (str v)) (defn transform-values [v] (map transform-value v)) (defn query [sql uuid] (with-open [conn (DriverManager/getConnection url)] (if-let [a (resultset-seq (-> conn .createStatement (.executeQuery sql)))] (let [only-values (doall (mapv #(vec (vals %)) a))] (reset! last-query-result {:uuid uuid :result only-values}) (if a {:columns (keys (first a)) :rows (doall (map transform-values only-values))})) {:columns [] :rows []}))) (defn execute [command] (match command {:command "schema"} (display-schema) {:command "query" :sql sql :uuid uuid} (query sql uuid)))
[ { "context": "frame.core :as rf]))\n\n(def data [{:db/id 1 :name \"Petr\" :aka [\"Devil\"]}])\n(defonce db (atom (dx/create-d", "end": 144, "score": 0.9935077428817749, "start": 140, "tag": "NAME", "value": "Petr" }, { "context": "s rf]))\n\n(def data [{:db/id 1 :name \"Petr\" :aka [\"Devil\"]}])\n(defonce db (atom (dx/create-dx data)))\n(dx/", "end": 158, "score": 0.9969227313995361, "start": 153, "tag": "NAME", "value": "Devil" }, { "context": "data)))\n(dx/commit! db [[:dx/put {:db/id 2 :name \"David2\" :aka [\"Devil\"]}]])\n(dx/commit! db [[:dx/put {:d", "end": 251, "score": 0.8547335863113403, "start": 246, "tag": "NAME", "value": "David" }, { "context": "))\n(dx/commit! db [[:dx/put {:db/id 2 :name \"David2\" :aka [\"Devil\"]}]])\n(dx/commit! db [[:dx/put {:db", "end": 252, "score": 0.7650060653686523, "start": 251, "tag": "USERNAME", "value": "2" }, { "context": "mit! db [[:dx/put {:db/id 2 :name \"David2\" :aka [\"Devil\"]}]])\n(dx/commit! db [[:dx/put {:db/id 3 :name \"D", "end": 266, "score": 0.9910290241241455, "start": 261, "tag": "NAME", "value": "Devil" }, { "context": "l\"]}]])\n(dx/commit! db [[:dx/put {:db/id 3 :name \"David3\" :aka [\"Devil\"]}]])\n\n(dx/pull @db [:name] [:db/i", "end": 320, "score": 0.9253259301185608, "start": 315, "tag": "NAME", "value": "David" }, { "context": "])\n(dx/commit! db [[:dx/put {:db/id 3 :name \"David3\" :aka [\"Devil\"]}]])\n\n(dx/pull @db [:name] [:db/id", "end": 321, "score": 0.7044737339019775, "start": 320, "tag": "USERNAME", "value": "3" }, { "context": "mit! db [[:dx/put {:db/id 3 :name \"David3\" :aka [\"Devil\"]}]])\n\n(dx/pull @db [:name] [:db/id 2])\n(dx/pull ", "end": 335, "score": 0.985632061958313, "start": 330, "tag": "NAME", "value": "Devil" } ]
src/rf_doxa/doxa_gist_2.cljs
ribelo/rf-doxa-etude
0
(ns rf-doxa.doxa-gist-2 "Adapted from" (:require [ribelo.doxa :as dx] [re-frame.core :as rf])) (def data [{:db/id 1 :name "Petr" :aka ["Devil"]}]) (defonce db (atom (dx/create-dx data))) (dx/commit! db [[:dx/put {:db/id 2 :name "David2" :aka ["Devil"]}]]) (dx/commit! db [[:dx/put {:db/id 3 :name "David3" :aka ["Devil"]}]]) (dx/pull @db [:name] [:db/id 2]) (dx/pull @db {[:db/id 2] [:name]}) (dx/q [:find ?e ; be sure to start symbols with ?, otherwise won't work :where [?e :name]] @db)
55768
(ns rf-doxa.doxa-gist-2 "Adapted from" (:require [ribelo.doxa :as dx] [re-frame.core :as rf])) (def data [{:db/id 1 :name "<NAME>" :aka ["<NAME>"]}]) (defonce db (atom (dx/create-dx data))) (dx/commit! db [[:dx/put {:db/id 2 :name "<NAME>2" :aka ["<NAME>"]}]]) (dx/commit! db [[:dx/put {:db/id 3 :name "<NAME>3" :aka ["<NAME>"]}]]) (dx/pull @db [:name] [:db/id 2]) (dx/pull @db {[:db/id 2] [:name]}) (dx/q [:find ?e ; be sure to start symbols with ?, otherwise won't work :where [?e :name]] @db)
true
(ns rf-doxa.doxa-gist-2 "Adapted from" (:require [ribelo.doxa :as dx] [re-frame.core :as rf])) (def data [{:db/id 1 :name "PI:NAME:<NAME>END_PI" :aka ["PI:NAME:<NAME>END_PI"]}]) (defonce db (atom (dx/create-dx data))) (dx/commit! db [[:dx/put {:db/id 2 :name "PI:NAME:<NAME>END_PI2" :aka ["PI:NAME:<NAME>END_PI"]}]]) (dx/commit! db [[:dx/put {:db/id 3 :name "PI:NAME:<NAME>END_PI3" :aka ["PI:NAME:<NAME>END_PI"]}]]) (dx/pull @db [:name] [:db/id 2]) (dx/pull @db {[:db/id 2] [:name]}) (dx/q [:find ?e ; be sure to start symbols with ?, otherwise won't work :where [?e :name]] @db)
[ { "context": "ISC License\"\n :url \"https://github.com/johanthoren/redbubble-helper\"\n :year 2020\n ", "end": 138, "score": 0.9975140690803528, "start": 127, "tag": "USERNAME", "value": "johanthoren" }, { "context": " images suitable for Redbubble.\"\n :vendor \"Johan Thorén <johan@thoren.xyz>\"\n :packager \"Johan Thor", "end": 1177, "score": 0.9998800754547119, "start": 1165, "tag": "NAME", "value": "Johan Thorén" }, { "context": "le for Redbubble.\"\n :vendor \"Johan Thorén <johan@thoren.xyz>\"\n :packager \"Johan Thorén <johan@thoren.x", "end": 1195, "score": 0.9999291300773621, "start": 1179, "tag": "EMAIL", "value": "johan@thoren.xyz" }, { "context": "han Thorén <johan@thoren.xyz>\"\n :packager \"Johan Thorén <johan@thoren.xyz>\"\n :release \"1\"\n ", "end": 1229, "score": 0.999716579914093, "start": 1217, "tag": "NAME", "value": "Johan Thorén" }, { "context": "han@thoren.xyz>\"\n :packager \"Johan Thorén <johan@thoren.xyz>\"\n :release \"1\"\n :provides \"rbh\"\n ", "end": 1247, "score": 0.9999296069145203, "start": 1231, "tag": "EMAIL", "value": "johan@thoren.xyz" } ]
project.clj
johanthoren/redbubble-helper
2
(defproject rbh "0.1.1" :description "Redbubble Helper" :license {:name "ISC License" :url "https://github.com/johanthoren/redbubble-helper" :year 2020 :key "isc"} :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/tools.cli "0.4.2"] [org.clojure/tools.logging "0.6.0"] [clj-commons/fs "1.5.0"] [clj-logging-config "1.9.12"] [simple-progress "0.1.3"] [trptcolin/versioneer "0.2.0"]] :main rbh.core :target-path "target/%s" :aliases {"deb" ["shell" "bash" "build-deb.sh" "redbubble-helper" "imagemagick (>= 8:6.9.2.10-dfsg-2~), inkscape (>= 0.92.4-4), openjdk-8-jre-headless" "Redbubble Helper" "rbh" "A simple CLI tool to generate images suitable for Redbubble."]} :profiles {:uberjar {:aot :all}} :plugins [[lein-redline-rpm "0.4.3"] [lein-shell "0.5.0"]] :bin {:name "rbh"} :rpm {:package-name "redbubble-helper" :distribution "Redbubble Helper" :summary "A simple CLI tool to generate images suitable for Redbubble." :vendor "Johan Thorén <johan@thoren.xyz>" :packager "Johan Thorén <johan@thoren.xyz>" :release "1" :provides "rbh" :requires [["ImageMagick" "<<" "7"] ["inkscape" ">=" "0.92.2"] ["java-11-openjdk-headless" ">=" "11"]] :files [["target/default/rbh" "/usr/local/bin/rbh" 0755 0750 "root" "root"]]})
103443
(defproject rbh "0.1.1" :description "Redbubble Helper" :license {:name "ISC License" :url "https://github.com/johanthoren/redbubble-helper" :year 2020 :key "isc"} :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/tools.cli "0.4.2"] [org.clojure/tools.logging "0.6.0"] [clj-commons/fs "1.5.0"] [clj-logging-config "1.9.12"] [simple-progress "0.1.3"] [trptcolin/versioneer "0.2.0"]] :main rbh.core :target-path "target/%s" :aliases {"deb" ["shell" "bash" "build-deb.sh" "redbubble-helper" "imagemagick (>= 8:6.9.2.10-dfsg-2~), inkscape (>= 0.92.4-4), openjdk-8-jre-headless" "Redbubble Helper" "rbh" "A simple CLI tool to generate images suitable for Redbubble."]} :profiles {:uberjar {:aot :all}} :plugins [[lein-redline-rpm "0.4.3"] [lein-shell "0.5.0"]] :bin {:name "rbh"} :rpm {:package-name "redbubble-helper" :distribution "Redbubble Helper" :summary "A simple CLI tool to generate images suitable for Redbubble." :vendor "<NAME> <<EMAIL>>" :packager "<NAME> <<EMAIL>>" :release "1" :provides "rbh" :requires [["ImageMagick" "<<" "7"] ["inkscape" ">=" "0.92.2"] ["java-11-openjdk-headless" ">=" "11"]] :files [["target/default/rbh" "/usr/local/bin/rbh" 0755 0750 "root" "root"]]})
true
(defproject rbh "0.1.1" :description "Redbubble Helper" :license {:name "ISC License" :url "https://github.com/johanthoren/redbubble-helper" :year 2020 :key "isc"} :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/tools.cli "0.4.2"] [org.clojure/tools.logging "0.6.0"] [clj-commons/fs "1.5.0"] [clj-logging-config "1.9.12"] [simple-progress "0.1.3"] [trptcolin/versioneer "0.2.0"]] :main rbh.core :target-path "target/%s" :aliases {"deb" ["shell" "bash" "build-deb.sh" "redbubble-helper" "imagemagick (>= 8:6.9.2.10-dfsg-2~), inkscape (>= 0.92.4-4), openjdk-8-jre-headless" "Redbubble Helper" "rbh" "A simple CLI tool to generate images suitable for Redbubble."]} :profiles {:uberjar {:aot :all}} :plugins [[lein-redline-rpm "0.4.3"] [lein-shell "0.5.0"]] :bin {:name "rbh"} :rpm {:package-name "redbubble-helper" :distribution "Redbubble Helper" :summary "A simple CLI tool to generate images suitable for Redbubble." :vendor "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :packager "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :release "1" :provides "rbh" :requires [["ImageMagick" "<<" "7"] ["inkscape" ">=" "0.92.2"] ["java-11-openjdk-headless" ">=" "11"]] :files [["target/default/rbh" "/usr/local/bin/rbh" 0755 0750 "root" "root"]]})
[ { "context": "unindexed_csv.csv\")))\n\n(deftest federer\n (is (= \"Roger Federer\"\n (:winner_name (first (ex/federer-wins d", "end": 422, "score": 0.9998791813850403, "start": 409, "tag": "NAME", "value": "Roger Federer" } ]
Chapter04/tests/packt-clj.chapter-4-tests/test/packt_clj/chapter_4_tests/exercise_4_13_test.clj
transducer/The-Clojure-Workshop
55
(ns packt-clj.exercise-4-13-test (:require [clojure.test :as t :refer [deftest is testing]] [clojure.data.csv :as csv] [clojure.java.io :as io] [semantic-csv.core :as sc] [packt-clj.chapter-4-tests.exercise-4-13 :as ex])) ;;; For convenience, we reference the csv file as a resource. (def data (io/file (io/resource "match_scores_1991-2016_unindexed_csv.csv"))) (deftest federer (is (= "Roger Federer" (:winner_name (first (ex/federer-wins data))))))
39937
(ns packt-clj.exercise-4-13-test (:require [clojure.test :as t :refer [deftest is testing]] [clojure.data.csv :as csv] [clojure.java.io :as io] [semantic-csv.core :as sc] [packt-clj.chapter-4-tests.exercise-4-13 :as ex])) ;;; For convenience, we reference the csv file as a resource. (def data (io/file (io/resource "match_scores_1991-2016_unindexed_csv.csv"))) (deftest federer (is (= "<NAME>" (:winner_name (first (ex/federer-wins data))))))
true
(ns packt-clj.exercise-4-13-test (:require [clojure.test :as t :refer [deftest is testing]] [clojure.data.csv :as csv] [clojure.java.io :as io] [semantic-csv.core :as sc] [packt-clj.chapter-4-tests.exercise-4-13 :as ex])) ;;; For convenience, we reference the csv file as a resource. (def data (io/file (io/resource "match_scores_1991-2016_unindexed_csv.csv"))) (deftest federer (is (= "PI:NAME:<NAME>END_PI" (:winner_name (first (ex/federer-wins data))))))
[ { "context": ";;; Copyright 2012 Hubert Iwaniuk\n\n;;; Licensed under the Apache License, Version 2", "end": 33, "score": 0.9998844265937805, "start": 19, "tag": "NAME", "value": "Hubert Iwaniuk" }, { "context": "TTP Client - Clojure - Multipart API\"\n {:author \"Hubert Iwaniuk\"}\n (:import (java.nio.charset Charset)\n ", "end": 699, "score": 0.9998915791511536, "start": 685, "tag": "NAME", "value": "Hubert Iwaniuk" } ]
src/clj/http/async/client/part.clj
gelatikmannah/cch1
0
;;; Copyright 2012 Hubert Iwaniuk ;;; 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 http.async.client.part "Asynchronous HTTP Client - Clojure - Multipart API" {:author "Hubert Iwaniuk"} (:import (java.nio.charset Charset) (com.ning.http.client.multipart ByteArrayPart FilePart StringPart))) (defn create-string-part "Create string multipart part" [{:keys [name value mime-type charset]}] (let [mime-type (or mime-type "text/plain")] (if charset (StringPart. name value mime-type (Charset/forName charset)) (StringPart. name value mime-type)))) (defn create-file-part "Create file multipart part" [{:keys [name file mime-type charset]}] (FilePart. name file mime-type (Charset/forName charset))) (defn create-bytearray-part "Create byte array multipart part" [{:keys [name file-name data mime-type charset]}] (ByteArrayPart. name data mime-type (Charset/forName charset) file-name)) (defn create-part "Create multipart part according to spec" [{type :type :as opts}] (case type :string (create-string-part opts) :file (create-file-part opts) :bytearray (create-bytearray-part opts)))
67893
;;; Copyright 2012 <NAME> ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (ns http.async.client.part "Asynchronous HTTP Client - Clojure - Multipart API" {:author "<NAME>"} (:import (java.nio.charset Charset) (com.ning.http.client.multipart ByteArrayPart FilePart StringPart))) (defn create-string-part "Create string multipart part" [{:keys [name value mime-type charset]}] (let [mime-type (or mime-type "text/plain")] (if charset (StringPart. name value mime-type (Charset/forName charset)) (StringPart. name value mime-type)))) (defn create-file-part "Create file multipart part" [{:keys [name file mime-type charset]}] (FilePart. name file mime-type (Charset/forName charset))) (defn create-bytearray-part "Create byte array multipart part" [{:keys [name file-name data mime-type charset]}] (ByteArrayPart. name data mime-type (Charset/forName charset) file-name)) (defn create-part "Create multipart part according to spec" [{type :type :as opts}] (case type :string (create-string-part opts) :file (create-file-part opts) :bytearray (create-bytearray-part opts)))
true
;;; Copyright 2012 PI:NAME:<NAME>END_PI ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (ns http.async.client.part "Asynchronous HTTP Client - Clojure - Multipart API" {:author "PI:NAME:<NAME>END_PI"} (:import (java.nio.charset Charset) (com.ning.http.client.multipart ByteArrayPart FilePart StringPart))) (defn create-string-part "Create string multipart part" [{:keys [name value mime-type charset]}] (let [mime-type (or mime-type "text/plain")] (if charset (StringPart. name value mime-type (Charset/forName charset)) (StringPart. name value mime-type)))) (defn create-file-part "Create file multipart part" [{:keys [name file mime-type charset]}] (FilePart. name file mime-type (Charset/forName charset))) (defn create-bytearray-part "Create byte array multipart part" [{:keys [name file-name data mime-type charset]}] (ByteArrayPart. name data mime-type (Charset/forName charset) file-name)) (defn create-part "Create multipart part according to spec" [{type :type :as opts}] (case type :string (create-string-part opts) :file (create-file-part opts) :bytearray (create-bytearray-part opts)))
[ { "context": ";; halfstep.clj\n;; (c) 2017 by Milan Gruner\n;; Half-step dubstep rhythm\n;; Original idea by D", "end": 43, "score": 0.9998540878295898, "start": 31, "tag": "NAME", "value": "Milan Gruner" }, { "context": "er\n;; Half-step dubstep rhythm\n;; Original idea by Darkraqqen\n\n(ns algorithmuss.halfstep\n (:require\n [overt", "end": 102, "score": 0.7746478319168091, "start": 92, "tag": "USERNAME", "value": "Darkraqqen" } ]
overtone/src/algorithmuss/halfstep.clj
lemilonkh/algorithmuss
13
;; halfstep.clj ;; (c) 2017 by Milan Gruner ;; Half-step dubstep rhythm ;; Original idea by Darkraqqen (ns algorithmuss.halfstep (:require [overtone.live :refer :all] [leipzig.live :as live] [leipzig.melody :refer :all] [overtone.inst.drum :as drums])) ; Load drum kit (def kit { :kick drums/kick2 :snare drums/snare :closed-hat drums/closed-hat :open-hat drums/open-hat }) ; Drum kit player (defmethod live/play-note :beat [note] (when-let [fn (-> (get kit (:drum note)) :sound)] (fn :amp (:amp note)))) ; Helper for programming drum sequences (defn drum [drum times length & {:keys [amp] :or {amp 1}}] (map #(zipmap [:time :duration :drum :amp] [%1 (- length %1) drum amp]) times)) ; Half step beat (def halfstep (->> (reduce with [ (drum :kick [0/8 3/8 8/8] 2) (drum :snare [4/8 12/8] 2)]) ;(drum :closed-hat (sort (concat [3.75 7.75] (range 1/2 8 1))) 8) (all :part :beat))) ; Play it! (->> halfstep (tempo (bpm 110)) live/play) ;(live/jam (var halfstep))
62171
;; halfstep.clj ;; (c) 2017 by <NAME> ;; Half-step dubstep rhythm ;; Original idea by Darkraqqen (ns algorithmuss.halfstep (:require [overtone.live :refer :all] [leipzig.live :as live] [leipzig.melody :refer :all] [overtone.inst.drum :as drums])) ; Load drum kit (def kit { :kick drums/kick2 :snare drums/snare :closed-hat drums/closed-hat :open-hat drums/open-hat }) ; Drum kit player (defmethod live/play-note :beat [note] (when-let [fn (-> (get kit (:drum note)) :sound)] (fn :amp (:amp note)))) ; Helper for programming drum sequences (defn drum [drum times length & {:keys [amp] :or {amp 1}}] (map #(zipmap [:time :duration :drum :amp] [%1 (- length %1) drum amp]) times)) ; Half step beat (def halfstep (->> (reduce with [ (drum :kick [0/8 3/8 8/8] 2) (drum :snare [4/8 12/8] 2)]) ;(drum :closed-hat (sort (concat [3.75 7.75] (range 1/2 8 1))) 8) (all :part :beat))) ; Play it! (->> halfstep (tempo (bpm 110)) live/play) ;(live/jam (var halfstep))
true
;; halfstep.clj ;; (c) 2017 by PI:NAME:<NAME>END_PI ;; Half-step dubstep rhythm ;; Original idea by Darkraqqen (ns algorithmuss.halfstep (:require [overtone.live :refer :all] [leipzig.live :as live] [leipzig.melody :refer :all] [overtone.inst.drum :as drums])) ; Load drum kit (def kit { :kick drums/kick2 :snare drums/snare :closed-hat drums/closed-hat :open-hat drums/open-hat }) ; Drum kit player (defmethod live/play-note :beat [note] (when-let [fn (-> (get kit (:drum note)) :sound)] (fn :amp (:amp note)))) ; Helper for programming drum sequences (defn drum [drum times length & {:keys [amp] :or {amp 1}}] (map #(zipmap [:time :duration :drum :amp] [%1 (- length %1) drum amp]) times)) ; Half step beat (def halfstep (->> (reduce with [ (drum :kick [0/8 3/8 8/8] 2) (drum :snare [4/8 12/8] 2)]) ;(drum :closed-hat (sort (concat [3.75 7.75] (range 1/2 8 1))) 8) (all :part :beat))) ; Play it! (->> halfstep (tempo (bpm 110)) live/play) ;(live/jam (var halfstep))