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": "y-attribute-conditions\n (let [name-map { :name \"Humedai Motors\" }\n humedai1 (manufacturer/creat", "end": 3980, "score": 0.5226654410362244, "start": 3977, "tag": "NAME", "value": "ume" }, { "context": "dai :id)]\n (manufacturer/update {:id id :name \"Schmoomdai Motors\" :founded \"2008\"})\n (is (= \n {:name \"Schm", "end": 4526, "score": 0.8536779284477234, "start": 4509, "tag": "NAME", "value": "Schmoomdai Motors" }, { "context": "tors\" :founded \"2008\"})\n (is (= \n {:name \"Schmoomdai Motors\" :grade 90 :founded \"2008\"}\n (select-keys (m", "end": 4589, "score": 0.810531735420227, "start": 4572, "tag": "NAME", "value": "Schmoomdai Motors" } ]
test/clj_record/core_test.clj
duelinmarkers/clj-record
8
(ns clj-record.core-test (:require [clj-record.core :as core] [clj-record.query :as query] [clj-record.test-model.manufacturer :as manufacturer] [clj-record.test-model.product :as product]) (:use clojure.test clj-record.test-helper)) (deftest table-name-can-be-unconventional-with-table-name-option-to-init-model (is (= "productos" (core/table-name "product")))) (deftest table-name-is-available-on-each-model-namespace (is (= "manufacturers" (manufacturer/table-name))) (is (= "productos" (product/table-name)))) (defdbtest insert-returns-id-of-new-record (let [id (manufacturer/insert (valid-manufacturer-with {:name "ACME"})) acme (manufacturer/get-record id)] (is (= "ACME" (acme :name))))) (defdbtest get-record-does-a-lookup-by-id (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))] (is (= humedai (manufacturer/get-record (humedai :id)))))) (defdbtest get-record-throws-if-not-found (is (thrown? IllegalArgumentException (manufacturer/get-record -1)))) (defdbtest all-records-returns-all (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= #{humedai other-1} (apply hash-set (manufacturer/all-records)))))) (defdbtest find-records-can-do-lookup-by-attribute-equality-conditions (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= [humedai] (manufacturer/find-records {:name "Humedai Motors"}))))) (defdbtest find-records-can-do-lookup-by-a-vector-of-SQL-conditions-followed-by-values (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= [humedai] (manufacturer/find-records ["name = ?" "Humedai Motors"]))))) (defdbtest find-record-can-do-lookup-by-attribute-equality-conditions (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= humedai (manufacturer/find-record {:name "Humedai Motors"}))))) (defdbtest find-record-can-do-lookup-by-a-vector-of-SQL-conditions-followed-by-values (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= humedai (manufacturer/find-record ["name = ?" "Humedai Motors"]))))) (defdbtest find-record-returns-the-first-matching-record (let [humedai (manufacturer/create (valid-manufacturer-with {:grade 90})) other-1 (manufacturer/create (valid-manufacturer-with {:grade 90}))] (is (= humedai (manufacturer/find-record {:grade 90}))))) (defdbtest find-by-sql-uses-a-complete-query (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))] (is (= (manufacturer/find-records ["name = ?" "Humedai Motors"]) (manufacturer/find-by-sql ["SELECT * FROM manufacturers WHERE name = ?" "Humedai Motors"]))))) (defdbtest destroy-record-destroys-by-id-from-record (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))] (manufacturer/destroy-record {:id (humedai :id)}) (is (empty? (manufacturer/find-records {:id (humedai :id)}))))) (defdbtest destroy-records-deletes-by-attribute-conditions (let [name-map { :name "Humedai Motors" } humedai1 (manufacturer/create (valid-manufacturer-with name-map)) humedai2 (manufacturer/create (valid-manufacturer-with name-map))] (manufacturer/destroy-records name-map) (is (empty? (manufacturer/find-records name-map))))) (defdbtest delete-records-deletes-by-attribute-conditions (let [name-map { :name "Humedai Motors" } humedai1 (manufacturer/create (valid-manufacturer-with name-map)) humedai2 (manufacturer/create (valid-manufacturer-with name-map))] (manufacturer/delete-records name-map) (is (empty? (manufacturer/find-records name-map))))) (defdbtest update-uses-id-to-update-other-given-attributes-leaving-unspecified-attributes-untouched (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors" :grade 90})) id (humedai :id)] (manufacturer/update {:id id :name "Schmoomdai Motors" :founded "2008"}) (is (= {:name "Schmoomdai Motors" :grade 90 :founded "2008"} (select-keys (manufacturer/get-record id) [:name :grade :founded]))))) (defdbtest record-count-all (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 2 (manufacturer/record-count))))) (defdbtest record-count-with-match-using-map (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 1 (manufacturer/record-count {:name "Some Other"}))))) (defdbtest record-count-with-match-using-vector (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 1 (manufacturer/record-count ["name = ?", "Some Other"]))))) (defdbtest record-count-no-match (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 0 (manufacturer/record-count {:name "bogus"}))))) (deftest to-conditions (are [expected-sql-conditions conditions-map] (= expected-sql-conditions (core/to-conditions conditions-map)) ["a = ?" 1] {:a 1} ["a = ?" "one"] {:a "one"} ["a IS NULL"] {:a nil} ["a = ?" 2] {:a (query/equal 2)} ["a <> ?" "two"] {:a (query/not-equal "two")} ["a > ?" 3] {:a (query/greater-than 3)} ["a >= ?" 3] {:a (query/greater-than-or-equal 3)} ["a < ?" 3] {:a (query/less-than 3)} ["a <= ?" 3] {:a (query/less-than-or-equal 3)} ["a LIKE ?" "a%"] {:a (query/like "a%")} ["a NOT LIKE ?" "%s"] {:a (query/not-like "%s")} ["a BETWEEN ? AND ?" 1 5] {:a (query/between 1 5)} ["a NOT BETWEEN ? AND ?" 6 10] {:a (query/not-between 6 10)} ["a IN (?, ?, ?)" "foo" "bar" "baz"] {:a (query/in "foo" "bar" "baz")} ["a NOT IN (?, ?, ?)" 1 2 3] {:a (query/not-in 1 2 3)}) (let [r (core/to-conditions {:a 1 :b 2})] (is (or (= r ["a = ? AND b = ?" 1 2]) (= r ["b = ? AND a = ?" 2 1]))))) (deftest model-metadata-with-no-args (is (= (@clj-record.meta/all-models-metadata "manufacturer") (manufacturer/model-metadata))) (is (contains? @(manufacturer/model-metadata) :validations))) (deftest model-metadata-with-one-arg (is (map? (manufacturer/model-metadata :callbacks)))) (deftest transaction-and-defined-callback-test (is (manufacturer/first-record)))
121809
(ns clj-record.core-test (:require [clj-record.core :as core] [clj-record.query :as query] [clj-record.test-model.manufacturer :as manufacturer] [clj-record.test-model.product :as product]) (:use clojure.test clj-record.test-helper)) (deftest table-name-can-be-unconventional-with-table-name-option-to-init-model (is (= "productos" (core/table-name "product")))) (deftest table-name-is-available-on-each-model-namespace (is (= "manufacturers" (manufacturer/table-name))) (is (= "productos" (product/table-name)))) (defdbtest insert-returns-id-of-new-record (let [id (manufacturer/insert (valid-manufacturer-with {:name "ACME"})) acme (manufacturer/get-record id)] (is (= "ACME" (acme :name))))) (defdbtest get-record-does-a-lookup-by-id (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))] (is (= humedai (manufacturer/get-record (humedai :id)))))) (defdbtest get-record-throws-if-not-found (is (thrown? IllegalArgumentException (manufacturer/get-record -1)))) (defdbtest all-records-returns-all (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= #{humedai other-1} (apply hash-set (manufacturer/all-records)))))) (defdbtest find-records-can-do-lookup-by-attribute-equality-conditions (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= [humedai] (manufacturer/find-records {:name "Humedai Motors"}))))) (defdbtest find-records-can-do-lookup-by-a-vector-of-SQL-conditions-followed-by-values (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= [humedai] (manufacturer/find-records ["name = ?" "Humedai Motors"]))))) (defdbtest find-record-can-do-lookup-by-attribute-equality-conditions (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= humedai (manufacturer/find-record {:name "Humedai Motors"}))))) (defdbtest find-record-can-do-lookup-by-a-vector-of-SQL-conditions-followed-by-values (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= humedai (manufacturer/find-record ["name = ?" "Humedai Motors"]))))) (defdbtest find-record-returns-the-first-matching-record (let [humedai (manufacturer/create (valid-manufacturer-with {:grade 90})) other-1 (manufacturer/create (valid-manufacturer-with {:grade 90}))] (is (= humedai (manufacturer/find-record {:grade 90}))))) (defdbtest find-by-sql-uses-a-complete-query (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))] (is (= (manufacturer/find-records ["name = ?" "Humedai Motors"]) (manufacturer/find-by-sql ["SELECT * FROM manufacturers WHERE name = ?" "Humedai Motors"]))))) (defdbtest destroy-record-destroys-by-id-from-record (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))] (manufacturer/destroy-record {:id (humedai :id)}) (is (empty? (manufacturer/find-records {:id (humedai :id)}))))) (defdbtest destroy-records-deletes-by-attribute-conditions (let [name-map { :name "Humedai Motors" } humedai1 (manufacturer/create (valid-manufacturer-with name-map)) humedai2 (manufacturer/create (valid-manufacturer-with name-map))] (manufacturer/destroy-records name-map) (is (empty? (manufacturer/find-records name-map))))) (defdbtest delete-records-deletes-by-attribute-conditions (let [name-map { :name "H<NAME>dai Motors" } humedai1 (manufacturer/create (valid-manufacturer-with name-map)) humedai2 (manufacturer/create (valid-manufacturer-with name-map))] (manufacturer/delete-records name-map) (is (empty? (manufacturer/find-records name-map))))) (defdbtest update-uses-id-to-update-other-given-attributes-leaving-unspecified-attributes-untouched (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors" :grade 90})) id (humedai :id)] (manufacturer/update {:id id :name "<NAME>" :founded "2008"}) (is (= {:name "<NAME>" :grade 90 :founded "2008"} (select-keys (manufacturer/get-record id) [:name :grade :founded]))))) (defdbtest record-count-all (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 2 (manufacturer/record-count))))) (defdbtest record-count-with-match-using-map (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 1 (manufacturer/record-count {:name "Some Other"}))))) (defdbtest record-count-with-match-using-vector (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 1 (manufacturer/record-count ["name = ?", "Some Other"]))))) (defdbtest record-count-no-match (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 0 (manufacturer/record-count {:name "bogus"}))))) (deftest to-conditions (are [expected-sql-conditions conditions-map] (= expected-sql-conditions (core/to-conditions conditions-map)) ["a = ?" 1] {:a 1} ["a = ?" "one"] {:a "one"} ["a IS NULL"] {:a nil} ["a = ?" 2] {:a (query/equal 2)} ["a <> ?" "two"] {:a (query/not-equal "two")} ["a > ?" 3] {:a (query/greater-than 3)} ["a >= ?" 3] {:a (query/greater-than-or-equal 3)} ["a < ?" 3] {:a (query/less-than 3)} ["a <= ?" 3] {:a (query/less-than-or-equal 3)} ["a LIKE ?" "a%"] {:a (query/like "a%")} ["a NOT LIKE ?" "%s"] {:a (query/not-like "%s")} ["a BETWEEN ? AND ?" 1 5] {:a (query/between 1 5)} ["a NOT BETWEEN ? AND ?" 6 10] {:a (query/not-between 6 10)} ["a IN (?, ?, ?)" "foo" "bar" "baz"] {:a (query/in "foo" "bar" "baz")} ["a NOT IN (?, ?, ?)" 1 2 3] {:a (query/not-in 1 2 3)}) (let [r (core/to-conditions {:a 1 :b 2})] (is (or (= r ["a = ? AND b = ?" 1 2]) (= r ["b = ? AND a = ?" 2 1]))))) (deftest model-metadata-with-no-args (is (= (@clj-record.meta/all-models-metadata "manufacturer") (manufacturer/model-metadata))) (is (contains? @(manufacturer/model-metadata) :validations))) (deftest model-metadata-with-one-arg (is (map? (manufacturer/model-metadata :callbacks)))) (deftest transaction-and-defined-callback-test (is (manufacturer/first-record)))
true
(ns clj-record.core-test (:require [clj-record.core :as core] [clj-record.query :as query] [clj-record.test-model.manufacturer :as manufacturer] [clj-record.test-model.product :as product]) (:use clojure.test clj-record.test-helper)) (deftest table-name-can-be-unconventional-with-table-name-option-to-init-model (is (= "productos" (core/table-name "product")))) (deftest table-name-is-available-on-each-model-namespace (is (= "manufacturers" (manufacturer/table-name))) (is (= "productos" (product/table-name)))) (defdbtest insert-returns-id-of-new-record (let [id (manufacturer/insert (valid-manufacturer-with {:name "ACME"})) acme (manufacturer/get-record id)] (is (= "ACME" (acme :name))))) (defdbtest get-record-does-a-lookup-by-id (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))] (is (= humedai (manufacturer/get-record (humedai :id)))))) (defdbtest get-record-throws-if-not-found (is (thrown? IllegalArgumentException (manufacturer/get-record -1)))) (defdbtest all-records-returns-all (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= #{humedai other-1} (apply hash-set (manufacturer/all-records)))))) (defdbtest find-records-can-do-lookup-by-attribute-equality-conditions (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= [humedai] (manufacturer/find-records {:name "Humedai Motors"}))))) (defdbtest find-records-can-do-lookup-by-a-vector-of-SQL-conditions-followed-by-values (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= [humedai] (manufacturer/find-records ["name = ?" "Humedai Motors"]))))) (defdbtest find-record-can-do-lookup-by-attribute-equality-conditions (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= humedai (manufacturer/find-record {:name "Humedai Motors"}))))) (defdbtest find-record-can-do-lookup-by-a-vector-of-SQL-conditions-followed-by-values (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= humedai (manufacturer/find-record ["name = ?" "Humedai Motors"]))))) (defdbtest find-record-returns-the-first-matching-record (let [humedai (manufacturer/create (valid-manufacturer-with {:grade 90})) other-1 (manufacturer/create (valid-manufacturer-with {:grade 90}))] (is (= humedai (manufacturer/find-record {:grade 90}))))) (defdbtest find-by-sql-uses-a-complete-query (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))] (is (= (manufacturer/find-records ["name = ?" "Humedai Motors"]) (manufacturer/find-by-sql ["SELECT * FROM manufacturers WHERE name = ?" "Humedai Motors"]))))) (defdbtest destroy-record-destroys-by-id-from-record (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))] (manufacturer/destroy-record {:id (humedai :id)}) (is (empty? (manufacturer/find-records {:id (humedai :id)}))))) (defdbtest destroy-records-deletes-by-attribute-conditions (let [name-map { :name "Humedai Motors" } humedai1 (manufacturer/create (valid-manufacturer-with name-map)) humedai2 (manufacturer/create (valid-manufacturer-with name-map))] (manufacturer/destroy-records name-map) (is (empty? (manufacturer/find-records name-map))))) (defdbtest delete-records-deletes-by-attribute-conditions (let [name-map { :name "HPI:NAME:<NAME>END_PIdai Motors" } humedai1 (manufacturer/create (valid-manufacturer-with name-map)) humedai2 (manufacturer/create (valid-manufacturer-with name-map))] (manufacturer/delete-records name-map) (is (empty? (manufacturer/find-records name-map))))) (defdbtest update-uses-id-to-update-other-given-attributes-leaving-unspecified-attributes-untouched (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors" :grade 90})) id (humedai :id)] (manufacturer/update {:id id :name "PI:NAME:<NAME>END_PI" :founded "2008"}) (is (= {:name "PI:NAME:<NAME>END_PI" :grade 90 :founded "2008"} (select-keys (manufacturer/get-record id) [:name :grade :founded]))))) (defdbtest record-count-all (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 2 (manufacturer/record-count))))) (defdbtest record-count-with-match-using-map (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 1 (manufacturer/record-count {:name "Some Other"}))))) (defdbtest record-count-with-match-using-vector (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 1 (manufacturer/record-count ["name = ?", "Some Other"]))))) (defdbtest record-count-no-match (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"})) other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))] (is (= 0 (manufacturer/record-count {:name "bogus"}))))) (deftest to-conditions (are [expected-sql-conditions conditions-map] (= expected-sql-conditions (core/to-conditions conditions-map)) ["a = ?" 1] {:a 1} ["a = ?" "one"] {:a "one"} ["a IS NULL"] {:a nil} ["a = ?" 2] {:a (query/equal 2)} ["a <> ?" "two"] {:a (query/not-equal "two")} ["a > ?" 3] {:a (query/greater-than 3)} ["a >= ?" 3] {:a (query/greater-than-or-equal 3)} ["a < ?" 3] {:a (query/less-than 3)} ["a <= ?" 3] {:a (query/less-than-or-equal 3)} ["a LIKE ?" "a%"] {:a (query/like "a%")} ["a NOT LIKE ?" "%s"] {:a (query/not-like "%s")} ["a BETWEEN ? AND ?" 1 5] {:a (query/between 1 5)} ["a NOT BETWEEN ? AND ?" 6 10] {:a (query/not-between 6 10)} ["a IN (?, ?, ?)" "foo" "bar" "baz"] {:a (query/in "foo" "bar" "baz")} ["a NOT IN (?, ?, ?)" 1 2 3] {:a (query/not-in 1 2 3)}) (let [r (core/to-conditions {:a 1 :b 2})] (is (or (= r ["a = ? AND b = ?" 1 2]) (= r ["b = ? AND a = ?" 2 1]))))) (deftest model-metadata-with-no-args (is (= (@clj-record.meta/all-models-metadata "manufacturer") (manufacturer/model-metadata))) (is (contains? @(manufacturer/model-metadata) :validations))) (deftest model-metadata-with-one-arg (is (map? (manufacturer/model-metadata :callbacks)))) (deftest transaction-and-defined-callback-test (is (manufacturer/first-record)))
[ { "context": ";; Copyright 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2017 Denis Shilov", "end": 36, "score": 0.9998793601989746, "start": 23, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2017 Denis Shilov <sxp@bk.ru>\n;", "end": 50, "score": 0.9999322891235352, "start": 38, "tag": "EMAIL", "value": "niwi@niwi.nz" }, { "context": "Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2017 Denis Shilov <sxp@bk.ru>\n;;\n;; Licensed under the Apache Licen", "end": 86, "score": 0.9998769760131836, "start": 74, "tag": "NAME", "value": "Denis Shilov" }, { "context": "niwi@niwi.nz>\n;; Copyright (c) 2017 Denis Shilov <sxp@bk.ru>\n;;\n;; Licensed under the Apache License, Version", "end": 97, "score": 0.9999309182167053, "start": 88, "tag": "EMAIL", "value": "sxp@bk.ru" }, { "context": "19-jwk-key\n {:kty \"OKP\"\n :crv \"Ed25519\"\n :d \"nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\",\n :x \"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcH", "end": 1080, "score": 0.9996739029884338, "start": 1037, "tag": "KEY", "value": "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A" }, { "context": "xne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A\",\n :x \"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\"})\n\n(deftest ed25519-jws-sign-unsign\n (let [[pub", "end": 1133, "score": 0.999708354473114, "start": 1090, "tag": "KEY", "value": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo" }, { "context": "private {:alg :eddsa :key private})]\n\n (is (= \"eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg\"\n token))\n (is (= \"Example of Ed2551", "end": 1522, "score": 0.9995782971382141, "start": 1379, "tag": "KEY", "value": "eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg" }, { "context": ")))))\n\n(def rsa2048-jwk-key\n {:kty \"RSA\",\n :n \"ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ\"\n :e \"AQAB\"\n :d \"Eq5xpGnNCivDflJsRQBXHx1hdR1k", "end": 2044, "score": 0.9997608065605164, "start": 1702, "tag": "KEY", "value": "ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ" }, { "context": "91kzk2PAcDTW9gb54h4FRWyuXpoQ\"\n :e \"AQAB\"\n :d \"Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97IjlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYTCBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLhBOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ\"})\n\n\n(deftest rsa-jws-sign-unsign\n (let [[public", "end": 2408, "score": 0.9987615346908569, "start": 2066, "tag": "KEY", "value": "Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97IjlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYTCBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLhBOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ" }, { "context": " :key private})]\n\n (is (= \"eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw\"\n ", "end": 3160, "score": 0.9993791580200195, "start": 2748, "tag": "KEY", "value": "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs" }, { "context": "PqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw\"\n ", "end": 3169, "score": 0.5068610310554504, "start": 3167, "tag": "KEY", "value": "AX" }, { "context": "J1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw\"\n tok", "end": 3172, "score": 0.5070512890815735, "start": 3171, "tag": "KEY", "value": "h" }, { "context": "YI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw\"\n token))\n (is (", "end": 3186, "score": 0.5186057090759277, "start": 3183, "tag": "KEY", "value": "Bp0" }, { "context": "QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw\"\n token))\n (is (= pay", "end": 3191, "score": 0.5107372999191284, "start": 3188, "tag": "KEY", "value": "cN_" }, { "context": "I8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw\"\n token))\n (is (= payload\n ", "end": 3206, "score": 0.6915366649627686, "start": 3197, "tag": "KEY", "value": "UPQGe77Rw" }, { "context": ")))))\n\n(def ec256-jwk-key\n {:kty \"EC\",\n :crv \"P-256\",\n :x \"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvR", "end": 3369, "score": 0.7798300981521606, "start": 3366, "tag": "KEY", "value": "256" }, { "context": "256-jwk-key\n {:kty \"EC\",\n :crv \"P-256\",\n :x \"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU\",\n :y \"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI", "end": 3422, "score": 0.9914150834083557, "start": 3379, "tag": "KEY", "value": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU" }, { "context": "OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU\",\n :y \"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0\",\n :d \"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E", "end": 3475, "score": 0.9536004662513733, "start": 3432, "tag": "KEY", "value": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0" }, { "context": "EzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0\",\n :d \"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI\"})\n\n(deftest ec256-jws-sign-unsign\n (let [[publi", "end": 3528, "score": 0.9584127068519592, "start": 3485, "tag": "KEY", "value": "jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI" }, { "context": " :key private})\n rfctoken \"eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q\"]\n\n ;; unsign using our token\n (is (= paylo", "end": 4045, "score": 0.9995964765548706, "start": 3843, "tag": "KEY", "value": "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q" }, { "context": "521-jwk-key\n {:kty \"EC\",\n :crv \"P-521\",\n :x \"AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_NjFZ", "end": 4378, "score": 0.9315516352653503, "start": 4368, "tag": "KEY", "value": "AekpBQ8ST8" }, { "context": " {:kty \"EC\",\n :crv \"P-521\",\n :x \"AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQG", "end": 4405, "score": 0.8836516737937927, "start": 4380, "tag": "KEY", "value": "VcfVOTNl353vSrDCLLJXmPk06" }, { "context": "21\",\n :x \"AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk\",\n :y \"ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg", "end": 4456, "score": 0.9580858945846558, "start": 4406, "tag": "KEY", "value": "TjxrrjcBpXp5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk" }, { "context": "p5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk\",\n :y \"ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2\",\n", "end": 4507, "score": 0.9182127118110657, "start": 4466, "tag": "KEY", "value": "ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_" }, { "context": "\n :y \"ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2\",\n :d \"AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw", "end": 4554, "score": 0.965608537197113, "start": 4508, "tag": "KEY", "value": "2Th-x3S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2" }, { "context": "S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2\",\n :d \"AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPAxerEzgdRhajnu0ferB0d53vM9mE15j2C\"})\n\n(deftest ec521-jws-sign-unsign\n (let [[publi", "end": 4652, "score": 0.9953373670578003, "start": 4564, "tag": "KEY", "value": "AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPAxerEzgdRhajnu0ferB0d53vM9mE15j2C" }, { "context": " :key private})\n rfctoken \"eyJhbGciOiJFUzUxMiJ9.UGF5bG9hZA.AdwMgeerwtHoh-l192l60hp9wAHZFVJbLfD_UxMi70cwnZOYaRI1bKPWROc-mZZqwqT2SI-KGDKB34XO0aw_7XdtAG8GaSwFKdCAPZgoXD2YBJZCPEX3xKpRwcdOO8KpEHwJjyqOgzDO7iKvU8vcnwNrmxYbSW9ERBXukOXolLzeO_Jn\"]\n\n ;; unsign using our token\n (is (= paylo", "end": 5100, "score": 0.9991072416305542, "start": 4892, "tag": "KEY", "value": "eyJhbGciOiJFUzUxMiJ9.UGF5bG9hZA.AdwMgeerwtHoh-l192l60hp9wAHZFVJbLfD_UxMi70cwnZOYaRI1bKPWROc-mZZqwqT2SI-KGDKB34XO0aw_7XdtAG8GaSwFKdCAPZgoXD2YBJZCPEX3xKpRwcdOO8KpEHwJjyqOgzDO7iKvU8vcnwNrmxYbSW9ERBXukOXolLzeO_Jn" } ]
test/buddy/sign/jwk_tests.clj
greut/buddy-sign
105
;; Copyright 2014-2016 Andrey Antukh <niwi@niwi.nz> ;; Copyright (c) 2017 Denis Shilov <sxp@bk.ru> ;; ;; 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.sign.jwk-tests (:require [clojure.test :refer :all] [buddy.core.codecs.base64 :as b64] [buddy.core.codecs :as codecs] [buddy.core.keys :as keys] [buddy.sign.jws :as jws])) (defn- load-pair [jwk] [(keys/jwk->public-key jwk) (keys/jwk->private-key jwk)]) (def ed25519-jwk-key {:kty "OKP" :crv "Ed25519" :d "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A", :x "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}) (deftest ed25519-jws-sign-unsign (let [[public private] (load-pair ed25519-jwk-key) ;; Example from RFC payload "Example of Ed25519 signing" token (jws/sign payload private {:alg :eddsa :key private})] (is (= "eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg" token)) (is (= "Example of Ed25519 signing" (codecs/bytes->str (jws/unsign token public {:alg :eddsa})))))) (def rsa2048-jwk-key {:kty "RSA", :n "ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ" :e "AQAB" :d "Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97IjlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYTCBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLhBOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ"}) (deftest rsa-jws-sign-unsign (let [[public private] (load-pair rsa2048-jwk-key) ;; Example from RFC payload "{\"iss\":\"joe\",\r\n \"exp\":1300819380,\r\n \"http://example.com/is_root\":true}" token (jws/sign payload private {:alg :rs256 :key private})] (is (= "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw" token)) (is (= payload (codecs/bytes->str (jws/unsign token public {:alg :rs256})))))) (def ec256-jwk-key {:kty "EC", :crv "P-256", :x "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", :y "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", :d "jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI"}) (deftest ec256-jws-sign-unsign (let [[public private] (load-pair ec256-jwk-key) payload "{\"iss\":\"joe\",\r\n \"exp\":1300819380,\r\n \"http://example.com/is_root\":true}" token (jws/sign payload private {:alg :es256 :key private}) rfctoken "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q"] ;; unsign using our token (is (= payload (codecs/bytes->str (jws/unsign token public {:alg :es256})))) ;; unsign using RFC reference token (is (= payload (codecs/bytes->str (jws/unsign rfctoken public {:alg :es256})))))) (def ec521-jwk-key {:kty "EC", :crv "P-521", :x "AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk", :y "ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2", :d "AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPAxerEzgdRhajnu0ferB0d53vM9mE15j2C"}) (deftest ec521-jws-sign-unsign (let [[public private] (load-pair ec521-jwk-key) payload "Payload" token (jws/sign payload private {:alg :es512 :key private}) rfctoken "eyJhbGciOiJFUzUxMiJ9.UGF5bG9hZA.AdwMgeerwtHoh-l192l60hp9wAHZFVJbLfD_UxMi70cwnZOYaRI1bKPWROc-mZZqwqT2SI-KGDKB34XO0aw_7XdtAG8GaSwFKdCAPZgoXD2YBJZCPEX3xKpRwcdOO8KpEHwJjyqOgzDO7iKvU8vcnwNrmxYbSW9ERBXukOXolLzeO_Jn"] ;; unsign using our token (is (= payload (codecs/bytes->str (jws/unsign token public {:alg :es512})))) ;; unsign using RFC reference token (is (= payload (codecs/bytes->str (jws/unsign rfctoken public {:alg :es512}))))))
48549
;; Copyright 2014-2016 <NAME> <<EMAIL>> ;; Copyright (c) 2017 <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.sign.jwk-tests (:require [clojure.test :refer :all] [buddy.core.codecs.base64 :as b64] [buddy.core.codecs :as codecs] [buddy.core.keys :as keys] [buddy.sign.jws :as jws])) (defn- load-pair [jwk] [(keys/jwk->public-key jwk) (keys/jwk->private-key jwk)]) (def ed25519-jwk-key {:kty "OKP" :crv "Ed25519" :d "<KEY>", :x "<KEY>"}) (deftest ed25519-jws-sign-unsign (let [[public private] (load-pair ed25519-jwk-key) ;; Example from RFC payload "Example of Ed25519 signing" token (jws/sign payload private {:alg :eddsa :key private})] (is (= "<KEY>" token)) (is (= "Example of Ed25519 signing" (codecs/bytes->str (jws/unsign token public {:alg :eddsa})))))) (def rsa2048-jwk-key {:kty "RSA", :n "<KEY>" :e "AQAB" :d "<KEY>"}) (deftest rsa-jws-sign-unsign (let [[public private] (load-pair rsa2048-jwk-key) ;; Example from RFC payload "{\"iss\":\"joe\",\r\n \"exp\":1300819380,\r\n \"http://example.com/is_root\":true}" token (jws/sign payload private {:alg :rs256 :key private})] (is (= "<KEY>98rqVt5<KEY>LI<KEY>WkWywlVmtVr<KEY>ig<KEY>IoypGl<KEY>" token)) (is (= payload (codecs/bytes->str (jws/unsign token public {:alg :rs256})))))) (def ec256-jwk-key {:kty "EC", :crv "P-<KEY>", :x "<KEY>", :y "<KEY>", :d "<KEY>"}) (deftest ec256-jws-sign-unsign (let [[public private] (load-pair ec256-jwk-key) payload "{\"iss\":\"joe\",\r\n \"exp\":1300819380,\r\n \"http://example.com/is_root\":true}" token (jws/sign payload private {:alg :es256 :key private}) rfctoken "<KEY>"] ;; unsign using our token (is (= payload (codecs/bytes->str (jws/unsign token public {:alg :es256})))) ;; unsign using RFC reference token (is (= payload (codecs/bytes->str (jws/unsign rfctoken public {:alg :es256})))))) (def ec521-jwk-key {:kty "EC", :crv "P-521", :x "<KEY>a8<KEY>w<KEY>", :y "<KEY>l<KEY>", :d "<KEY>"}) (deftest ec521-jws-sign-unsign (let [[public private] (load-pair ec521-jwk-key) payload "Payload" token (jws/sign payload private {:alg :es512 :key private}) rfctoken "<KEY>"] ;; unsign using our token (is (= payload (codecs/bytes->str (jws/unsign token public {:alg :es512})))) ;; unsign using RFC reference token (is (= payload (codecs/bytes->str (jws/unsign rfctoken public {:alg :es512}))))))
true
;; Copyright 2014-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; Copyright (c) 2017 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.sign.jwk-tests (:require [clojure.test :refer :all] [buddy.core.codecs.base64 :as b64] [buddy.core.codecs :as codecs] [buddy.core.keys :as keys] [buddy.sign.jws :as jws])) (defn- load-pair [jwk] [(keys/jwk->public-key jwk) (keys/jwk->private-key jwk)]) (def ed25519-jwk-key {:kty "OKP" :crv "Ed25519" :d "PI:KEY:<KEY>END_PI", :x "PI:KEY:<KEY>END_PI"}) (deftest ed25519-jws-sign-unsign (let [[public private] (load-pair ed25519-jwk-key) ;; Example from RFC payload "Example of Ed25519 signing" token (jws/sign payload private {:alg :eddsa :key private})] (is (= "PI:KEY:<KEY>END_PI" token)) (is (= "Example of Ed25519 signing" (codecs/bytes->str (jws/unsign token public {:alg :eddsa})))))) (def rsa2048-jwk-key {:kty "RSA", :n "PI:KEY:<KEY>END_PI" :e "AQAB" :d "PI:KEY:<KEY>END_PI"}) (deftest rsa-jws-sign-unsign (let [[public private] (load-pair rsa2048-jwk-key) ;; Example from RFC payload "{\"iss\":\"joe\",\r\n \"exp\":1300819380,\r\n \"http://example.com/is_root\":true}" token (jws/sign payload private {:alg :rs256 :key private})] (is (= "PI:KEY:<KEY>END_PI98rqVt5PI:KEY:<KEY>END_PILIPI:KEY:<KEY>END_PIWkWywlVmtVrPI:KEY:<KEY>END_PIigPI:KEY:<KEY>END_PIIoypGlPI:KEY:<KEY>END_PI" token)) (is (= payload (codecs/bytes->str (jws/unsign token public {:alg :rs256})))))) (def ec256-jwk-key {:kty "EC", :crv "P-PI:KEY:<KEY>END_PI", :x "PI:KEY:<KEY>END_PI", :y "PI:KEY:<KEY>END_PI", :d "PI:KEY:<KEY>END_PI"}) (deftest ec256-jws-sign-unsign (let [[public private] (load-pair ec256-jwk-key) payload "{\"iss\":\"joe\",\r\n \"exp\":1300819380,\r\n \"http://example.com/is_root\":true}" token (jws/sign payload private {:alg :es256 :key private}) rfctoken "PI:KEY:<KEY>END_PI"] ;; unsign using our token (is (= payload (codecs/bytes->str (jws/unsign token public {:alg :es256})))) ;; unsign using RFC reference token (is (= payload (codecs/bytes->str (jws/unsign rfctoken public {:alg :es256})))))) (def ec521-jwk-key {:kty "EC", :crv "P-521", :x "PI:KEY:<KEY>END_PIa8PI:KEY:<KEY>END_PIwPI:KEY:<KEY>END_PI", :y "PI:KEY:<KEY>END_PIlPI:KEY:<KEY>END_PI", :d "PI:KEY:<KEY>END_PI"}) (deftest ec521-jws-sign-unsign (let [[public private] (load-pair ec521-jwk-key) payload "Payload" token (jws/sign payload private {:alg :es512 :key private}) rfctoken "PI:KEY:<KEY>END_PI"] ;; unsign using our token (is (= payload (codecs/bytes->str (jws/unsign token public {:alg :es512})))) ;; unsign using RFC reference token (is (= payload (codecs/bytes->str (jws/unsign rfctoken public {:alg :es512}))))))
[ { "context": " :subprotocol \"sqlite\"\n :subname \"/Users/mertnuhoglu/projects/study/clj/ex/book_practicalli_clojure_we", "end": 368, "score": 0.9919202923774719, "start": 357, "tag": "USERNAME", "value": "mertnuhoglu" }, { "context": "st_name, email, phone)\n values (103, 'ali', 'veli', 'ali2@x.com', '+90(555)2...');\n \"))\n\n (j/quer", "end": 971, "score": 0.8504785299301147, "start": 967, "tag": "NAME", "value": "veli" }, { "context": " email, phone)\n values (103, 'ali', 'veli', 'ali2@x.com', '+90(555)2...');\n \"))\n\n (j/query db\n (str ", "end": 985, "score": 0.9999116063117981, "start": 975, "tag": "EMAIL", "value": "ali2@x.com" } ]
clj/ex/book_practicalli_clojure_webapps/p01/src/practicalli/p10.clj
mertnuhoglu/study
1
(ns practicalli.p10 (:require [clojure.pprint :as p] [clojure.java.jdbc :as j] )) ; from: [Clojure and SQLite – Yet Another Blog in Statistical Computing](https://statcompute.wordpress.com/2018/03/12/clojure-and-sqlite/) (comment (def db {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname "/Users/mertnuhoglu/projects/study/clj/ex/book_practicalli_clojure_webapps/p01/db_p10.db"}) (p/print-table (j/query db (str "select tbl_name, type from sqlite_master where type = 'table' limit 3;"))) (j/db-do-commands db (str " CREATE TABLE contacts ( contact_id INTEGER PRIMARY KEY, first_name TEXT NOT NULL, last_name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, phone TEXT NOT NULL UNIQUE ); ")) (j/db-do-commands db (str " insert into contacts(contact_id, first_name, last_name, email, phone) values (103, 'ali', 'veli', 'ali2@x.com', '+90(555)2...'); ")) (j/query db (str "select * from contacts;")) ,)
64727
(ns practicalli.p10 (:require [clojure.pprint :as p] [clojure.java.jdbc :as j] )) ; from: [Clojure and SQLite – Yet Another Blog in Statistical Computing](https://statcompute.wordpress.com/2018/03/12/clojure-and-sqlite/) (comment (def db {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname "/Users/mertnuhoglu/projects/study/clj/ex/book_practicalli_clojure_webapps/p01/db_p10.db"}) (p/print-table (j/query db (str "select tbl_name, type from sqlite_master where type = 'table' limit 3;"))) (j/db-do-commands db (str " CREATE TABLE contacts ( contact_id INTEGER PRIMARY KEY, first_name TEXT NOT NULL, last_name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, phone TEXT NOT NULL UNIQUE ); ")) (j/db-do-commands db (str " insert into contacts(contact_id, first_name, last_name, email, phone) values (103, 'ali', '<NAME>', '<EMAIL>', '+90(555)2...'); ")) (j/query db (str "select * from contacts;")) ,)
true
(ns practicalli.p10 (:require [clojure.pprint :as p] [clojure.java.jdbc :as j] )) ; from: [Clojure and SQLite – Yet Another Blog in Statistical Computing](https://statcompute.wordpress.com/2018/03/12/clojure-and-sqlite/) (comment (def db {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname "/Users/mertnuhoglu/projects/study/clj/ex/book_practicalli_clojure_webapps/p01/db_p10.db"}) (p/print-table (j/query db (str "select tbl_name, type from sqlite_master where type = 'table' limit 3;"))) (j/db-do-commands db (str " CREATE TABLE contacts ( contact_id INTEGER PRIMARY KEY, first_name TEXT NOT NULL, last_name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, phone TEXT NOT NULL UNIQUE ); ")) (j/db-do-commands db (str " insert into contacts(contact_id, first_name, last_name, email, phone) values (103, 'ali', 'PI:NAME:<NAME>END_PI', 'PI:EMAIL:<EMAIL>END_PI', '+90(555)2...'); ")) (j/query db (str "select * from contacts;")) ,)
[ { "context": "e\" \"1.6\" \"-Xlint:-options\"]\n :signing {:gpg-key \"7A9D8E91\"}\n :deploy-repositories [[\"releases\" :clojars]\n", "end": 560, "score": 0.9951555132865906, "start": 552, "tag": "KEY", "value": "7A9D8E91" }, { "context": ":developer\n [:name \"Nathan Rajlich\"]\n [:url \"https://g", "end": 752, "score": 0.9998989105224609, "start": 738, "tag": "NAME", "value": "Nathan Rajlich" }, { "context": "allNate\"]\n [:email \"nathan@tootallnate.net\"]]\n [:developer\n ", "end": 888, "score": 0.9999347925186157, "start": 866, "tag": "EMAIL", "value": "nathan@tootallnate.net" }, { "context": ":developer\n [:name \"David Rohmer\"]\n [:url \"https://g", "end": 984, "score": 0.9998977780342102, "start": 972, "tag": "NAME", "value": "David Rohmer" }, { "context": " [:url \"https://github.com/Davidiusdadi\"]\n [:email \"rohmer.", "end": 1056, "score": 0.9996200203895569, "start": 1044, "tag": "USERNAME", "value": "Davidiusdadi" }, { "context": "iusdadi\"]\n [:email \"rohmer.david@gmail.com\"]]\n [:developer\n ", "end": 1121, "score": 0.9999309182167053, "start": 1099, "tag": "EMAIL", "value": "rohmer.david@gmail.com" }, { "context": ":developer\n [:name \"Marcel Prestel\"]\n [:url \"https://g", "end": 1219, "score": 0.9998967051506042, "start": 1205, "tag": "NAME", "value": "Marcel Prestel" }, { "context": " [:url \"https://github.com/marci4\"]\n [:email \"admin@m", "end": 1285, "score": 0.9993602633476257, "start": 1279, "tag": "USERNAME", "value": "marci4" }, { "context": "/marci4\"]\n [:email \"admin@marci4.de\"]]])\n\n\n", "end": 1343, "score": 0.99993497133255, "start": 1328, "tag": "EMAIL", "value": "admin@marci4.de" } ]
project.clj
ammanchipavan/Java-web-socket
0
(defproject org.java-websocket/java-websocket "1.3.2" :description "A barebones WebSocket client and server implementation written 100% in Java" :url "http://java-websocket.org/" :scm {:name "git" :url "https://github.com/TooTallNate/Java-WebSocket"} :license {:name "MIT License" :url "https://github.com/TooTallNate/Java-WebSocket/blob/master/LICENSE"} :source-paths [] :omit-source true :java-source-paths ["src/main/java"] :javac-options ["-target" "1.6" "-source" "1.6" "-Xlint:-options"] :signing {:gpg-key "7A9D8E91"} :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]] :pom-addition [:developers [:developer [:name "Nathan Rajlich"] [:url "https://github.com/TooTallNate"] [:email "nathan@tootallnate.net"]] [:developer [:name "David Rohmer"] [:url "https://github.com/Davidiusdadi"] [:email "rohmer.david@gmail.com"]] [:developer [:name "Marcel Prestel"] [:url "https://github.com/marci4"] [:email "admin@marci4.de"]]])
93169
(defproject org.java-websocket/java-websocket "1.3.2" :description "A barebones WebSocket client and server implementation written 100% in Java" :url "http://java-websocket.org/" :scm {:name "git" :url "https://github.com/TooTallNate/Java-WebSocket"} :license {:name "MIT License" :url "https://github.com/TooTallNate/Java-WebSocket/blob/master/LICENSE"} :source-paths [] :omit-source true :java-source-paths ["src/main/java"] :javac-options ["-target" "1.6" "-source" "1.6" "-Xlint:-options"] :signing {:gpg-key "<KEY>"} :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]] :pom-addition [:developers [:developer [:name "<NAME>"] [:url "https://github.com/TooTallNate"] [:email "<EMAIL>"]] [:developer [:name "<NAME>"] [:url "https://github.com/Davidiusdadi"] [:email "<EMAIL>"]] [:developer [:name "<NAME>"] [:url "https://github.com/marci4"] [:email "<EMAIL>"]]])
true
(defproject org.java-websocket/java-websocket "1.3.2" :description "A barebones WebSocket client and server implementation written 100% in Java" :url "http://java-websocket.org/" :scm {:name "git" :url "https://github.com/TooTallNate/Java-WebSocket"} :license {:name "MIT License" :url "https://github.com/TooTallNate/Java-WebSocket/blob/master/LICENSE"} :source-paths [] :omit-source true :java-source-paths ["src/main/java"] :javac-options ["-target" "1.6" "-source" "1.6" "-Xlint:-options"] :signing {:gpg-key "PI:KEY:<KEY>END_PI"} :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]] :pom-addition [:developers [:developer [:name "PI:NAME:<NAME>END_PI"] [:url "https://github.com/TooTallNate"] [:email "PI:EMAIL:<EMAIL>END_PI"]] [:developer [:name "PI:NAME:<NAME>END_PI"] [:url "https://github.com/Davidiusdadi"] [:email "PI:EMAIL:<EMAIL>END_PI"]] [:developer [:name "PI:NAME:<NAME>END_PI"] [:url "https://github.com/marci4"] [:email "PI:EMAIL:<EMAIL>END_PI"]]])
[ { "context": " (is (set/subset? #{[\"/scripts/actors.script\" [\"\\\"Will Smith\\\"\"]]\n [\"/scripts/apples", "end": 8123, "score": 0.999763548374176, "start": 8113, "tag": "NAME", "value": "Will Smith" }, { "context": " [\"/scripts/apples.script\" [\"\\\"Granny Smith\\\"\"]]}\n (set (perform-sear", "end": 8198, "score": 0.9997012615203857, "start": 8186, "tag": "NAME", "value": "Granny Smith" } ]
editor/test/editor/defold_project_search_test.clj
madwareru/defold
0
;; Copyright 2020 The Defold Foundation ;; 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.defold-project-search-test (:require [clojure.set :as set] [clojure.string :as string] [clojure.test :refer :all] [dynamo.graph :as g] [editor.defold-project-search :as project-search] [editor.resource :as resource] [integration.test-util :as test-util] [support.test-support :refer [with-clean-system]] [util.thread-util :as thread-util]) (:import [java.util.concurrent LinkedBlockingQueue])) (def ^:const search-project-path "test/resources/search_project") (def ^:const timeout-ms 15000) (defn- make-consumer [report-error!] (atom {:consumed [] :future nil :report-error! report-error!})) (defn- consumer-start! [consumer-atom results-fn!] (swap! consumer-atom (fn [consumer] (when (:future consumer) (future-cancel (:future consumer))) (-> consumer (assoc :consumed []) (assoc :future (future (try (loop [last-response-time (System/nanoTime)] (thread-util/throw-if-interrupted!) (let [poll-time (System/nanoTime) ret (loop [[result & more] (results-fn!)] (if result (if (= ::project-search/done result) ::done (do (swap! consumer-atom update :consumed conj result) (recur more))) ::not-done))] (when (= ret ::not-done) (when (< (- poll-time last-response-time) (* 1000000 timeout-ms)) (Thread/sleep 10) (recur last-response-time))))) (catch InterruptedException _ nil) (catch Throwable error ((:report-error! consumer) error) nil))))))) consumer-atom) (defn- consumer-stop! [consumer-atom] (swap! consumer-atom (fn [consumer] (when (:future consumer) (future-cancel (:future consumer))) consumer)) nil) (defn- consumer-started? [consumer-atom] (-> consumer-atom deref :future some?)) (defn- consumer-finished? [consumer-atom] (if-let [pending-future (-> consumer-atom deref :future)] (and (future-done? pending-future) (not (future-cancelled? pending-future))) false)) (defn- consumer-stopped? [consumer-atom] (if-let [pending-future (-> consumer-atom deref :future)] (or (future-cancelled? pending-future) (future-done? pending-future)) true)) (defn- consumer-consumed [consumer-atom] (-> consumer-atom deref :consumed)) (defn- match->trimmed-text [{:keys [line] :as _match}] (string/trim line)) (defn- matched-text-by-proj-path [consumed] (mapv (fn [{:keys [resource matches]}] [(resource/proj-path resource) (mapv match->trimmed-text matches)]) consumed)) (defn- match-proj-paths [consumed] (into #{} (map (comp resource/proj-path :resource)) consumed)) (deftest mock-consumer-test (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) queue (LinkedBlockingQueue. 4) poll-fn #(.poll queue)] (is (false? (consumer-started? consumer))) (is (false? (consumer-finished? consumer))) (is (true? (consumer-stopped? consumer))) (consumer-start! consumer poll-fn) (is (true? (consumer-started? consumer))) (is (false? (consumer-finished? consumer))) (is (false? (consumer-stopped? consumer))) (future (.put queue ::project-search/done)) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (is (true? (consumer-started? consumer))) (is (true? (consumer-stopped? consumer))) (consumer-start! consumer poll-fn) (consumer-stop! consumer) (is (true? (consumer-started? consumer))) (is (false? (consumer-finished? consumer))) (is (true? (consumer-stopped? consumer))))) (deftest compile-find-in-files-regex-test (is (= "(?i)\\Qfoo\\E" (str (project-search/compile-find-in-files-regex "foo")))) (testing "* is handled correctly" (is (= "(?i)\\Qfoo\\E.*\\Qbar\\E" (str (project-search/compile-find-in-files-regex "foo*bar"))))) (testing "other wildcard chars are quoted" (is (= "(?i)\\Qfoo\\E.*\\Qbar[]().$^\\E" (str (project-search/compile-find-in-files-regex "foo*bar[]().$^"))))) (testing "case insensitive search strings" (let [pattern (project-search/compile-find-in-files-regex "fOoO")] (is (= "fooo" (re-matches pattern "fooo")))))) (deftest make-file-resource-save-data-future-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) save-data-future (project-search/make-file-resource-save-data-future report-error! project) search-paths (->> save-data-future deref (map :resource) (map resource/proj-path))] (is (= (set search-paths) (into #{} (comp (keep #(some-> (g/node-value % :save-data) :resource)) (remove resource/internal?) (keep resource/proj-path)) (g/node-value project :nodes)))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-results-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!) perform-search! (fn [term exts] (start-search! term exts true) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (-> consumer consumer-consumed matched-text-by-proj-path))] (is (= [] (perform-search! nil nil))) (is (= [] (perform-search! "" nil))) (is (= [] (perform-search! nil ""))) (is (set/subset? #{["/modules/colors.lua" ["-- Unless required by applicable law or agreed to in writing, software distributed" "red = {255, 0, 0},"]] ["/scripts/apples.script" ["\"Red Delicious\","]]} (set (perform-search! "red" nil)))) (is (set/subset? #{["/modules/colors.lua" ["red = {255, 0, 0}," "green = {0, 255, 0}," "blue = {0, 0, 255}"]]} (set (perform-search! "255" nil)))) (is (set/subset? #{["/scripts/actors.script" ["\"Will Smith\""]] ["/scripts/apples.script" ["\"Granny Smith\""]]} (set (perform-search! "smith" "script")))) (is (set/subset? #{["/modules/colors.lua" ["return {"]] ["/scripts/actors.script" ["return {"]] ["/scripts/apples.script" ["return {"]]} (set (perform-search! "return" "lua, script")))) (is (some #(.startsWith % "/builtins") (map first (perform-search! "return" "lua, script")))) (is (= [["/foo.bar" ["Buckle my shoe;"]]] (perform-search! "buckle" nil))) (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-abort-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!)] (start-search! "*" nil true) (is (true? (consumer-started? consumer))) (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-file-extensions-test ;; Regular project path (test-util/with-loaded-project (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!) search-string "peaNUTbutterjellytime" perform-search! (fn [term exts] (start-search! term exts true) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (-> consumer consumer-consumed matched-text-by-proj-path))] (are [expected-count exts] (= expected-count (count (perform-search! search-string exts))) 1 "g" 1 "go" 1 ".go" 1 "*.go" 2 "go,sCR" 2 nil 2 "" 0 "lua" 1 "lua,go" 1 " lua, go" 1 " lua, GO" 1 "script") (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-include-libraries-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!) perform-search! (fn [term exts include-libraries?] (start-search! term exts include-libraries?) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (-> consumer consumer-consumed match-proj-paths))] (is (= #{} (perform-search! "socket" "lua" false))) (is (= #{"/builtins/scripts/mobdebug.lua" "/builtins/scripts/socket.lua"} (perform-search! "socket" "lua" true))) (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!)))))))
2099
;; Copyright 2020 The Defold Foundation ;; 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.defold-project-search-test (:require [clojure.set :as set] [clojure.string :as string] [clojure.test :refer :all] [dynamo.graph :as g] [editor.defold-project-search :as project-search] [editor.resource :as resource] [integration.test-util :as test-util] [support.test-support :refer [with-clean-system]] [util.thread-util :as thread-util]) (:import [java.util.concurrent LinkedBlockingQueue])) (def ^:const search-project-path "test/resources/search_project") (def ^:const timeout-ms 15000) (defn- make-consumer [report-error!] (atom {:consumed [] :future nil :report-error! report-error!})) (defn- consumer-start! [consumer-atom results-fn!] (swap! consumer-atom (fn [consumer] (when (:future consumer) (future-cancel (:future consumer))) (-> consumer (assoc :consumed []) (assoc :future (future (try (loop [last-response-time (System/nanoTime)] (thread-util/throw-if-interrupted!) (let [poll-time (System/nanoTime) ret (loop [[result & more] (results-fn!)] (if result (if (= ::project-search/done result) ::done (do (swap! consumer-atom update :consumed conj result) (recur more))) ::not-done))] (when (= ret ::not-done) (when (< (- poll-time last-response-time) (* 1000000 timeout-ms)) (Thread/sleep 10) (recur last-response-time))))) (catch InterruptedException _ nil) (catch Throwable error ((:report-error! consumer) error) nil))))))) consumer-atom) (defn- consumer-stop! [consumer-atom] (swap! consumer-atom (fn [consumer] (when (:future consumer) (future-cancel (:future consumer))) consumer)) nil) (defn- consumer-started? [consumer-atom] (-> consumer-atom deref :future some?)) (defn- consumer-finished? [consumer-atom] (if-let [pending-future (-> consumer-atom deref :future)] (and (future-done? pending-future) (not (future-cancelled? pending-future))) false)) (defn- consumer-stopped? [consumer-atom] (if-let [pending-future (-> consumer-atom deref :future)] (or (future-cancelled? pending-future) (future-done? pending-future)) true)) (defn- consumer-consumed [consumer-atom] (-> consumer-atom deref :consumed)) (defn- match->trimmed-text [{:keys [line] :as _match}] (string/trim line)) (defn- matched-text-by-proj-path [consumed] (mapv (fn [{:keys [resource matches]}] [(resource/proj-path resource) (mapv match->trimmed-text matches)]) consumed)) (defn- match-proj-paths [consumed] (into #{} (map (comp resource/proj-path :resource)) consumed)) (deftest mock-consumer-test (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) queue (LinkedBlockingQueue. 4) poll-fn #(.poll queue)] (is (false? (consumer-started? consumer))) (is (false? (consumer-finished? consumer))) (is (true? (consumer-stopped? consumer))) (consumer-start! consumer poll-fn) (is (true? (consumer-started? consumer))) (is (false? (consumer-finished? consumer))) (is (false? (consumer-stopped? consumer))) (future (.put queue ::project-search/done)) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (is (true? (consumer-started? consumer))) (is (true? (consumer-stopped? consumer))) (consumer-start! consumer poll-fn) (consumer-stop! consumer) (is (true? (consumer-started? consumer))) (is (false? (consumer-finished? consumer))) (is (true? (consumer-stopped? consumer))))) (deftest compile-find-in-files-regex-test (is (= "(?i)\\Qfoo\\E" (str (project-search/compile-find-in-files-regex "foo")))) (testing "* is handled correctly" (is (= "(?i)\\Qfoo\\E.*\\Qbar\\E" (str (project-search/compile-find-in-files-regex "foo*bar"))))) (testing "other wildcard chars are quoted" (is (= "(?i)\\Qfoo\\E.*\\Qbar[]().$^\\E" (str (project-search/compile-find-in-files-regex "foo*bar[]().$^"))))) (testing "case insensitive search strings" (let [pattern (project-search/compile-find-in-files-regex "fOoO")] (is (= "fooo" (re-matches pattern "fooo")))))) (deftest make-file-resource-save-data-future-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) save-data-future (project-search/make-file-resource-save-data-future report-error! project) search-paths (->> save-data-future deref (map :resource) (map resource/proj-path))] (is (= (set search-paths) (into #{} (comp (keep #(some-> (g/node-value % :save-data) :resource)) (remove resource/internal?) (keep resource/proj-path)) (g/node-value project :nodes)))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-results-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!) perform-search! (fn [term exts] (start-search! term exts true) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (-> consumer consumer-consumed matched-text-by-proj-path))] (is (= [] (perform-search! nil nil))) (is (= [] (perform-search! "" nil))) (is (= [] (perform-search! nil ""))) (is (set/subset? #{["/modules/colors.lua" ["-- Unless required by applicable law or agreed to in writing, software distributed" "red = {255, 0, 0},"]] ["/scripts/apples.script" ["\"Red Delicious\","]]} (set (perform-search! "red" nil)))) (is (set/subset? #{["/modules/colors.lua" ["red = {255, 0, 0}," "green = {0, 255, 0}," "blue = {0, 0, 255}"]]} (set (perform-search! "255" nil)))) (is (set/subset? #{["/scripts/actors.script" ["\"<NAME>\""]] ["/scripts/apples.script" ["\"<NAME>\""]]} (set (perform-search! "smith" "script")))) (is (set/subset? #{["/modules/colors.lua" ["return {"]] ["/scripts/actors.script" ["return {"]] ["/scripts/apples.script" ["return {"]]} (set (perform-search! "return" "lua, script")))) (is (some #(.startsWith % "/builtins") (map first (perform-search! "return" "lua, script")))) (is (= [["/foo.bar" ["Buckle my shoe;"]]] (perform-search! "buckle" nil))) (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-abort-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!)] (start-search! "*" nil true) (is (true? (consumer-started? consumer))) (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-file-extensions-test ;; Regular project path (test-util/with-loaded-project (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!) search-string "peaNUTbutterjellytime" perform-search! (fn [term exts] (start-search! term exts true) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (-> consumer consumer-consumed matched-text-by-proj-path))] (are [expected-count exts] (= expected-count (count (perform-search! search-string exts))) 1 "g" 1 "go" 1 ".go" 1 "*.go" 2 "go,sCR" 2 nil 2 "" 0 "lua" 1 "lua,go" 1 " lua, go" 1 " lua, GO" 1 "script") (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-include-libraries-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!) perform-search! (fn [term exts include-libraries?] (start-search! term exts include-libraries?) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (-> consumer consumer-consumed match-proj-paths))] (is (= #{} (perform-search! "socket" "lua" false))) (is (= #{"/builtins/scripts/mobdebug.lua" "/builtins/scripts/socket.lua"} (perform-search! "socket" "lua" true))) (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!)))))))
true
;; Copyright 2020 The Defold Foundation ;; 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.defold-project-search-test (:require [clojure.set :as set] [clojure.string :as string] [clojure.test :refer :all] [dynamo.graph :as g] [editor.defold-project-search :as project-search] [editor.resource :as resource] [integration.test-util :as test-util] [support.test-support :refer [with-clean-system]] [util.thread-util :as thread-util]) (:import [java.util.concurrent LinkedBlockingQueue])) (def ^:const search-project-path "test/resources/search_project") (def ^:const timeout-ms 15000) (defn- make-consumer [report-error!] (atom {:consumed [] :future nil :report-error! report-error!})) (defn- consumer-start! [consumer-atom results-fn!] (swap! consumer-atom (fn [consumer] (when (:future consumer) (future-cancel (:future consumer))) (-> consumer (assoc :consumed []) (assoc :future (future (try (loop [last-response-time (System/nanoTime)] (thread-util/throw-if-interrupted!) (let [poll-time (System/nanoTime) ret (loop [[result & more] (results-fn!)] (if result (if (= ::project-search/done result) ::done (do (swap! consumer-atom update :consumed conj result) (recur more))) ::not-done))] (when (= ret ::not-done) (when (< (- poll-time last-response-time) (* 1000000 timeout-ms)) (Thread/sleep 10) (recur last-response-time))))) (catch InterruptedException _ nil) (catch Throwable error ((:report-error! consumer) error) nil))))))) consumer-atom) (defn- consumer-stop! [consumer-atom] (swap! consumer-atom (fn [consumer] (when (:future consumer) (future-cancel (:future consumer))) consumer)) nil) (defn- consumer-started? [consumer-atom] (-> consumer-atom deref :future some?)) (defn- consumer-finished? [consumer-atom] (if-let [pending-future (-> consumer-atom deref :future)] (and (future-done? pending-future) (not (future-cancelled? pending-future))) false)) (defn- consumer-stopped? [consumer-atom] (if-let [pending-future (-> consumer-atom deref :future)] (or (future-cancelled? pending-future) (future-done? pending-future)) true)) (defn- consumer-consumed [consumer-atom] (-> consumer-atom deref :consumed)) (defn- match->trimmed-text [{:keys [line] :as _match}] (string/trim line)) (defn- matched-text-by-proj-path [consumed] (mapv (fn [{:keys [resource matches]}] [(resource/proj-path resource) (mapv match->trimmed-text matches)]) consumed)) (defn- match-proj-paths [consumed] (into #{} (map (comp resource/proj-path :resource)) consumed)) (deftest mock-consumer-test (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) queue (LinkedBlockingQueue. 4) poll-fn #(.poll queue)] (is (false? (consumer-started? consumer))) (is (false? (consumer-finished? consumer))) (is (true? (consumer-stopped? consumer))) (consumer-start! consumer poll-fn) (is (true? (consumer-started? consumer))) (is (false? (consumer-finished? consumer))) (is (false? (consumer-stopped? consumer))) (future (.put queue ::project-search/done)) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (is (true? (consumer-started? consumer))) (is (true? (consumer-stopped? consumer))) (consumer-start! consumer poll-fn) (consumer-stop! consumer) (is (true? (consumer-started? consumer))) (is (false? (consumer-finished? consumer))) (is (true? (consumer-stopped? consumer))))) (deftest compile-find-in-files-regex-test (is (= "(?i)\\Qfoo\\E" (str (project-search/compile-find-in-files-regex "foo")))) (testing "* is handled correctly" (is (= "(?i)\\Qfoo\\E.*\\Qbar\\E" (str (project-search/compile-find-in-files-regex "foo*bar"))))) (testing "other wildcard chars are quoted" (is (= "(?i)\\Qfoo\\E.*\\Qbar[]().$^\\E" (str (project-search/compile-find-in-files-regex "foo*bar[]().$^"))))) (testing "case insensitive search strings" (let [pattern (project-search/compile-find-in-files-regex "fOoO")] (is (= "fooo" (re-matches pattern "fooo")))))) (deftest make-file-resource-save-data-future-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) save-data-future (project-search/make-file-resource-save-data-future report-error! project) search-paths (->> save-data-future deref (map :resource) (map resource/proj-path))] (is (= (set search-paths) (into #{} (comp (keep #(some-> (g/node-value % :save-data) :resource)) (remove resource/internal?) (keep resource/proj-path)) (g/node-value project :nodes)))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-results-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!) perform-search! (fn [term exts] (start-search! term exts true) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (-> consumer consumer-consumed matched-text-by-proj-path))] (is (= [] (perform-search! nil nil))) (is (= [] (perform-search! "" nil))) (is (= [] (perform-search! nil ""))) (is (set/subset? #{["/modules/colors.lua" ["-- Unless required by applicable law or agreed to in writing, software distributed" "red = {255, 0, 0},"]] ["/scripts/apples.script" ["\"Red Delicious\","]]} (set (perform-search! "red" nil)))) (is (set/subset? #{["/modules/colors.lua" ["red = {255, 0, 0}," "green = {0, 255, 0}," "blue = {0, 0, 255}"]]} (set (perform-search! "255" nil)))) (is (set/subset? #{["/scripts/actors.script" ["\"PI:NAME:<NAME>END_PI\""]] ["/scripts/apples.script" ["\"PI:NAME:<NAME>END_PI\""]]} (set (perform-search! "smith" "script")))) (is (set/subset? #{["/modules/colors.lua" ["return {"]] ["/scripts/actors.script" ["return {"]] ["/scripts/apples.script" ["return {"]]} (set (perform-search! "return" "lua, script")))) (is (some #(.startsWith % "/builtins") (map first (perform-search! "return" "lua, script")))) (is (= [["/foo.bar" ["Buckle my shoe;"]]] (perform-search! "buckle" nil))) (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-abort-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!)] (start-search! "*" nil true) (is (true? (consumer-started? consumer))) (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-file-extensions-test ;; Regular project path (test-util/with-loaded-project (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!) search-string "peaNUTbutterjellytime" perform-search! (fn [term exts] (start-search! term exts true) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (-> consumer consumer-consumed matched-text-by-proj-path))] (are [expected-count exts] (= expected-count (count (perform-search! search-string exts))) 1 "g" 1 "go" 1 ".go" 1 "*.go" 2 "go,sCR" 2 nil 2 "" 0 "lua" 1 "lua,go" 1 " lua, go" 1 " lua, GO" 1 "script") (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!))))))) (deftest file-searcher-include-libraries-test (test-util/with-loaded-project search-project-path (test-util/with-ui-run-later-rebound (let [report-error! (test-util/make-call-logger) consumer (make-consumer report-error!) start-consumer! (partial consumer-start! consumer) stop-consumer! consumer-stop! save-data-future (project-search/make-file-resource-save-data-future report-error! project) {:keys [start-search! abort-search!]} (project-search/make-file-searcher save-data-future start-consumer! stop-consumer! report-error!) perform-search! (fn [term exts include-libraries?] (start-search! term exts include-libraries?) (is (true? (test-util/block-until true? timeout-ms consumer-finished? consumer))) (-> consumer consumer-consumed match-proj-paths))] (is (= #{} (perform-search! "socket" "lua" false))) (is (= #{"/builtins/scripts/mobdebug.lua" "/builtins/scripts/socket.lua"} (perform-search! "socket" "lua" true))) (abort-search!) (is (true? (test-util/block-until true? timeout-ms consumer-stopped? consumer))) (is (= [] (test-util/call-logger-calls report-error!)))))))
[ { "context": ";; Copyright (c) 2021 Thomas J. Otterson\n;; \n;; This software is released under the MIT Li", "end": 40, "score": 0.9998087882995605, "start": 22, "tag": "NAME", "value": "Thomas J. Otterson" } ]
src/barandis/euler/p14.clj
Barandis/euler-clojure
0
;; Copyright (c) 2021 Thomas J. Otterson ;; ;; This software is released under the MIT License. ;; https://opensource.org/licenses/MIT ;; Solves Project Euler problem 14: ;; ;; The following iterative sequence is defined for the set of positive integers: ;; ;; n → n/2 (n is even) ;; n → 3n + 1 (n is odd) ;; ;; Using the rule above and starting with 13, we generate the following ;; sequence: ;; ;; 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 ;; ;; It can be seen that this sequence (starting at 13 and finishing at 1) ;; contains 10 terms. Although it has not been proved yet (Collatz Problem), it ;; is thought that all starting numbers finish at 1. ;; ;; Which starting number, under one million, produces the longest chain? ;; ;; NOTE: Once the chain starts the terms are allowed to go above one million. ;; Collatz sequences are, on the individual level, pretty unpredictable. There ;; isn't a good shortcut algorithm. So brute force is used to calculate the ;; length of each Collatz sequence. Memoization is used because it's very common ;; for two Collatz sequences to share the last several values; this cuts the ;; algorithm's runtime by about 60% when the target number is one million. ;; ;; This solution can be run using `clojure -X:p14`. It will default to the 1e6 ;; target described in the problem. To run with another target, use `clojure ;; -X:p14 :target 13` or similar. (ns barandis.euler.p14) (def prior-results "A map of collatz lengths that have already been calculated." (atom {})) (defn- collatz-length "Calculates the length of the Collatz sequence for `n`. Uses memoization to reduce the number of actual calculations that need to be made." [n] (loop [current n acc 0] (if (contains? @prior-results current) (let [result (+ acc (@prior-results current))] (swap! prior-results assoc n result) result) (if (= current 1) (let [result (inc acc)] (swap! prior-results assoc n result) result) (if (odd? current) (recur (inc (* 3 current)) (inc acc)) (recur (/ current 2) (inc acc))))))) (defn- max-collatz-length "Calculates the number between 1 and `n` (inclusive) that has the longest Collatz sequence." [n] (loop [current 1 max-start 0 max-length 0] (if (> current n) max-start (let [len (collatz-length current)] (if (> len max-length) (recur (inc current) current len) (recur (inc current) max-start max-length)))))) (defn solve "Displays the number between 1 and (:target data) that has the longest Collatz sequence. This number defaults to 1e6, which makes the displayed value the solution to Project Euler problem 14." ([] (solve {})) ([data] (-> (get data :target 1e6) max-collatz-length println time)))
76760
;; Copyright (c) 2021 <NAME> ;; ;; This software is released under the MIT License. ;; https://opensource.org/licenses/MIT ;; Solves Project Euler problem 14: ;; ;; The following iterative sequence is defined for the set of positive integers: ;; ;; n → n/2 (n is even) ;; n → 3n + 1 (n is odd) ;; ;; Using the rule above and starting with 13, we generate the following ;; sequence: ;; ;; 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 ;; ;; It can be seen that this sequence (starting at 13 and finishing at 1) ;; contains 10 terms. Although it has not been proved yet (Collatz Problem), it ;; is thought that all starting numbers finish at 1. ;; ;; Which starting number, under one million, produces the longest chain? ;; ;; NOTE: Once the chain starts the terms are allowed to go above one million. ;; Collatz sequences are, on the individual level, pretty unpredictable. There ;; isn't a good shortcut algorithm. So brute force is used to calculate the ;; length of each Collatz sequence. Memoization is used because it's very common ;; for two Collatz sequences to share the last several values; this cuts the ;; algorithm's runtime by about 60% when the target number is one million. ;; ;; This solution can be run using `clojure -X:p14`. It will default to the 1e6 ;; target described in the problem. To run with another target, use `clojure ;; -X:p14 :target 13` or similar. (ns barandis.euler.p14) (def prior-results "A map of collatz lengths that have already been calculated." (atom {})) (defn- collatz-length "Calculates the length of the Collatz sequence for `n`. Uses memoization to reduce the number of actual calculations that need to be made." [n] (loop [current n acc 0] (if (contains? @prior-results current) (let [result (+ acc (@prior-results current))] (swap! prior-results assoc n result) result) (if (= current 1) (let [result (inc acc)] (swap! prior-results assoc n result) result) (if (odd? current) (recur (inc (* 3 current)) (inc acc)) (recur (/ current 2) (inc acc))))))) (defn- max-collatz-length "Calculates the number between 1 and `n` (inclusive) that has the longest Collatz sequence." [n] (loop [current 1 max-start 0 max-length 0] (if (> current n) max-start (let [len (collatz-length current)] (if (> len max-length) (recur (inc current) current len) (recur (inc current) max-start max-length)))))) (defn solve "Displays the number between 1 and (:target data) that has the longest Collatz sequence. This number defaults to 1e6, which makes the displayed value the solution to Project Euler problem 14." ([] (solve {})) ([data] (-> (get data :target 1e6) max-collatz-length println time)))
true
;; Copyright (c) 2021 PI:NAME:<NAME>END_PI ;; ;; This software is released under the MIT License. ;; https://opensource.org/licenses/MIT ;; Solves Project Euler problem 14: ;; ;; The following iterative sequence is defined for the set of positive integers: ;; ;; n → n/2 (n is even) ;; n → 3n + 1 (n is odd) ;; ;; Using the rule above and starting with 13, we generate the following ;; sequence: ;; ;; 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 ;; ;; It can be seen that this sequence (starting at 13 and finishing at 1) ;; contains 10 terms. Although it has not been proved yet (Collatz Problem), it ;; is thought that all starting numbers finish at 1. ;; ;; Which starting number, under one million, produces the longest chain? ;; ;; NOTE: Once the chain starts the terms are allowed to go above one million. ;; Collatz sequences are, on the individual level, pretty unpredictable. There ;; isn't a good shortcut algorithm. So brute force is used to calculate the ;; length of each Collatz sequence. Memoization is used because it's very common ;; for two Collatz sequences to share the last several values; this cuts the ;; algorithm's runtime by about 60% when the target number is one million. ;; ;; This solution can be run using `clojure -X:p14`. It will default to the 1e6 ;; target described in the problem. To run with another target, use `clojure ;; -X:p14 :target 13` or similar. (ns barandis.euler.p14) (def prior-results "A map of collatz lengths that have already been calculated." (atom {})) (defn- collatz-length "Calculates the length of the Collatz sequence for `n`. Uses memoization to reduce the number of actual calculations that need to be made." [n] (loop [current n acc 0] (if (contains? @prior-results current) (let [result (+ acc (@prior-results current))] (swap! prior-results assoc n result) result) (if (= current 1) (let [result (inc acc)] (swap! prior-results assoc n result) result) (if (odd? current) (recur (inc (* 3 current)) (inc acc)) (recur (/ current 2) (inc acc))))))) (defn- max-collatz-length "Calculates the number between 1 and `n` (inclusive) that has the longest Collatz sequence." [n] (loop [current 1 max-start 0 max-length 0] (if (> current n) max-start (let [len (collatz-length current)] (if (> len max-length) (recur (inc current) current len) (recur (inc current) max-start max-length)))))) (defn solve "Displays the number between 1 and (:target data) that has the longest Collatz sequence. This number defaults to 1e6, which makes the displayed value the solution to Project Euler problem 14." ([] (solve {})) ([data] (-> (get data :target 1e6) max-collatz-length println time)))
[ { "context": "il] [:field to-id nil]]]\n col-key \"[\\\"name\\\",\\\"Some Column\\\"]\"\n norm-key {::mb.viz/column-name \"Some", "end": 6796, "score": 0.9018890261650085, "start": 6773, "tag": "KEY", "value": "name\\\",\\\"Some Column\\\"]" } ]
c#-metabase/shared/test/metabase/shared/models/visualization_settings_test.cljc
hanakhry/Crime_Admin
0
(ns metabase.shared.models.visualization-settings-test "Tests for the shared visualization-settings namespace functions" #?@ (:clj [(:require [clojure.spec.test.alpha :as stest] [clojure.test :as t] [clojure.walk :as walk] [metabase.shared.models.visualization-settings :as mb.viz])] :cljs [(:require [clojure.spec.test.alpha :as stest] [clojure.test :as t] [clojure.walk :as walk] [goog.string :as gstring] [metabase.shared.models.visualization-settings :as mb.viz])])) (def all-instrument-fns [`mb.viz/field-id->column-ref `mb.viz/column-name->column-ref `mb.viz/field-str->column-ref `mb.viz/keyname `mb.viz/parse-json-string `mb.viz/encode-json-string `mb.viz/parse-db-column-ref `mb.viz/with-col-settings `mb.viz/crossfilter-click-action `mb.viz/url-click-action `mb.viz/entity-click-action `mb.viz/with-click-action `mb.viz/with-entity-click-action `mb.viz/fk-parameter-mapping]) (defn with-spec-instrumentation-fixture "`clojure.test` fixture that turns on instrumentation of all specs in the viz settings namespace, then turns it off." [f] (stest/instrument `all-instrument-fns) (f) (stest/unstrument `all-instrument-fns)) (def fmt #?(:clj format :cljs gstring/format)) (t/use-fixtures :once with-spec-instrumentation-fixture) (t/deftest parse-column-ref-strings-test (t/testing "Column ref strings are parsed correctly" (let [f-qual-nm "/databases/MY_DB/tables/MY_TBL/fields/COL1" f-id 42 col-nm "Year"] (doseq [[input-str expected] [[(fmt "[\"ref\",[\"field\",%d,null]]" f-id) {::mb.viz/field-id f-id}] [(fmt "[\"ref\",[\"field\",\"%s\",null]]" f-qual-nm) {::mb.viz/field-str f-qual-nm}] [(fmt "[\"name\",\"Year\"]" col-nm) {::mb.viz/column-name col-nm}]]] (t/is (= expected (mb.viz/parse-db-column-ref input-str))))))) (t/deftest form-conversion-test (t/testing ":visualization_settings are correctly converted from DB to qualified form and back" (let [f-id 42 target-id 19 col-name "My Column" db-click-behavior {:type "link" :linkType "question" :parameterMapping {} :targetId target-id} db-click-bhv-map {:click_behavior db-click-behavior} col-nm-map {:show_mini_bar true :column_title "Name Column"} db-col-settings {(fmt "[\"ref\",[\"field\",%d,{\"base-type\":\"type/Integer\"}]]" f-id) db-click-bhv-map (fmt "[\"name\",\"%s\"]" col-name) col-nm-map} db-viz-settings {:column_settings db-col-settings :table.columns [{:name "ID" :fieldRef [:field f-id nil] :enabled true} {:name "Name" :fieldRef [:expression col-name] :enabled true}]} norm-click-behavior {::mb.viz/click-behavior-type ::mb.viz/link ::mb.viz/link-type ::mb.viz/card ::mb.viz/parameter-mapping {} ::mb.viz/link-target-id target-id} norm-col-nm {::mb.viz/column-title "Name Column" ::mb.viz/show-mini-bar true} norm-click-bhvr-map {::mb.viz/click-behavior norm-click-behavior} norm-col-settings {(mb.viz/field-id->column-ref f-id {"base-type" "type/Integer"}) norm-click-bhvr-map (mb.viz/column-name->column-ref col-name) norm-col-nm} norm-viz-settings {::mb.viz/column-settings norm-col-settings ::mb.viz/table-columns [{::mb.viz/table-column-name "ID" ::mb.viz/table-column-field-ref [:field f-id nil] ::mb.viz/table-column-enabled true} {::mb.viz/table-column-name "Name" ::mb.viz/table-column-field-ref [:expression col-name] ::mb.viz/table-column-enabled true}]}] (doseq [[db-form norm-form] [[db-viz-settings norm-viz-settings]]] (let [to-norm (mb.viz/db->norm db-form)] (t/is (= norm-form to-norm)) (let [to-db (mb.viz/norm->db to-norm)] (t/is (= db-form to-db))))) ;; for a non-table card, the :click_behavior map is directly underneath :visualization_settings (t/is (= norm-click-bhvr-map (mb.viz/db->norm db-click-bhv-map)))))) (t/deftest virtual-card-test (t/testing "Virtual card in visualization settings is preserved through normalization roundtrip" ;; virtual cards have the form of a regular card, mostly (let [db-form {:virtual_card {:archived false ;; the name is nil :name nil ;; there is no dataset_query :dataset_query {} ;; display is text :display "text" ;; visualization settings also exist here (being a card), but are unused :visualization_settings {}} ;; this is where the actual text is stored :text "Stuff in Textbox"}] ;; the current viz setting code does not interpret textbox type cards, hence this should be a passthrough (t/is (= db-form (-> db-form mb.viz/db->norm mb.viz/norm->db)))))) (t/deftest parameter-mapping-test (t/testing "parameterMappings are handled correctly" (let [from-id 101 to-id 294 card-id 19852 mapping-id (fmt "[\"dimension\",[\"fk->\",[\"field\",%d,null],[\"field\",%d,null]]]" from-id to-id) norm-id [:dimension [:fk-> [:field from-id nil] [:field to-id nil]]] col-key "[\"name\",\"Some Column\"]" norm-key {::mb.viz/column-name "Some Column"} dimension [:dimension [:field to-id {:source-field from-id}]] param-map {mapping-id {:id mapping-id :source {:type "column" :id "Category_ID" :name "Category ID"} :target {:type "dimension" :id mapping-id :dimension dimension}}} vs-db {:column_settings {col-key {:click_behavior {:linkType "question" :type "link" :linkTextTemplate "Link Text Template" :targetId card-id :parameterMapping param-map}}}} norm-pm {norm-id #::mb.viz{:param-mapping-id norm-id :param-mapping-source #::mb.viz{:param-ref-id "Category_ID" :param-ref-type "column" :param-ref-name "Category ID"} :param-mapping-target #::mb.viz{:param-ref-id norm-id :param-ref-type "dimension" :param-dimension dimension}}} exp-norm {::mb.viz/column-settings {norm-key {::mb.viz/click-behavior #::mb.viz{:click-behavior-type ::mb.viz/link :link-type ::mb.viz/card :link-text-template "Link Text Template" :link-target-id card-id :parameter-mapping norm-pm}}}} vs-norm (mb.viz/db->norm vs-db)] (t/is (= exp-norm vs-norm)) (t/is (= vs-db (mb.viz/norm->db vs-norm)))))) (defn- all-keywords [m] (let [all-kws (atom #{})] (walk/postwalk (fn [v] (if (keyword? v) (swap! all-kws #(conj % v)))) m) @all-kws)) (t/deftest comprehensive-click-actions-test (t/testing "Visualization settings for card in 'EE14566 - Click Behavior visualization_settings' should be handled" (let [db-form {:column_settings {"[\"name\",\"Year\"]" {:click_behavior {:type "crossfilter", :parameterMapping {:447496ef {:source {:type "column", :id "Year", :name "Year"}, :target {:type "parameter", :id "447496ef"}, :id "447496ef"}}}}, "[\"name\",\"Question: Plain QB - Orders\"]" {:click_behavior {:type "link", :linkType "question", :parameterMapping {}, :targetId 1}}, "[\"name\",\"Dashboard: EE532\"]" {:click_behavior {:type "link", :linkType "dashboard", :parameterMapping {}, :targetId 2}}, "[\"name\",\"Custom Destination\"]" {:click_behavior {:type "link", :linkType "url", :linkTemplate "/dashboard/1?year={{column:Year}}"}}}} norm-form (mb.viz/db->norm db-form) to-db (mb.viz/norm->db norm-form)] ;; make sure all keywords have the right namespace in normalized form (except the one param mapping key) (t/is (= [:447496ef] (filter #(not= (namespace %) (namespace ::mb.viz/column-settings)) (all-keywords norm-form)))) ;; make sure all keywords have the right namespace in normalized form (t/is (empty? (filter #(some? (namespace %)) (all-keywords to-db)))) (t/is (= db-form to-db)))))
116186
(ns metabase.shared.models.visualization-settings-test "Tests for the shared visualization-settings namespace functions" #?@ (:clj [(:require [clojure.spec.test.alpha :as stest] [clojure.test :as t] [clojure.walk :as walk] [metabase.shared.models.visualization-settings :as mb.viz])] :cljs [(:require [clojure.spec.test.alpha :as stest] [clojure.test :as t] [clojure.walk :as walk] [goog.string :as gstring] [metabase.shared.models.visualization-settings :as mb.viz])])) (def all-instrument-fns [`mb.viz/field-id->column-ref `mb.viz/column-name->column-ref `mb.viz/field-str->column-ref `mb.viz/keyname `mb.viz/parse-json-string `mb.viz/encode-json-string `mb.viz/parse-db-column-ref `mb.viz/with-col-settings `mb.viz/crossfilter-click-action `mb.viz/url-click-action `mb.viz/entity-click-action `mb.viz/with-click-action `mb.viz/with-entity-click-action `mb.viz/fk-parameter-mapping]) (defn with-spec-instrumentation-fixture "`clojure.test` fixture that turns on instrumentation of all specs in the viz settings namespace, then turns it off." [f] (stest/instrument `all-instrument-fns) (f) (stest/unstrument `all-instrument-fns)) (def fmt #?(:clj format :cljs gstring/format)) (t/use-fixtures :once with-spec-instrumentation-fixture) (t/deftest parse-column-ref-strings-test (t/testing "Column ref strings are parsed correctly" (let [f-qual-nm "/databases/MY_DB/tables/MY_TBL/fields/COL1" f-id 42 col-nm "Year"] (doseq [[input-str expected] [[(fmt "[\"ref\",[\"field\",%d,null]]" f-id) {::mb.viz/field-id f-id}] [(fmt "[\"ref\",[\"field\",\"%s\",null]]" f-qual-nm) {::mb.viz/field-str f-qual-nm}] [(fmt "[\"name\",\"Year\"]" col-nm) {::mb.viz/column-name col-nm}]]] (t/is (= expected (mb.viz/parse-db-column-ref input-str))))))) (t/deftest form-conversion-test (t/testing ":visualization_settings are correctly converted from DB to qualified form and back" (let [f-id 42 target-id 19 col-name "My Column" db-click-behavior {:type "link" :linkType "question" :parameterMapping {} :targetId target-id} db-click-bhv-map {:click_behavior db-click-behavior} col-nm-map {:show_mini_bar true :column_title "Name Column"} db-col-settings {(fmt "[\"ref\",[\"field\",%d,{\"base-type\":\"type/Integer\"}]]" f-id) db-click-bhv-map (fmt "[\"name\",\"%s\"]" col-name) col-nm-map} db-viz-settings {:column_settings db-col-settings :table.columns [{:name "ID" :fieldRef [:field f-id nil] :enabled true} {:name "Name" :fieldRef [:expression col-name] :enabled true}]} norm-click-behavior {::mb.viz/click-behavior-type ::mb.viz/link ::mb.viz/link-type ::mb.viz/card ::mb.viz/parameter-mapping {} ::mb.viz/link-target-id target-id} norm-col-nm {::mb.viz/column-title "Name Column" ::mb.viz/show-mini-bar true} norm-click-bhvr-map {::mb.viz/click-behavior norm-click-behavior} norm-col-settings {(mb.viz/field-id->column-ref f-id {"base-type" "type/Integer"}) norm-click-bhvr-map (mb.viz/column-name->column-ref col-name) norm-col-nm} norm-viz-settings {::mb.viz/column-settings norm-col-settings ::mb.viz/table-columns [{::mb.viz/table-column-name "ID" ::mb.viz/table-column-field-ref [:field f-id nil] ::mb.viz/table-column-enabled true} {::mb.viz/table-column-name "Name" ::mb.viz/table-column-field-ref [:expression col-name] ::mb.viz/table-column-enabled true}]}] (doseq [[db-form norm-form] [[db-viz-settings norm-viz-settings]]] (let [to-norm (mb.viz/db->norm db-form)] (t/is (= norm-form to-norm)) (let [to-db (mb.viz/norm->db to-norm)] (t/is (= db-form to-db))))) ;; for a non-table card, the :click_behavior map is directly underneath :visualization_settings (t/is (= norm-click-bhvr-map (mb.viz/db->norm db-click-bhv-map)))))) (t/deftest virtual-card-test (t/testing "Virtual card in visualization settings is preserved through normalization roundtrip" ;; virtual cards have the form of a regular card, mostly (let [db-form {:virtual_card {:archived false ;; the name is nil :name nil ;; there is no dataset_query :dataset_query {} ;; display is text :display "text" ;; visualization settings also exist here (being a card), but are unused :visualization_settings {}} ;; this is where the actual text is stored :text "Stuff in Textbox"}] ;; the current viz setting code does not interpret textbox type cards, hence this should be a passthrough (t/is (= db-form (-> db-form mb.viz/db->norm mb.viz/norm->db)))))) (t/deftest parameter-mapping-test (t/testing "parameterMappings are handled correctly" (let [from-id 101 to-id 294 card-id 19852 mapping-id (fmt "[\"dimension\",[\"fk->\",[\"field\",%d,null],[\"field\",%d,null]]]" from-id to-id) norm-id [:dimension [:fk-> [:field from-id nil] [:field to-id nil]]] col-key "[\"<KEY>" norm-key {::mb.viz/column-name "Some Column"} dimension [:dimension [:field to-id {:source-field from-id}]] param-map {mapping-id {:id mapping-id :source {:type "column" :id "Category_ID" :name "Category ID"} :target {:type "dimension" :id mapping-id :dimension dimension}}} vs-db {:column_settings {col-key {:click_behavior {:linkType "question" :type "link" :linkTextTemplate "Link Text Template" :targetId card-id :parameterMapping param-map}}}} norm-pm {norm-id #::mb.viz{:param-mapping-id norm-id :param-mapping-source #::mb.viz{:param-ref-id "Category_ID" :param-ref-type "column" :param-ref-name "Category ID"} :param-mapping-target #::mb.viz{:param-ref-id norm-id :param-ref-type "dimension" :param-dimension dimension}}} exp-norm {::mb.viz/column-settings {norm-key {::mb.viz/click-behavior #::mb.viz{:click-behavior-type ::mb.viz/link :link-type ::mb.viz/card :link-text-template "Link Text Template" :link-target-id card-id :parameter-mapping norm-pm}}}} vs-norm (mb.viz/db->norm vs-db)] (t/is (= exp-norm vs-norm)) (t/is (= vs-db (mb.viz/norm->db vs-norm)))))) (defn- all-keywords [m] (let [all-kws (atom #{})] (walk/postwalk (fn [v] (if (keyword? v) (swap! all-kws #(conj % v)))) m) @all-kws)) (t/deftest comprehensive-click-actions-test (t/testing "Visualization settings for card in 'EE14566 - Click Behavior visualization_settings' should be handled" (let [db-form {:column_settings {"[\"name\",\"Year\"]" {:click_behavior {:type "crossfilter", :parameterMapping {:447496ef {:source {:type "column", :id "Year", :name "Year"}, :target {:type "parameter", :id "447496ef"}, :id "447496ef"}}}}, "[\"name\",\"Question: Plain QB - Orders\"]" {:click_behavior {:type "link", :linkType "question", :parameterMapping {}, :targetId 1}}, "[\"name\",\"Dashboard: EE532\"]" {:click_behavior {:type "link", :linkType "dashboard", :parameterMapping {}, :targetId 2}}, "[\"name\",\"Custom Destination\"]" {:click_behavior {:type "link", :linkType "url", :linkTemplate "/dashboard/1?year={{column:Year}}"}}}} norm-form (mb.viz/db->norm db-form) to-db (mb.viz/norm->db norm-form)] ;; make sure all keywords have the right namespace in normalized form (except the one param mapping key) (t/is (= [:447496ef] (filter #(not= (namespace %) (namespace ::mb.viz/column-settings)) (all-keywords norm-form)))) ;; make sure all keywords have the right namespace in normalized form (t/is (empty? (filter #(some? (namespace %)) (all-keywords to-db)))) (t/is (= db-form to-db)))))
true
(ns metabase.shared.models.visualization-settings-test "Tests for the shared visualization-settings namespace functions" #?@ (:clj [(:require [clojure.spec.test.alpha :as stest] [clojure.test :as t] [clojure.walk :as walk] [metabase.shared.models.visualization-settings :as mb.viz])] :cljs [(:require [clojure.spec.test.alpha :as stest] [clojure.test :as t] [clojure.walk :as walk] [goog.string :as gstring] [metabase.shared.models.visualization-settings :as mb.viz])])) (def all-instrument-fns [`mb.viz/field-id->column-ref `mb.viz/column-name->column-ref `mb.viz/field-str->column-ref `mb.viz/keyname `mb.viz/parse-json-string `mb.viz/encode-json-string `mb.viz/parse-db-column-ref `mb.viz/with-col-settings `mb.viz/crossfilter-click-action `mb.viz/url-click-action `mb.viz/entity-click-action `mb.viz/with-click-action `mb.viz/with-entity-click-action `mb.viz/fk-parameter-mapping]) (defn with-spec-instrumentation-fixture "`clojure.test` fixture that turns on instrumentation of all specs in the viz settings namespace, then turns it off." [f] (stest/instrument `all-instrument-fns) (f) (stest/unstrument `all-instrument-fns)) (def fmt #?(:clj format :cljs gstring/format)) (t/use-fixtures :once with-spec-instrumentation-fixture) (t/deftest parse-column-ref-strings-test (t/testing "Column ref strings are parsed correctly" (let [f-qual-nm "/databases/MY_DB/tables/MY_TBL/fields/COL1" f-id 42 col-nm "Year"] (doseq [[input-str expected] [[(fmt "[\"ref\",[\"field\",%d,null]]" f-id) {::mb.viz/field-id f-id}] [(fmt "[\"ref\",[\"field\",\"%s\",null]]" f-qual-nm) {::mb.viz/field-str f-qual-nm}] [(fmt "[\"name\",\"Year\"]" col-nm) {::mb.viz/column-name col-nm}]]] (t/is (= expected (mb.viz/parse-db-column-ref input-str))))))) (t/deftest form-conversion-test (t/testing ":visualization_settings are correctly converted from DB to qualified form and back" (let [f-id 42 target-id 19 col-name "My Column" db-click-behavior {:type "link" :linkType "question" :parameterMapping {} :targetId target-id} db-click-bhv-map {:click_behavior db-click-behavior} col-nm-map {:show_mini_bar true :column_title "Name Column"} db-col-settings {(fmt "[\"ref\",[\"field\",%d,{\"base-type\":\"type/Integer\"}]]" f-id) db-click-bhv-map (fmt "[\"name\",\"%s\"]" col-name) col-nm-map} db-viz-settings {:column_settings db-col-settings :table.columns [{:name "ID" :fieldRef [:field f-id nil] :enabled true} {:name "Name" :fieldRef [:expression col-name] :enabled true}]} norm-click-behavior {::mb.viz/click-behavior-type ::mb.viz/link ::mb.viz/link-type ::mb.viz/card ::mb.viz/parameter-mapping {} ::mb.viz/link-target-id target-id} norm-col-nm {::mb.viz/column-title "Name Column" ::mb.viz/show-mini-bar true} norm-click-bhvr-map {::mb.viz/click-behavior norm-click-behavior} norm-col-settings {(mb.viz/field-id->column-ref f-id {"base-type" "type/Integer"}) norm-click-bhvr-map (mb.viz/column-name->column-ref col-name) norm-col-nm} norm-viz-settings {::mb.viz/column-settings norm-col-settings ::mb.viz/table-columns [{::mb.viz/table-column-name "ID" ::mb.viz/table-column-field-ref [:field f-id nil] ::mb.viz/table-column-enabled true} {::mb.viz/table-column-name "Name" ::mb.viz/table-column-field-ref [:expression col-name] ::mb.viz/table-column-enabled true}]}] (doseq [[db-form norm-form] [[db-viz-settings norm-viz-settings]]] (let [to-norm (mb.viz/db->norm db-form)] (t/is (= norm-form to-norm)) (let [to-db (mb.viz/norm->db to-norm)] (t/is (= db-form to-db))))) ;; for a non-table card, the :click_behavior map is directly underneath :visualization_settings (t/is (= norm-click-bhvr-map (mb.viz/db->norm db-click-bhv-map)))))) (t/deftest virtual-card-test (t/testing "Virtual card in visualization settings is preserved through normalization roundtrip" ;; virtual cards have the form of a regular card, mostly (let [db-form {:virtual_card {:archived false ;; the name is nil :name nil ;; there is no dataset_query :dataset_query {} ;; display is text :display "text" ;; visualization settings also exist here (being a card), but are unused :visualization_settings {}} ;; this is where the actual text is stored :text "Stuff in Textbox"}] ;; the current viz setting code does not interpret textbox type cards, hence this should be a passthrough (t/is (= db-form (-> db-form mb.viz/db->norm mb.viz/norm->db)))))) (t/deftest parameter-mapping-test (t/testing "parameterMappings are handled correctly" (let [from-id 101 to-id 294 card-id 19852 mapping-id (fmt "[\"dimension\",[\"fk->\",[\"field\",%d,null],[\"field\",%d,null]]]" from-id to-id) norm-id [:dimension [:fk-> [:field from-id nil] [:field to-id nil]]] col-key "[\"PI:KEY:<KEY>END_PI" norm-key {::mb.viz/column-name "Some Column"} dimension [:dimension [:field to-id {:source-field from-id}]] param-map {mapping-id {:id mapping-id :source {:type "column" :id "Category_ID" :name "Category ID"} :target {:type "dimension" :id mapping-id :dimension dimension}}} vs-db {:column_settings {col-key {:click_behavior {:linkType "question" :type "link" :linkTextTemplate "Link Text Template" :targetId card-id :parameterMapping param-map}}}} norm-pm {norm-id #::mb.viz{:param-mapping-id norm-id :param-mapping-source #::mb.viz{:param-ref-id "Category_ID" :param-ref-type "column" :param-ref-name "Category ID"} :param-mapping-target #::mb.viz{:param-ref-id norm-id :param-ref-type "dimension" :param-dimension dimension}}} exp-norm {::mb.viz/column-settings {norm-key {::mb.viz/click-behavior #::mb.viz{:click-behavior-type ::mb.viz/link :link-type ::mb.viz/card :link-text-template "Link Text Template" :link-target-id card-id :parameter-mapping norm-pm}}}} vs-norm (mb.viz/db->norm vs-db)] (t/is (= exp-norm vs-norm)) (t/is (= vs-db (mb.viz/norm->db vs-norm)))))) (defn- all-keywords [m] (let [all-kws (atom #{})] (walk/postwalk (fn [v] (if (keyword? v) (swap! all-kws #(conj % v)))) m) @all-kws)) (t/deftest comprehensive-click-actions-test (t/testing "Visualization settings for card in 'EE14566 - Click Behavior visualization_settings' should be handled" (let [db-form {:column_settings {"[\"name\",\"Year\"]" {:click_behavior {:type "crossfilter", :parameterMapping {:447496ef {:source {:type "column", :id "Year", :name "Year"}, :target {:type "parameter", :id "447496ef"}, :id "447496ef"}}}}, "[\"name\",\"Question: Plain QB - Orders\"]" {:click_behavior {:type "link", :linkType "question", :parameterMapping {}, :targetId 1}}, "[\"name\",\"Dashboard: EE532\"]" {:click_behavior {:type "link", :linkType "dashboard", :parameterMapping {}, :targetId 2}}, "[\"name\",\"Custom Destination\"]" {:click_behavior {:type "link", :linkType "url", :linkTemplate "/dashboard/1?year={{column:Year}}"}}}} norm-form (mb.viz/db->norm db-form) to-db (mb.viz/norm->db norm-form)] ;; make sure all keywords have the right namespace in normalized form (except the one param mapping key) (t/is (= [:447496ef] (filter #(not= (namespace %) (namespace ::mb.viz/column-settings)) (all-keywords norm-form)))) ;; make sure all keywords have the right namespace in normalized form (t/is (empty? (filter #(some? (namespace %)) (all-keywords to-db)))) (t/is (= db-form to-db)))))
[ { "context": " content\")\n\n(def ADMIN_AND_WRITER_STONECUTTER_ID \"d-cent-123123\")\n(def OBJECTIVE_OWNER_TWITTER_ID \"twitter-7", "end": 3208, "score": 0.6713203191757202, "start": 3200, "tag": "USERNAME", "value": "d-cent-1" }, { "context": "\n\n(def ADMIN_AND_WRITER_STONECUTTER_ID \"d-cent-123123\")\n(def OBJECTIVE_OWNER_TWITTER_ID \"twitter-789789", "end": 3213, "score": 0.5918616652488708, "start": 3210, "tag": "USERNAME", "value": "123" }, { "context": "\"d-cent-123123\")\n(def OBJECTIVE_OWNER_TWITTER_ID \"twitter-789789\")\n\n(against-background\n [(sign-in/twitter-creden", "end": 3263, "score": 0.9757145643234253, "start": 3249, "tag": "USERNAME", "value": "twitter-789789" }, { "context": "there\")\n\n (wd/input-text \"#username\" \"funcTestUser123\")\n (-> \"#email-address\"\n ", "end": 4860, "score": 0.9996525645256042, "start": 4845, "tag": "USERNAME", "value": "funcTestUser123" }, { "context": "\"#email-address\"\n (wd/input-text \"func_test_user@domain.com\")\n wd/submit)\n\n (scre", "end": 4955, "score": 0.9992845058441162, "start": 4930, "tag": "EMAIL", "value": "func_test_user@domain.com" }, { "context": "est headline\"\n :writer-name \"funcTestUser123\"}))\n\n (fact \"user cannot see empty promoted obje", "end": 6215, "score": 0.9957661628723145, "start": 6200, "tag": "USERNAME", "value": "funcTestUser123" }, { "context": " (wd/input-text \".func--writer-email\" \"func_test_writer@domain.com\")\n (-> \".func--writer-reason\"\n ", "end": 12507, "score": 0.9999237060546875, "start": 12480, "tag": "EMAIL", "value": "func_test_writer@domain.com" }, { "context": "r-title \"Sign up | Objective[8]\")\n (-> \"#username\"\n (wd/input-text \"funcTestWriter\"", "end": 13980, "score": 0.9946730136871338, "start": 13970, "tag": "USERNAME", "value": "\"#username" }, { "context": " (-> \"#username\"\n (wd/input-text \"funcTestWriter\")\n wd/submit)\n\n (wait", "end": 14029, "score": 0.9991700649261475, "start": 14015, "tag": "USERNAME", "value": "funcTestWriter" }, { "context": "rd\"\n (try (wd/to \"localhost:8080/users/funcTestUser123\")\n (wait-for-title \"funcTestUs", "end": 24496, "score": 0.5299196839332581, "start": 24492, "tag": "USERNAME", "value": "Test" } ]
test/objective8/functional/functional_tests.clj
d-cent/objective8
23
(ns objective8.functional.functional-tests (:require [midje.sweet :refer :all] [org.httpkit.server :refer [run-server]] [clj-webdriver.taxi :as wd] [clojure.java.io :as io] [clojure.tools.logging :as log] [clojure.string :as string] [objective8.core :as core] [objective8.back-end.domain.users :as users] [objective8.integration.integration-helpers :as integration-helpers] [dev-helpers.stub-twitter-and-stonecutter :refer :all] [objective8.front-end.templates.sign-in :as sign-in])) (def config-without-twitter-or-stonecutter (assoc core/app-config :authentication stub-twitter-and-stonecutter-auth-config)) (defn wait-for-title [title] (try (wd/wait-until #(= (wd/title) title) 5000) (catch Exception e (log/info (str ">>>>>>>>>>> Title never appeared:")) (log/info (str "Expected: " title)) (log/info (str "Actual: " (wd/title))) (throw e)))) (def not-empty? (comp not empty?)) (defn wait-for-element [q] (try (wd/wait-until #(not-empty? (wd/elements q)) 5000) (catch Exception e (log/info (str "Could not find element: " q)) (throw e)))) (defn wait-for [pred] (try (wd/wait-until pred 5000) (catch Exception e (log/info (str "Waiting for predicate failed")) (throw e)))) (defn check-not-present [element] (if (try (wd/present? element) false (catch Exception e true)) true (do (throw (Throwable. (str "Element " element " was found that should not be present"))) false))) (def screenshot-directory "test/objective8/functional/screenshots") (def screenshot-number (atom 0)) (defn screenshot [filename] (log/info (str "Screenshot: " filename)) (wd/take-screenshot :file (str screenshot-directory "/" (format "%02d" (swap! screenshot-number + 1)) "_" filename ".png"))) (defn clear-screenshots [] (doall (->> (io/file screenshot-directory) file-seq (filter #(re-matches #".*\.png$" (.getName %))) (map io/delete-file)))) (def journey-state (atom nil)) (def test-data-collector (atom {})) (def objective-description "Functional test description with lots of hipster-ipsum: Master cleanse squid nulla, ugh kitsch biodiesel cronut food truck. Nostrud Schlitz tempor farm-to-table skateboard, wayfarers adipisicing Pitchfork sunt Neutra brunch four dollar toast forage placeat. Fugiat lo-fi sed polaroid Portland et tofu Austin. Blue Bottle labore forage, in bitters incididunt ugh delectus seitan flannel. Mixtape migas cardigan, quis American Apparel culpa aliquip cupidatat et nisi scenester. Labore sriracha Etsy flannel XOXO. Normcore selvage do vero keytar synth.") (def FIRST_DRAFT_MARKDOWN "First draft heading\n===\n\n- Some content") (def SECOND_DRAFT_MARKDOWN "Second draft heading\n===\n\n- Some content\n- Some more content") (def THIRD_DRAFT_MARKDOWN "Third draft heading\n===\n\n- Some content\n- Some more content\n- Another line of content") (def ADMIN_AND_WRITER_STONECUTTER_ID "d-cent-123123") (def OBJECTIVE_OWNER_TWITTER_ID "twitter-789789") (against-background [(sign-in/twitter-credentials-present?) => true (sign-in/stonecutter-credentials-present?) => true (before :contents (do (integration-helpers/db-connection) (integration-helpers/truncate-tables) (core/start-server config-without-twitter-or-stonecutter) (wd/set-driver! {:browser :firefox}) (users/store-admin! {:auth-provider-user-id ADMIN_AND_WRITER_STONECUTTER_ID}) (reset! journey-state {}) (clear-screenshots))) (before :facts (reset! test-data-collector {})) (after :contents (do (wd/quit) (integration-helpers/truncate-tables) (core/stop-back-end-server) (core/stop-front-end-server)))] (fact "can add an objective" (try (reset! twitter-id OBJECTIVE_OWNER_TWITTER_ID) (wd/to "localhost:8080") (wait-for-title "Objective[8]") (screenshot "home_page") (wd/click "a[href='/objectives']") (wait-for-title "Objectives | Objective[8]") (screenshot "objectives_page") (wd/click "a[href='/objectives/create']") (wait-for-title "Sign in or Sign up | Objective[8]") (screenshot "sign_in_page") (wd/click ".func--sign-in-with-twitter") (wait-for-title "Sign up | Objective[8]") (screenshot "sign_up_almost_there") (wd/input-text "#username" "funcTestUser123") (-> "#email-address" (wd/input-text "func_test_user@domain.com") wd/submit) (screenshot "create_objective_page") (wait-for-title "Create an Objective | Objective[8]") (-> (wd/input-text ".func--input-objective-title" "F") (wd/submit)) (wait-for-element ".func--objective-title-error") (screenshot "create_objective_invalid_title") (wd/input-text ".func--input-objective-title" "unctional test headline") (-> ".func--input-objective-background" (wd/input-text objective-description) wd/submit) (wait-for-title "Functional test headline | Objective[8]") (swap! journey-state assoc :objective-url (wd/current-url)) (screenshot "objective_page") {:page-title (wd/title) :modal-text (wd/text ".func--share-objective-modal-text") :writer-name (wd/text ".func--writer-name")} (catch Exception e (screenshot "ERROR-Can-add-an-objective") (throw e))) => (contains {:page-title "Functional test headline | Objective[8]" :modal-text "Functional test headline" :writer-name "funcTestUser123"})) (fact "user cannot see empty promoted objectives container" (try (wd/click "a[href='/objectives']") (wait-for-title "Objectives | Objective[8]") (check-not-present ".clj-promoted-objectives-container") (catch Exception e (screenshot "ERROR-Cannot-see-empty-promoted-objectives") (throw e)))) (fact "Can star an objective" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--objective-star") (wd/to "/") (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_with_starred_objective") (wd/attribute ".func--objective-star" :class) (catch Exception e (screenshot "ERROR-Can-star-an-objective") (throw e))) => (contains "starred")) (fact "Can comment on an objective" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/input-text ".func--comment-form-text-area" "Functional test comment text") (wd/click ".func--comment-form-submit") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_comment") (wait-for-title "Functional test headline | Objective[8]") (wd/input-text ".func--comment-form-text-area" "Functional test second comment text") (wd/click ".func--comment-form-submit") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_two_comments") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-comment-on-an-objective") (throw e))) => (contains "Functional test comment text")) (fact "Can view and navigate comment history for an objective" (try (wd/to (str (:objective-url @journey-state) "/comments?offset=1")) (wait-for-title "Comments for Functional test headline | Objective[8]") (screenshot "objective_comment_history_offset_1") (swap! test-data-collector assoc :offset-equals-1-comment-count (count (wd/elements ".func--comment-text"))) (wd/click ".func--previous-link") (wait-for-title "Comments for Functional test headline | Objective[8]") (screenshot "objective_comment_history_offset_0") (swap! test-data-collector assoc :offset-equals-0-comment-count (count (wd/elements ".func--comment-text"))) @test-data-collector (catch Exception e (screenshot "ERROR-Can-view-comment-history-for-an-objective") (throw e))) ) => {:offset-equals-1-comment-count 1 :offset-equals-0-comment-count 2} (fact "Can add a question" (try (wd/to "localhost:8080/objectives") (wait-for-title "Objectives | Objective[8]") (screenshot "objectives_page_with_an_objective") (wd/click ".func--objective-list-item-link") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page") (wd/click ".func--add-question") (wait-for-element ".func--question-textarea") (screenshot "add_question_page") (-> ".func--question-textarea" (wd/input-text "Functional test question") (wd/submit)) (wait-for-element ".func--add-question") (screenshot "objective_page_with_question") {:modal-text (wd/text ".func--share-question-modal-text")} (catch Exception e (screenshot "Error-Can-add-questions") (throw e))) => {:modal-text "Functional test question"}) (fact "Objective owner can promote and demote questions" (try (wd/to (:objective-url @journey-state)) (wait-for-element ".func--demote-question") (wd/click ".func--demote-question") (wait-for-element ".func--promote-question") (screenshot "demoted_question") (wait-for-element ".func--promote-question") (wd/click ".func--promote-question") (screenshot "promoted_question") (catch Exception e (screenshot "Error-Objective-owner-can-promote-and-demote-questions") (throw e)))) (fact "Can answer a question" (try (wd/to (:objective-url @journey-state)) (wait-for-element ".func--answer-link") (wd/click ".func--answer-link") (wait-for-element ".func--add-answer") (-> ".func--add-answer" (wd/input-text "Functional test answer") (wd/submit)) (wait-for-element ".func--answer-text") (screenshot "answered_question") (swap! journey-state assoc :question-url (wd/current-url)) (wd/text ".func--answer-text") (catch Exception e (screenshot "Error-Can-answer-questions") (throw e))) => "Functional test answer") (fact "Can up vote an answer" (try (wd/to (:question-url @journey-state)) (wait-for-element "textarea.func--add-answer") (wd/text ".func--up-score") => "0" (wd/click "button.func--up-vote") (wait-for-element "textarea.func--add-answer") (wd/text ".func--up-score") => "1" (catch Exception e (screenshot "Error-Can-vote-on-an-answer") (throw e)))) (fact "Can invite a writer" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page") (wd/click ".func--invite-writer") (wait-for-element ".func--invite-writer") (screenshot "invite_writer_page") (wd/input-text ".func--writer-name" "Invitee name") (wd/input-text ".func--writer-email" "func_test_writer@domain.com") (-> ".func--writer-reason" (wd/input-text "Functional test invitation reason") wd/submit) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_invitation_flash") (->> (wd/value ".func--invitation-url") (re-find #"http://.*$") (swap! journey-state assoc :invitation-url)) {:page-title (wd/title) :flash-message (wd/text ".func--invitation-guidance")} (catch Exception e (screenshot "ERROR-Can-invite-a-writer") (throw e))) => (contains {:page-title "Functional test headline | Objective[8]" :flash-message (contains "Your writer's invitation")})) (fact "Can accept a writer invitation" (try (reset! stonecutter-id ADMIN_AND_WRITER_STONECUTTER_ID) (wd/click ".func--masthead-sign-out") (screenshot "after_sign_out") (wd/to (:invitation-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_after_hitting_invitation_url") (wd/click ".func--sign-in-to-accept") (wait-for-title "Sign in or Sign up | Objective[8]") (wd/click ".func--sign-in-with-d-cent") (wait-for-title "Sign up | Objective[8]") (-> "#username" (wd/input-text "funcTestWriter") wd/submit) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_after_signing_up") (wd/click ".func--invitation-accept") (wait-for-title "Create profile | Objective[8]") (screenshot "create_profile_page") (wd/input-text ".func--name" "Invited writer real name") (-> ".func--biog" (wd/input-text "Biography with lots of text...") wd/submit) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_from_recently_added_writer") (wd/text (second (wd/elements ".func--writer-name"))) (catch Exception e (screenshot "ERROR-Can-accept-a-writer-invitation") (throw e))) => "Invited writer real name") (fact "Can view writer profile page" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click (second (wd/elements ".func--writer-name"))) (wait-for-title "Invited writer real name | Objective[8]") (screenshot "writer_profile_page") {:biog-text (wd/text (first (wd/elements ".func--writer-biog"))) :objective-title (wd/text (first (wd/elements ".func--objective-title")))} (catch Exception e (screenshot "ERROR-can-view-writer-profile") (throw e))) => {:biog-text "Biography with lots of text..." :objective-title "Functional test headline"}) (fact "Can edit writer profile" (try (wd/click ".func--edit-profile") (wait-for-title "Edit profile | Objective[8]") (screenshot "edit_profile_page") (-> ".func--name" wd/clear (wd/input-text "My new real name")) (-> ".func--biog" wd/clear (wd/input-text "My new biography") wd/submit) (wait-for-title "My new real name | Objective[8]") (screenshot "updated_profile_page") {:name (wd/text (first (wd/elements ".func--writer-name"))) :biog (wd/text (first (wd/elements ".func--writer-biog")))} (catch Exception e (screenshot "ERROR-can-edit-writer-profile") (throw e))) => (contains {:biog "My new biography"})) (fact "Can access dashboard from profile page" (try (wd/click ".func--dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "writer_dashboard_from_profile_page") (wd/current-url) (catch Exception e (screenshot "ERROR-can-access-dashboard-from-profile-page") (throw e))) => (contains (str (:objective-url @journey-state) "/dashboard/questions"))) (fact "Can submit a draft" (try (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (screenshot "drafts_list_no_drafts") (wd/click ".func--add-a-draft") (wait-for-title "Add draft | Objective[8]") (screenshot "add_draft_empty") (wd/input-text ".func--add-draft-content" FIRST_DRAFT_MARKDOWN) (wd/click ".func--preview-action") (wait-for-title "Add draft | Objective[8]") (screenshot "preview_draft") (wd/click ".func--submit-action") (wait-for-title "Policy draft | Objective[8]") (screenshot "submitted_draft") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-Can-submit-a-draft") (throw e))) => (contains {:page-title "Policy draft | Objective[8]" :page-source (contains "First draft heading")})) (fact "Can view latest draft" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_a_draft") (wd/click ".func--drafting-message-link") (wait-for-title "Drafts | Objective[8]") (screenshot "drafts_list_with_one_draft") (wd/click ".func--latest-draft-link") (wait-for-title "Policy draft | Objective[8]") (screenshot "latest_draft") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-Can-view-latest-draft") (throw e))) => (contains {:page-title "Policy draft | Objective[8]" :page-source (contains "First draft heading")})) (fact "Can comment on a draft" (try (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (wd/input-text ".func--comment-form-text-area" "Functional test comment text") (wd/click ".func--comment-form-submit") (wait-for-title "Policy draft | Objective[8]") (screenshot "draft_with_comment") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-comment-on-a-draft") (throw e))) => (contains "Functional test comment text")) (fact "Can down vote a comment on a draft" (try (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (wd/text ".func--down-score") => "0" (wd/click "button.func--down-vote") (wait-for-title "Policy draft | Objective[8]") (wd/text ".func--down-score") => "1" (catch Exception e (screenshot "ERROR-Can-vote-on-a-comment-on-a-draft") (throw e)))) (fact "Can navigate between drafts" (try (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (screenshot "list_of_drafts_with_one_draft") (wd/click ".func--add-a-draft") (wait-for-title "Add draft | Objective[8]") (wd/input-text ".func--add-draft-content" SECOND_DRAFT_MARKDOWN) (wd/click ".func--submit-action") (wait-for-title "Policy draft | Objective[8]") (screenshot "second_draft") (wd/click ".func--parent-link") (wait-for-title "Drafts | Objective[8]") (wd/click ".func--add-a-draft") (wait-for-title "Add draft | Objective[8]") (wd/input-text ".func--add-draft-content" THIRD_DRAFT_MARKDOWN) (wd/click ".func--submit-action") (wait-for-title "Policy draft | Objective[8]") (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (screenshot "list_of_drafts_with_three_drafts") (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (screenshot "latest_draft_with_previous_button") (wd/click ".func--previous-link") (wait-for-title "Policy draft | Objective[8]") (screenshot "second_draft_with_next") (wd/click ".func--next-link") (wait-for-title "Policy draft | Objective[8]") (screenshot "third_draft") (swap! journey-state assoc :draft-url (wd/current-url)) (swap! journey-state assoc :section-label (wd/attribute "h1" :data-section-label)) (wd/page-source) (catch Exception e (screenshot "ERROR-Can-navigate-between-drafts") (throw e))) => (contains "Third draft heading")) (fact "Can view draft diffs" (try (wd/click ".func--what-changed") (wait-for-title "Draft changes | Objective[8]") (screenshot "draft_diff") (catch Exception e (screenshot "ERROR-Can-view-draft-diffs") (throw e)))) (fact "Can view draft section" (try (wd/click ".func--back-to-draft") (wait-for-title "Policy draft | Objective[8]") (wd/click ".func--annotation-link") (wait-for-title "Draft section | Objective[8]") (screenshot "draft_section") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-view-draft-section") (throw e))) => (contains "Third draft heading")) (fact "Can annotate a draft section" (try (wd/input-text ".func--comment-form-text-area" "my draft section annotation") (wd/click ".func--comment-reason-select") (wd/click ".func--comment-form-submit") (wait-for-title "Draft section | Objective[8]") (screenshot "draft_section_with_comment") {:annotation (wd/text ".func--comment-text") :annotation-reason (wd/text ".func--comment-reason-text")} (catch Exception e (screenshot "ERROR-Can-annotate-a-draft-section") (throw e))) => {:annotation "my draft section annotation" :annotation-reason "Section is difficult to understand"}) (fact "Can view number of annotations on a section" (try (wd/click ".func--back-to-draft") (wait-for-title "Policy draft | Objective[8]") (screenshot "draft_with_one_annotation") (wd/text ".func--annotation-count") (catch Exception e (screenshot "ERROR-Can-view-number-of-annotations-on-a-section") (throw e))) => "1") (fact "Can navigate to import from Google Drive" (try (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (wd/click ".func--import-draft-link") (wait-for-title "Import draft | Objective[8]") (screenshot "import_draft") (wd/click ".func--cancel-link") (wait-for-title "Drafts | Objective[8]") (screenshot "draft_list") (catch Exception e (screenshot "ERROR-Can-navigate-to-import-from-Google-Drive") (throw e)))) (fact "Can view questions dashboard" (try (wd/to "localhost:8080/users/funcTestUser123") (wait-for-title "funcTestUser123 | Objective[8]") (screenshot "objectives_list_as_a_writer_with_an_objective") (wd/click ".func--dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "questions_dashboard") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-can-view-questions-dashboard") (throw e))) => (contains {:page-title "Writer dashboard | Objective[8]" :page-source (every-checker (contains "Functional test question") (contains "Functional test answer"))})) (fact "Can add a writer note to an answer" (try (-> ".func--dashboard-writer-note-item-field" (wd/input-text "Functional test writer note on answer") wd/submit) (wait-for-title "Writer dashboard | Objective[8]") (screenshot "questions_dashboard_with_writer_note") (wd/text ".func--writer-note-text") (catch Exception e (screenshot "ERROR-can-add-a-writer-note-to-an-answer") (throw e))) => "Functional test writer note on answer") (fact "Can view comments dashboard" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--writer-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (wd/click ".func--comment-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "comments_dashboard") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-can-view-comments-dashboard") (throw e))) => (contains {:page-title "Writer dashboard | Objective[8]" :page-source (contains "Functional test comment text")})) (fact "Can add a writer note to a comment" (try (-> ".func--dashboard-writer-note-item-field" (wd/input-text "Functional test writer note on comment") wd/submit) (wait-for-title "Writer dashboard | Objective[8]") (screenshot "comment_dashboard_with_writer_note") (wd/text ".func--writer-note-text") (catch Exception e (screenshot "ERROR-can-add-a-writer-note-to-an-comment") (throw e))) => "Functional test writer note on comment") (fact "Can view writer note on objective comment" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "writer_note_on_objective_comment") (wd/page-source) (catch Exception e (screenshot "ERROR-can-view-writer-note-on-objective-comment") (throw e))) => (contains "Functional test writer note on comment")) (fact "Can view annotations dashboard" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--writer-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (wd/click ".func--annotation-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "annotations_dashboard") {:page-title (wd/title) :page-source (wd/page-source) :annotation-count (wd/text ".func--item-count")} (catch Exception e (screenshot "ERROR-can-view-annotations-dashboard") (throw e))) => (contains {:page-title "Writer dashboard | Objective[8]" :page-source (contains "my draft section annotation") :annotation-count (contains "1")})) (fact "Can add a writer note to an annotation" (try (-> ".func--dashboard-writer-note-item-field" (wd/input-text "Functional test writer note on annotation") wd/submit) (wait-for-title "Writer dashboard | Objective[8]") (screenshot "annotation_dashboard_with_writer_note") (wd/text ".func--writer-note-text") (catch Exception e (screenshot "ERROR-can-add-a-writer-note-to-an-annotation") (throw e))) => "Functional test writer note on annotation") (fact "Annotation writer note appears alongside the annotation" (try (wd/to (str (:draft-url @journey-state) "/sections/" (:section-label @journey-state))) (wait-for-title "Draft section | Objective[8]") (screenshot "draft_section_with_annotation_with_writer_note") (wd/page-source) (catch Exception e (screenshot "ERROR-annotation-writer-note-appears-alongside-the-annotation") (throw e))) => (contains "Functional test writer note on annotation")) (fact "User with admin credentials can promote and demote an objective" (let [result (try (wd/click ".func--objectives") (wait-for-title "Objectives | Objective[8]") (screenshot "admins_objectives_page") (check-not-present ".clj-promoted-objectives-container") (wd/click ".func--toggle-promoted-objective-button") (wait-for-title "Objectives | Objective[8]") (wait-for-element ".func--promoted-objectives-container") (screenshot "promoted-objectives-list-page") (wd/click ".func--toggle-promoted-objective-button") (wait-for-title "Objectives | Objective[8]") (screenshot "demoted-objectives-list-page") (check-not-present ".clj-promoted-objectives-container") {:page-title (wd/title) :content (wd/page-source)} (catch Exception e (screenshot "ERROR-User-with-admin-credentials-can-promote-and-demote-an-objective") (throw e)))] (:page-title result) => "Objectives | Objective[8]")) (fact "Admin can delete a comment on an objective" (let [result (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_comments_to_remove") (wd/click ".func--remove-comment") (wait-for-title "Are you sure? | Objective[8]") (screenshot "objective_comment_removal_confirmation_page") (wd/click ".func--confirm-removal") (screenshot "objective_with_one_comment_removed") (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--remove-comment") (wait-for-title "Are you sure? | Objective[8]") (screenshot "another_objective_comment_removal_confirmation_page") (wd/click ".func--confirm-removal") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_with_both_comments_removed") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-can-remove-comments") (throw e)))] (:content result) =not=> (contains "Functional test comment text"))) (future-fact "Admin can delete a comment on a draft" (let [result (try (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (screenshot "draft_with_comment_to_remove") (wd/click ".func--remove-comment") (wait-for-title "Are you sure? | Objective[8]") (screenshot "objective_comment_removal_confirmation_page") (wd/click ".func--confirm-removal") (screenshot "draft_with_one_comment_removed") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-Can-comment-on-a-draft") (throw e)))] (:content result =not=> (contains "my draft section annotation")))) (fact "User with admin credentials can remove an objective" (let [result (try (wd/click ".func--objectives") (wait-for-title "Objectives | Objective[8]") (wd/click ".func--remove-objective") (wait-for-title "Are you sure? | Objective[8]") (screenshot "admin_removal_confirmation_page") (wd/click ".func--confirm-removal") (wait-for-title "Objectives | Objective[8]") (screenshot "objectives_page_after_removing_the_only_objective") {:page-title (wd/title) :content (wd/page-source)} (catch Exception e (screenshot "ERROR-User-with-admin-credentials-can-remove-objective") (throw e)))] (:page-title result) => "Objectives | Objective[8]" (:content result) =not=> (contains "Functional test headline"))) (fact "Can view the removed objective on the admin-activity page" (let [objective-id (-> (:objective-url @journey-state) (string/split #"/") last) objective-uri (str "/objectives/" objective-id)] (try (wd/click ".func--admin-link") (wait-for-title "Admin activity | Objective[8]") (screenshot "admin_activity_page") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-view-the-removed-objective-on-the-admin-activity-page") (throw e))) => (contains objective-uri))))
12753
(ns objective8.functional.functional-tests (:require [midje.sweet :refer :all] [org.httpkit.server :refer [run-server]] [clj-webdriver.taxi :as wd] [clojure.java.io :as io] [clojure.tools.logging :as log] [clojure.string :as string] [objective8.core :as core] [objective8.back-end.domain.users :as users] [objective8.integration.integration-helpers :as integration-helpers] [dev-helpers.stub-twitter-and-stonecutter :refer :all] [objective8.front-end.templates.sign-in :as sign-in])) (def config-without-twitter-or-stonecutter (assoc core/app-config :authentication stub-twitter-and-stonecutter-auth-config)) (defn wait-for-title [title] (try (wd/wait-until #(= (wd/title) title) 5000) (catch Exception e (log/info (str ">>>>>>>>>>> Title never appeared:")) (log/info (str "Expected: " title)) (log/info (str "Actual: " (wd/title))) (throw e)))) (def not-empty? (comp not empty?)) (defn wait-for-element [q] (try (wd/wait-until #(not-empty? (wd/elements q)) 5000) (catch Exception e (log/info (str "Could not find element: " q)) (throw e)))) (defn wait-for [pred] (try (wd/wait-until pred 5000) (catch Exception e (log/info (str "Waiting for predicate failed")) (throw e)))) (defn check-not-present [element] (if (try (wd/present? element) false (catch Exception e true)) true (do (throw (Throwable. (str "Element " element " was found that should not be present"))) false))) (def screenshot-directory "test/objective8/functional/screenshots") (def screenshot-number (atom 0)) (defn screenshot [filename] (log/info (str "Screenshot: " filename)) (wd/take-screenshot :file (str screenshot-directory "/" (format "%02d" (swap! screenshot-number + 1)) "_" filename ".png"))) (defn clear-screenshots [] (doall (->> (io/file screenshot-directory) file-seq (filter #(re-matches #".*\.png$" (.getName %))) (map io/delete-file)))) (def journey-state (atom nil)) (def test-data-collector (atom {})) (def objective-description "Functional test description with lots of hipster-ipsum: Master cleanse squid nulla, ugh kitsch biodiesel cronut food truck. Nostrud Schlitz tempor farm-to-table skateboard, wayfarers adipisicing Pitchfork sunt Neutra brunch four dollar toast forage placeat. Fugiat lo-fi sed polaroid Portland et tofu Austin. Blue Bottle labore forage, in bitters incididunt ugh delectus seitan flannel. Mixtape migas cardigan, quis American Apparel culpa aliquip cupidatat et nisi scenester. Labore sriracha Etsy flannel XOXO. Normcore selvage do vero keytar synth.") (def FIRST_DRAFT_MARKDOWN "First draft heading\n===\n\n- Some content") (def SECOND_DRAFT_MARKDOWN "Second draft heading\n===\n\n- Some content\n- Some more content") (def THIRD_DRAFT_MARKDOWN "Third draft heading\n===\n\n- Some content\n- Some more content\n- Another line of content") (def ADMIN_AND_WRITER_STONECUTTER_ID "d-cent-123123") (def OBJECTIVE_OWNER_TWITTER_ID "twitter-789789") (against-background [(sign-in/twitter-credentials-present?) => true (sign-in/stonecutter-credentials-present?) => true (before :contents (do (integration-helpers/db-connection) (integration-helpers/truncate-tables) (core/start-server config-without-twitter-or-stonecutter) (wd/set-driver! {:browser :firefox}) (users/store-admin! {:auth-provider-user-id ADMIN_AND_WRITER_STONECUTTER_ID}) (reset! journey-state {}) (clear-screenshots))) (before :facts (reset! test-data-collector {})) (after :contents (do (wd/quit) (integration-helpers/truncate-tables) (core/stop-back-end-server) (core/stop-front-end-server)))] (fact "can add an objective" (try (reset! twitter-id OBJECTIVE_OWNER_TWITTER_ID) (wd/to "localhost:8080") (wait-for-title "Objective[8]") (screenshot "home_page") (wd/click "a[href='/objectives']") (wait-for-title "Objectives | Objective[8]") (screenshot "objectives_page") (wd/click "a[href='/objectives/create']") (wait-for-title "Sign in or Sign up | Objective[8]") (screenshot "sign_in_page") (wd/click ".func--sign-in-with-twitter") (wait-for-title "Sign up | Objective[8]") (screenshot "sign_up_almost_there") (wd/input-text "#username" "funcTestUser123") (-> "#email-address" (wd/input-text "<EMAIL>") wd/submit) (screenshot "create_objective_page") (wait-for-title "Create an Objective | Objective[8]") (-> (wd/input-text ".func--input-objective-title" "F") (wd/submit)) (wait-for-element ".func--objective-title-error") (screenshot "create_objective_invalid_title") (wd/input-text ".func--input-objective-title" "unctional test headline") (-> ".func--input-objective-background" (wd/input-text objective-description) wd/submit) (wait-for-title "Functional test headline | Objective[8]") (swap! journey-state assoc :objective-url (wd/current-url)) (screenshot "objective_page") {:page-title (wd/title) :modal-text (wd/text ".func--share-objective-modal-text") :writer-name (wd/text ".func--writer-name")} (catch Exception e (screenshot "ERROR-Can-add-an-objective") (throw e))) => (contains {:page-title "Functional test headline | Objective[8]" :modal-text "Functional test headline" :writer-name "funcTestUser123"})) (fact "user cannot see empty promoted objectives container" (try (wd/click "a[href='/objectives']") (wait-for-title "Objectives | Objective[8]") (check-not-present ".clj-promoted-objectives-container") (catch Exception e (screenshot "ERROR-Cannot-see-empty-promoted-objectives") (throw e)))) (fact "Can star an objective" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--objective-star") (wd/to "/") (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_with_starred_objective") (wd/attribute ".func--objective-star" :class) (catch Exception e (screenshot "ERROR-Can-star-an-objective") (throw e))) => (contains "starred")) (fact "Can comment on an objective" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/input-text ".func--comment-form-text-area" "Functional test comment text") (wd/click ".func--comment-form-submit") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_comment") (wait-for-title "Functional test headline | Objective[8]") (wd/input-text ".func--comment-form-text-area" "Functional test second comment text") (wd/click ".func--comment-form-submit") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_two_comments") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-comment-on-an-objective") (throw e))) => (contains "Functional test comment text")) (fact "Can view and navigate comment history for an objective" (try (wd/to (str (:objective-url @journey-state) "/comments?offset=1")) (wait-for-title "Comments for Functional test headline | Objective[8]") (screenshot "objective_comment_history_offset_1") (swap! test-data-collector assoc :offset-equals-1-comment-count (count (wd/elements ".func--comment-text"))) (wd/click ".func--previous-link") (wait-for-title "Comments for Functional test headline | Objective[8]") (screenshot "objective_comment_history_offset_0") (swap! test-data-collector assoc :offset-equals-0-comment-count (count (wd/elements ".func--comment-text"))) @test-data-collector (catch Exception e (screenshot "ERROR-Can-view-comment-history-for-an-objective") (throw e))) ) => {:offset-equals-1-comment-count 1 :offset-equals-0-comment-count 2} (fact "Can add a question" (try (wd/to "localhost:8080/objectives") (wait-for-title "Objectives | Objective[8]") (screenshot "objectives_page_with_an_objective") (wd/click ".func--objective-list-item-link") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page") (wd/click ".func--add-question") (wait-for-element ".func--question-textarea") (screenshot "add_question_page") (-> ".func--question-textarea" (wd/input-text "Functional test question") (wd/submit)) (wait-for-element ".func--add-question") (screenshot "objective_page_with_question") {:modal-text (wd/text ".func--share-question-modal-text")} (catch Exception e (screenshot "Error-Can-add-questions") (throw e))) => {:modal-text "Functional test question"}) (fact "Objective owner can promote and demote questions" (try (wd/to (:objective-url @journey-state)) (wait-for-element ".func--demote-question") (wd/click ".func--demote-question") (wait-for-element ".func--promote-question") (screenshot "demoted_question") (wait-for-element ".func--promote-question") (wd/click ".func--promote-question") (screenshot "promoted_question") (catch Exception e (screenshot "Error-Objective-owner-can-promote-and-demote-questions") (throw e)))) (fact "Can answer a question" (try (wd/to (:objective-url @journey-state)) (wait-for-element ".func--answer-link") (wd/click ".func--answer-link") (wait-for-element ".func--add-answer") (-> ".func--add-answer" (wd/input-text "Functional test answer") (wd/submit)) (wait-for-element ".func--answer-text") (screenshot "answered_question") (swap! journey-state assoc :question-url (wd/current-url)) (wd/text ".func--answer-text") (catch Exception e (screenshot "Error-Can-answer-questions") (throw e))) => "Functional test answer") (fact "Can up vote an answer" (try (wd/to (:question-url @journey-state)) (wait-for-element "textarea.func--add-answer") (wd/text ".func--up-score") => "0" (wd/click "button.func--up-vote") (wait-for-element "textarea.func--add-answer") (wd/text ".func--up-score") => "1" (catch Exception e (screenshot "Error-Can-vote-on-an-answer") (throw e)))) (fact "Can invite a writer" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page") (wd/click ".func--invite-writer") (wait-for-element ".func--invite-writer") (screenshot "invite_writer_page") (wd/input-text ".func--writer-name" "Invitee name") (wd/input-text ".func--writer-email" "<EMAIL>") (-> ".func--writer-reason" (wd/input-text "Functional test invitation reason") wd/submit) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_invitation_flash") (->> (wd/value ".func--invitation-url") (re-find #"http://.*$") (swap! journey-state assoc :invitation-url)) {:page-title (wd/title) :flash-message (wd/text ".func--invitation-guidance")} (catch Exception e (screenshot "ERROR-Can-invite-a-writer") (throw e))) => (contains {:page-title "Functional test headline | Objective[8]" :flash-message (contains "Your writer's invitation")})) (fact "Can accept a writer invitation" (try (reset! stonecutter-id ADMIN_AND_WRITER_STONECUTTER_ID) (wd/click ".func--masthead-sign-out") (screenshot "after_sign_out") (wd/to (:invitation-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_after_hitting_invitation_url") (wd/click ".func--sign-in-to-accept") (wait-for-title "Sign in or Sign up | Objective[8]") (wd/click ".func--sign-in-with-d-cent") (wait-for-title "Sign up | Objective[8]") (-> "#username" (wd/input-text "funcTestWriter") wd/submit) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_after_signing_up") (wd/click ".func--invitation-accept") (wait-for-title "Create profile | Objective[8]") (screenshot "create_profile_page") (wd/input-text ".func--name" "Invited writer real name") (-> ".func--biog" (wd/input-text "Biography with lots of text...") wd/submit) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_from_recently_added_writer") (wd/text (second (wd/elements ".func--writer-name"))) (catch Exception e (screenshot "ERROR-Can-accept-a-writer-invitation") (throw e))) => "Invited writer real name") (fact "Can view writer profile page" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click (second (wd/elements ".func--writer-name"))) (wait-for-title "Invited writer real name | Objective[8]") (screenshot "writer_profile_page") {:biog-text (wd/text (first (wd/elements ".func--writer-biog"))) :objective-title (wd/text (first (wd/elements ".func--objective-title")))} (catch Exception e (screenshot "ERROR-can-view-writer-profile") (throw e))) => {:biog-text "Biography with lots of text..." :objective-title "Functional test headline"}) (fact "Can edit writer profile" (try (wd/click ".func--edit-profile") (wait-for-title "Edit profile | Objective[8]") (screenshot "edit_profile_page") (-> ".func--name" wd/clear (wd/input-text "My new real name")) (-> ".func--biog" wd/clear (wd/input-text "My new biography") wd/submit) (wait-for-title "My new real name | Objective[8]") (screenshot "updated_profile_page") {:name (wd/text (first (wd/elements ".func--writer-name"))) :biog (wd/text (first (wd/elements ".func--writer-biog")))} (catch Exception e (screenshot "ERROR-can-edit-writer-profile") (throw e))) => (contains {:biog "My new biography"})) (fact "Can access dashboard from profile page" (try (wd/click ".func--dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "writer_dashboard_from_profile_page") (wd/current-url) (catch Exception e (screenshot "ERROR-can-access-dashboard-from-profile-page") (throw e))) => (contains (str (:objective-url @journey-state) "/dashboard/questions"))) (fact "Can submit a draft" (try (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (screenshot "drafts_list_no_drafts") (wd/click ".func--add-a-draft") (wait-for-title "Add draft | Objective[8]") (screenshot "add_draft_empty") (wd/input-text ".func--add-draft-content" FIRST_DRAFT_MARKDOWN) (wd/click ".func--preview-action") (wait-for-title "Add draft | Objective[8]") (screenshot "preview_draft") (wd/click ".func--submit-action") (wait-for-title "Policy draft | Objective[8]") (screenshot "submitted_draft") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-Can-submit-a-draft") (throw e))) => (contains {:page-title "Policy draft | Objective[8]" :page-source (contains "First draft heading")})) (fact "Can view latest draft" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_a_draft") (wd/click ".func--drafting-message-link") (wait-for-title "Drafts | Objective[8]") (screenshot "drafts_list_with_one_draft") (wd/click ".func--latest-draft-link") (wait-for-title "Policy draft | Objective[8]") (screenshot "latest_draft") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-Can-view-latest-draft") (throw e))) => (contains {:page-title "Policy draft | Objective[8]" :page-source (contains "First draft heading")})) (fact "Can comment on a draft" (try (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (wd/input-text ".func--comment-form-text-area" "Functional test comment text") (wd/click ".func--comment-form-submit") (wait-for-title "Policy draft | Objective[8]") (screenshot "draft_with_comment") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-comment-on-a-draft") (throw e))) => (contains "Functional test comment text")) (fact "Can down vote a comment on a draft" (try (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (wd/text ".func--down-score") => "0" (wd/click "button.func--down-vote") (wait-for-title "Policy draft | Objective[8]") (wd/text ".func--down-score") => "1" (catch Exception e (screenshot "ERROR-Can-vote-on-a-comment-on-a-draft") (throw e)))) (fact "Can navigate between drafts" (try (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (screenshot "list_of_drafts_with_one_draft") (wd/click ".func--add-a-draft") (wait-for-title "Add draft | Objective[8]") (wd/input-text ".func--add-draft-content" SECOND_DRAFT_MARKDOWN) (wd/click ".func--submit-action") (wait-for-title "Policy draft | Objective[8]") (screenshot "second_draft") (wd/click ".func--parent-link") (wait-for-title "Drafts | Objective[8]") (wd/click ".func--add-a-draft") (wait-for-title "Add draft | Objective[8]") (wd/input-text ".func--add-draft-content" THIRD_DRAFT_MARKDOWN) (wd/click ".func--submit-action") (wait-for-title "Policy draft | Objective[8]") (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (screenshot "list_of_drafts_with_three_drafts") (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (screenshot "latest_draft_with_previous_button") (wd/click ".func--previous-link") (wait-for-title "Policy draft | Objective[8]") (screenshot "second_draft_with_next") (wd/click ".func--next-link") (wait-for-title "Policy draft | Objective[8]") (screenshot "third_draft") (swap! journey-state assoc :draft-url (wd/current-url)) (swap! journey-state assoc :section-label (wd/attribute "h1" :data-section-label)) (wd/page-source) (catch Exception e (screenshot "ERROR-Can-navigate-between-drafts") (throw e))) => (contains "Third draft heading")) (fact "Can view draft diffs" (try (wd/click ".func--what-changed") (wait-for-title "Draft changes | Objective[8]") (screenshot "draft_diff") (catch Exception e (screenshot "ERROR-Can-view-draft-diffs") (throw e)))) (fact "Can view draft section" (try (wd/click ".func--back-to-draft") (wait-for-title "Policy draft | Objective[8]") (wd/click ".func--annotation-link") (wait-for-title "Draft section | Objective[8]") (screenshot "draft_section") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-view-draft-section") (throw e))) => (contains "Third draft heading")) (fact "Can annotate a draft section" (try (wd/input-text ".func--comment-form-text-area" "my draft section annotation") (wd/click ".func--comment-reason-select") (wd/click ".func--comment-form-submit") (wait-for-title "Draft section | Objective[8]") (screenshot "draft_section_with_comment") {:annotation (wd/text ".func--comment-text") :annotation-reason (wd/text ".func--comment-reason-text")} (catch Exception e (screenshot "ERROR-Can-annotate-a-draft-section") (throw e))) => {:annotation "my draft section annotation" :annotation-reason "Section is difficult to understand"}) (fact "Can view number of annotations on a section" (try (wd/click ".func--back-to-draft") (wait-for-title "Policy draft | Objective[8]") (screenshot "draft_with_one_annotation") (wd/text ".func--annotation-count") (catch Exception e (screenshot "ERROR-Can-view-number-of-annotations-on-a-section") (throw e))) => "1") (fact "Can navigate to import from Google Drive" (try (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (wd/click ".func--import-draft-link") (wait-for-title "Import draft | Objective[8]") (screenshot "import_draft") (wd/click ".func--cancel-link") (wait-for-title "Drafts | Objective[8]") (screenshot "draft_list") (catch Exception e (screenshot "ERROR-Can-navigate-to-import-from-Google-Drive") (throw e)))) (fact "Can view questions dashboard" (try (wd/to "localhost:8080/users/funcTestUser123") (wait-for-title "funcTestUser123 | Objective[8]") (screenshot "objectives_list_as_a_writer_with_an_objective") (wd/click ".func--dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "questions_dashboard") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-can-view-questions-dashboard") (throw e))) => (contains {:page-title "Writer dashboard | Objective[8]" :page-source (every-checker (contains "Functional test question") (contains "Functional test answer"))})) (fact "Can add a writer note to an answer" (try (-> ".func--dashboard-writer-note-item-field" (wd/input-text "Functional test writer note on answer") wd/submit) (wait-for-title "Writer dashboard | Objective[8]") (screenshot "questions_dashboard_with_writer_note") (wd/text ".func--writer-note-text") (catch Exception e (screenshot "ERROR-can-add-a-writer-note-to-an-answer") (throw e))) => "Functional test writer note on answer") (fact "Can view comments dashboard" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--writer-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (wd/click ".func--comment-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "comments_dashboard") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-can-view-comments-dashboard") (throw e))) => (contains {:page-title "Writer dashboard | Objective[8]" :page-source (contains "Functional test comment text")})) (fact "Can add a writer note to a comment" (try (-> ".func--dashboard-writer-note-item-field" (wd/input-text "Functional test writer note on comment") wd/submit) (wait-for-title "Writer dashboard | Objective[8]") (screenshot "comment_dashboard_with_writer_note") (wd/text ".func--writer-note-text") (catch Exception e (screenshot "ERROR-can-add-a-writer-note-to-an-comment") (throw e))) => "Functional test writer note on comment") (fact "Can view writer note on objective comment" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "writer_note_on_objective_comment") (wd/page-source) (catch Exception e (screenshot "ERROR-can-view-writer-note-on-objective-comment") (throw e))) => (contains "Functional test writer note on comment")) (fact "Can view annotations dashboard" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--writer-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (wd/click ".func--annotation-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "annotations_dashboard") {:page-title (wd/title) :page-source (wd/page-source) :annotation-count (wd/text ".func--item-count")} (catch Exception e (screenshot "ERROR-can-view-annotations-dashboard") (throw e))) => (contains {:page-title "Writer dashboard | Objective[8]" :page-source (contains "my draft section annotation") :annotation-count (contains "1")})) (fact "Can add a writer note to an annotation" (try (-> ".func--dashboard-writer-note-item-field" (wd/input-text "Functional test writer note on annotation") wd/submit) (wait-for-title "Writer dashboard | Objective[8]") (screenshot "annotation_dashboard_with_writer_note") (wd/text ".func--writer-note-text") (catch Exception e (screenshot "ERROR-can-add-a-writer-note-to-an-annotation") (throw e))) => "Functional test writer note on annotation") (fact "Annotation writer note appears alongside the annotation" (try (wd/to (str (:draft-url @journey-state) "/sections/" (:section-label @journey-state))) (wait-for-title "Draft section | Objective[8]") (screenshot "draft_section_with_annotation_with_writer_note") (wd/page-source) (catch Exception e (screenshot "ERROR-annotation-writer-note-appears-alongside-the-annotation") (throw e))) => (contains "Functional test writer note on annotation")) (fact "User with admin credentials can promote and demote an objective" (let [result (try (wd/click ".func--objectives") (wait-for-title "Objectives | Objective[8]") (screenshot "admins_objectives_page") (check-not-present ".clj-promoted-objectives-container") (wd/click ".func--toggle-promoted-objective-button") (wait-for-title "Objectives | Objective[8]") (wait-for-element ".func--promoted-objectives-container") (screenshot "promoted-objectives-list-page") (wd/click ".func--toggle-promoted-objective-button") (wait-for-title "Objectives | Objective[8]") (screenshot "demoted-objectives-list-page") (check-not-present ".clj-promoted-objectives-container") {:page-title (wd/title) :content (wd/page-source)} (catch Exception e (screenshot "ERROR-User-with-admin-credentials-can-promote-and-demote-an-objective") (throw e)))] (:page-title result) => "Objectives | Objective[8]")) (fact "Admin can delete a comment on an objective" (let [result (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_comments_to_remove") (wd/click ".func--remove-comment") (wait-for-title "Are you sure? | Objective[8]") (screenshot "objective_comment_removal_confirmation_page") (wd/click ".func--confirm-removal") (screenshot "objective_with_one_comment_removed") (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--remove-comment") (wait-for-title "Are you sure? | Objective[8]") (screenshot "another_objective_comment_removal_confirmation_page") (wd/click ".func--confirm-removal") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_with_both_comments_removed") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-can-remove-comments") (throw e)))] (:content result) =not=> (contains "Functional test comment text"))) (future-fact "Admin can delete a comment on a draft" (let [result (try (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (screenshot "draft_with_comment_to_remove") (wd/click ".func--remove-comment") (wait-for-title "Are you sure? | Objective[8]") (screenshot "objective_comment_removal_confirmation_page") (wd/click ".func--confirm-removal") (screenshot "draft_with_one_comment_removed") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-Can-comment-on-a-draft") (throw e)))] (:content result =not=> (contains "my draft section annotation")))) (fact "User with admin credentials can remove an objective" (let [result (try (wd/click ".func--objectives") (wait-for-title "Objectives | Objective[8]") (wd/click ".func--remove-objective") (wait-for-title "Are you sure? | Objective[8]") (screenshot "admin_removal_confirmation_page") (wd/click ".func--confirm-removal") (wait-for-title "Objectives | Objective[8]") (screenshot "objectives_page_after_removing_the_only_objective") {:page-title (wd/title) :content (wd/page-source)} (catch Exception e (screenshot "ERROR-User-with-admin-credentials-can-remove-objective") (throw e)))] (:page-title result) => "Objectives | Objective[8]" (:content result) =not=> (contains "Functional test headline"))) (fact "Can view the removed objective on the admin-activity page" (let [objective-id (-> (:objective-url @journey-state) (string/split #"/") last) objective-uri (str "/objectives/" objective-id)] (try (wd/click ".func--admin-link") (wait-for-title "Admin activity | Objective[8]") (screenshot "admin_activity_page") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-view-the-removed-objective-on-the-admin-activity-page") (throw e))) => (contains objective-uri))))
true
(ns objective8.functional.functional-tests (:require [midje.sweet :refer :all] [org.httpkit.server :refer [run-server]] [clj-webdriver.taxi :as wd] [clojure.java.io :as io] [clojure.tools.logging :as log] [clojure.string :as string] [objective8.core :as core] [objective8.back-end.domain.users :as users] [objective8.integration.integration-helpers :as integration-helpers] [dev-helpers.stub-twitter-and-stonecutter :refer :all] [objective8.front-end.templates.sign-in :as sign-in])) (def config-without-twitter-or-stonecutter (assoc core/app-config :authentication stub-twitter-and-stonecutter-auth-config)) (defn wait-for-title [title] (try (wd/wait-until #(= (wd/title) title) 5000) (catch Exception e (log/info (str ">>>>>>>>>>> Title never appeared:")) (log/info (str "Expected: " title)) (log/info (str "Actual: " (wd/title))) (throw e)))) (def not-empty? (comp not empty?)) (defn wait-for-element [q] (try (wd/wait-until #(not-empty? (wd/elements q)) 5000) (catch Exception e (log/info (str "Could not find element: " q)) (throw e)))) (defn wait-for [pred] (try (wd/wait-until pred 5000) (catch Exception e (log/info (str "Waiting for predicate failed")) (throw e)))) (defn check-not-present [element] (if (try (wd/present? element) false (catch Exception e true)) true (do (throw (Throwable. (str "Element " element " was found that should not be present"))) false))) (def screenshot-directory "test/objective8/functional/screenshots") (def screenshot-number (atom 0)) (defn screenshot [filename] (log/info (str "Screenshot: " filename)) (wd/take-screenshot :file (str screenshot-directory "/" (format "%02d" (swap! screenshot-number + 1)) "_" filename ".png"))) (defn clear-screenshots [] (doall (->> (io/file screenshot-directory) file-seq (filter #(re-matches #".*\.png$" (.getName %))) (map io/delete-file)))) (def journey-state (atom nil)) (def test-data-collector (atom {})) (def objective-description "Functional test description with lots of hipster-ipsum: Master cleanse squid nulla, ugh kitsch biodiesel cronut food truck. Nostrud Schlitz tempor farm-to-table skateboard, wayfarers adipisicing Pitchfork sunt Neutra brunch four dollar toast forage placeat. Fugiat lo-fi sed polaroid Portland et tofu Austin. Blue Bottle labore forage, in bitters incididunt ugh delectus seitan flannel. Mixtape migas cardigan, quis American Apparel culpa aliquip cupidatat et nisi scenester. Labore sriracha Etsy flannel XOXO. Normcore selvage do vero keytar synth.") (def FIRST_DRAFT_MARKDOWN "First draft heading\n===\n\n- Some content") (def SECOND_DRAFT_MARKDOWN "Second draft heading\n===\n\n- Some content\n- Some more content") (def THIRD_DRAFT_MARKDOWN "Third draft heading\n===\n\n- Some content\n- Some more content\n- Another line of content") (def ADMIN_AND_WRITER_STONECUTTER_ID "d-cent-123123") (def OBJECTIVE_OWNER_TWITTER_ID "twitter-789789") (against-background [(sign-in/twitter-credentials-present?) => true (sign-in/stonecutter-credentials-present?) => true (before :contents (do (integration-helpers/db-connection) (integration-helpers/truncate-tables) (core/start-server config-without-twitter-or-stonecutter) (wd/set-driver! {:browser :firefox}) (users/store-admin! {:auth-provider-user-id ADMIN_AND_WRITER_STONECUTTER_ID}) (reset! journey-state {}) (clear-screenshots))) (before :facts (reset! test-data-collector {})) (after :contents (do (wd/quit) (integration-helpers/truncate-tables) (core/stop-back-end-server) (core/stop-front-end-server)))] (fact "can add an objective" (try (reset! twitter-id OBJECTIVE_OWNER_TWITTER_ID) (wd/to "localhost:8080") (wait-for-title "Objective[8]") (screenshot "home_page") (wd/click "a[href='/objectives']") (wait-for-title "Objectives | Objective[8]") (screenshot "objectives_page") (wd/click "a[href='/objectives/create']") (wait-for-title "Sign in or Sign up | Objective[8]") (screenshot "sign_in_page") (wd/click ".func--sign-in-with-twitter") (wait-for-title "Sign up | Objective[8]") (screenshot "sign_up_almost_there") (wd/input-text "#username" "funcTestUser123") (-> "#email-address" (wd/input-text "PI:EMAIL:<EMAIL>END_PI") wd/submit) (screenshot "create_objective_page") (wait-for-title "Create an Objective | Objective[8]") (-> (wd/input-text ".func--input-objective-title" "F") (wd/submit)) (wait-for-element ".func--objective-title-error") (screenshot "create_objective_invalid_title") (wd/input-text ".func--input-objective-title" "unctional test headline") (-> ".func--input-objective-background" (wd/input-text objective-description) wd/submit) (wait-for-title "Functional test headline | Objective[8]") (swap! journey-state assoc :objective-url (wd/current-url)) (screenshot "objective_page") {:page-title (wd/title) :modal-text (wd/text ".func--share-objective-modal-text") :writer-name (wd/text ".func--writer-name")} (catch Exception e (screenshot "ERROR-Can-add-an-objective") (throw e))) => (contains {:page-title "Functional test headline | Objective[8]" :modal-text "Functional test headline" :writer-name "funcTestUser123"})) (fact "user cannot see empty promoted objectives container" (try (wd/click "a[href='/objectives']") (wait-for-title "Objectives | Objective[8]") (check-not-present ".clj-promoted-objectives-container") (catch Exception e (screenshot "ERROR-Cannot-see-empty-promoted-objectives") (throw e)))) (fact "Can star an objective" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--objective-star") (wd/to "/") (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_with_starred_objective") (wd/attribute ".func--objective-star" :class) (catch Exception e (screenshot "ERROR-Can-star-an-objective") (throw e))) => (contains "starred")) (fact "Can comment on an objective" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/input-text ".func--comment-form-text-area" "Functional test comment text") (wd/click ".func--comment-form-submit") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_comment") (wait-for-title "Functional test headline | Objective[8]") (wd/input-text ".func--comment-form-text-area" "Functional test second comment text") (wd/click ".func--comment-form-submit") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_two_comments") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-comment-on-an-objective") (throw e))) => (contains "Functional test comment text")) (fact "Can view and navigate comment history for an objective" (try (wd/to (str (:objective-url @journey-state) "/comments?offset=1")) (wait-for-title "Comments for Functional test headline | Objective[8]") (screenshot "objective_comment_history_offset_1") (swap! test-data-collector assoc :offset-equals-1-comment-count (count (wd/elements ".func--comment-text"))) (wd/click ".func--previous-link") (wait-for-title "Comments for Functional test headline | Objective[8]") (screenshot "objective_comment_history_offset_0") (swap! test-data-collector assoc :offset-equals-0-comment-count (count (wd/elements ".func--comment-text"))) @test-data-collector (catch Exception e (screenshot "ERROR-Can-view-comment-history-for-an-objective") (throw e))) ) => {:offset-equals-1-comment-count 1 :offset-equals-0-comment-count 2} (fact "Can add a question" (try (wd/to "localhost:8080/objectives") (wait-for-title "Objectives | Objective[8]") (screenshot "objectives_page_with_an_objective") (wd/click ".func--objective-list-item-link") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page") (wd/click ".func--add-question") (wait-for-element ".func--question-textarea") (screenshot "add_question_page") (-> ".func--question-textarea" (wd/input-text "Functional test question") (wd/submit)) (wait-for-element ".func--add-question") (screenshot "objective_page_with_question") {:modal-text (wd/text ".func--share-question-modal-text")} (catch Exception e (screenshot "Error-Can-add-questions") (throw e))) => {:modal-text "Functional test question"}) (fact "Objective owner can promote and demote questions" (try (wd/to (:objective-url @journey-state)) (wait-for-element ".func--demote-question") (wd/click ".func--demote-question") (wait-for-element ".func--promote-question") (screenshot "demoted_question") (wait-for-element ".func--promote-question") (wd/click ".func--promote-question") (screenshot "promoted_question") (catch Exception e (screenshot "Error-Objective-owner-can-promote-and-demote-questions") (throw e)))) (fact "Can answer a question" (try (wd/to (:objective-url @journey-state)) (wait-for-element ".func--answer-link") (wd/click ".func--answer-link") (wait-for-element ".func--add-answer") (-> ".func--add-answer" (wd/input-text "Functional test answer") (wd/submit)) (wait-for-element ".func--answer-text") (screenshot "answered_question") (swap! journey-state assoc :question-url (wd/current-url)) (wd/text ".func--answer-text") (catch Exception e (screenshot "Error-Can-answer-questions") (throw e))) => "Functional test answer") (fact "Can up vote an answer" (try (wd/to (:question-url @journey-state)) (wait-for-element "textarea.func--add-answer") (wd/text ".func--up-score") => "0" (wd/click "button.func--up-vote") (wait-for-element "textarea.func--add-answer") (wd/text ".func--up-score") => "1" (catch Exception e (screenshot "Error-Can-vote-on-an-answer") (throw e)))) (fact "Can invite a writer" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page") (wd/click ".func--invite-writer") (wait-for-element ".func--invite-writer") (screenshot "invite_writer_page") (wd/input-text ".func--writer-name" "Invitee name") (wd/input-text ".func--writer-email" "PI:EMAIL:<EMAIL>END_PI") (-> ".func--writer-reason" (wd/input-text "Functional test invitation reason") wd/submit) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_invitation_flash") (->> (wd/value ".func--invitation-url") (re-find #"http://.*$") (swap! journey-state assoc :invitation-url)) {:page-title (wd/title) :flash-message (wd/text ".func--invitation-guidance")} (catch Exception e (screenshot "ERROR-Can-invite-a-writer") (throw e))) => (contains {:page-title "Functional test headline | Objective[8]" :flash-message (contains "Your writer's invitation")})) (fact "Can accept a writer invitation" (try (reset! stonecutter-id ADMIN_AND_WRITER_STONECUTTER_ID) (wd/click ".func--masthead-sign-out") (screenshot "after_sign_out") (wd/to (:invitation-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_after_hitting_invitation_url") (wd/click ".func--sign-in-to-accept") (wait-for-title "Sign in or Sign up | Objective[8]") (wd/click ".func--sign-in-with-d-cent") (wait-for-title "Sign up | Objective[8]") (-> "#username" (wd/input-text "funcTestWriter") wd/submit) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_after_signing_up") (wd/click ".func--invitation-accept") (wait-for-title "Create profile | Objective[8]") (screenshot "create_profile_page") (wd/input-text ".func--name" "Invited writer real name") (-> ".func--biog" (wd/input-text "Biography with lots of text...") wd/submit) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_from_recently_added_writer") (wd/text (second (wd/elements ".func--writer-name"))) (catch Exception e (screenshot "ERROR-Can-accept-a-writer-invitation") (throw e))) => "Invited writer real name") (fact "Can view writer profile page" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click (second (wd/elements ".func--writer-name"))) (wait-for-title "Invited writer real name | Objective[8]") (screenshot "writer_profile_page") {:biog-text (wd/text (first (wd/elements ".func--writer-biog"))) :objective-title (wd/text (first (wd/elements ".func--objective-title")))} (catch Exception e (screenshot "ERROR-can-view-writer-profile") (throw e))) => {:biog-text "Biography with lots of text..." :objective-title "Functional test headline"}) (fact "Can edit writer profile" (try (wd/click ".func--edit-profile") (wait-for-title "Edit profile | Objective[8]") (screenshot "edit_profile_page") (-> ".func--name" wd/clear (wd/input-text "My new real name")) (-> ".func--biog" wd/clear (wd/input-text "My new biography") wd/submit) (wait-for-title "My new real name | Objective[8]") (screenshot "updated_profile_page") {:name (wd/text (first (wd/elements ".func--writer-name"))) :biog (wd/text (first (wd/elements ".func--writer-biog")))} (catch Exception e (screenshot "ERROR-can-edit-writer-profile") (throw e))) => (contains {:biog "My new biography"})) (fact "Can access dashboard from profile page" (try (wd/click ".func--dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "writer_dashboard_from_profile_page") (wd/current-url) (catch Exception e (screenshot "ERROR-can-access-dashboard-from-profile-page") (throw e))) => (contains (str (:objective-url @journey-state) "/dashboard/questions"))) (fact "Can submit a draft" (try (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (screenshot "drafts_list_no_drafts") (wd/click ".func--add-a-draft") (wait-for-title "Add draft | Objective[8]") (screenshot "add_draft_empty") (wd/input-text ".func--add-draft-content" FIRST_DRAFT_MARKDOWN) (wd/click ".func--preview-action") (wait-for-title "Add draft | Objective[8]") (screenshot "preview_draft") (wd/click ".func--submit-action") (wait-for-title "Policy draft | Objective[8]") (screenshot "submitted_draft") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-Can-submit-a-draft") (throw e))) => (contains {:page-title "Policy draft | Objective[8]" :page-source (contains "First draft heading")})) (fact "Can view latest draft" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_a_draft") (wd/click ".func--drafting-message-link") (wait-for-title "Drafts | Objective[8]") (screenshot "drafts_list_with_one_draft") (wd/click ".func--latest-draft-link") (wait-for-title "Policy draft | Objective[8]") (screenshot "latest_draft") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-Can-view-latest-draft") (throw e))) => (contains {:page-title "Policy draft | Objective[8]" :page-source (contains "First draft heading")})) (fact "Can comment on a draft" (try (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (wd/input-text ".func--comment-form-text-area" "Functional test comment text") (wd/click ".func--comment-form-submit") (wait-for-title "Policy draft | Objective[8]") (screenshot "draft_with_comment") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-comment-on-a-draft") (throw e))) => (contains "Functional test comment text")) (fact "Can down vote a comment on a draft" (try (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (wd/text ".func--down-score") => "0" (wd/click "button.func--down-vote") (wait-for-title "Policy draft | Objective[8]") (wd/text ".func--down-score") => "1" (catch Exception e (screenshot "ERROR-Can-vote-on-a-comment-on-a-draft") (throw e)))) (fact "Can navigate between drafts" (try (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (screenshot "list_of_drafts_with_one_draft") (wd/click ".func--add-a-draft") (wait-for-title "Add draft | Objective[8]") (wd/input-text ".func--add-draft-content" SECOND_DRAFT_MARKDOWN) (wd/click ".func--submit-action") (wait-for-title "Policy draft | Objective[8]") (screenshot "second_draft") (wd/click ".func--parent-link") (wait-for-title "Drafts | Objective[8]") (wd/click ".func--add-a-draft") (wait-for-title "Add draft | Objective[8]") (wd/input-text ".func--add-draft-content" THIRD_DRAFT_MARKDOWN) (wd/click ".func--submit-action") (wait-for-title "Policy draft | Objective[8]") (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (screenshot "list_of_drafts_with_three_drafts") (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (screenshot "latest_draft_with_previous_button") (wd/click ".func--previous-link") (wait-for-title "Policy draft | Objective[8]") (screenshot "second_draft_with_next") (wd/click ".func--next-link") (wait-for-title "Policy draft | Objective[8]") (screenshot "third_draft") (swap! journey-state assoc :draft-url (wd/current-url)) (swap! journey-state assoc :section-label (wd/attribute "h1" :data-section-label)) (wd/page-source) (catch Exception e (screenshot "ERROR-Can-navigate-between-drafts") (throw e))) => (contains "Third draft heading")) (fact "Can view draft diffs" (try (wd/click ".func--what-changed") (wait-for-title "Draft changes | Objective[8]") (screenshot "draft_diff") (catch Exception e (screenshot "ERROR-Can-view-draft-diffs") (throw e)))) (fact "Can view draft section" (try (wd/click ".func--back-to-draft") (wait-for-title "Policy draft | Objective[8]") (wd/click ".func--annotation-link") (wait-for-title "Draft section | Objective[8]") (screenshot "draft_section") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-view-draft-section") (throw e))) => (contains "Third draft heading")) (fact "Can annotate a draft section" (try (wd/input-text ".func--comment-form-text-area" "my draft section annotation") (wd/click ".func--comment-reason-select") (wd/click ".func--comment-form-submit") (wait-for-title "Draft section | Objective[8]") (screenshot "draft_section_with_comment") {:annotation (wd/text ".func--comment-text") :annotation-reason (wd/text ".func--comment-reason-text")} (catch Exception e (screenshot "ERROR-Can-annotate-a-draft-section") (throw e))) => {:annotation "my draft section annotation" :annotation-reason "Section is difficult to understand"}) (fact "Can view number of annotations on a section" (try (wd/click ".func--back-to-draft") (wait-for-title "Policy draft | Objective[8]") (screenshot "draft_with_one_annotation") (wd/text ".func--annotation-count") (catch Exception e (screenshot "ERROR-Can-view-number-of-annotations-on-a-section") (throw e))) => "1") (fact "Can navigate to import from Google Drive" (try (wd/to (str (:objective-url @journey-state) "/drafts")) (wait-for-title "Drafts | Objective[8]") (wd/click ".func--import-draft-link") (wait-for-title "Import draft | Objective[8]") (screenshot "import_draft") (wd/click ".func--cancel-link") (wait-for-title "Drafts | Objective[8]") (screenshot "draft_list") (catch Exception e (screenshot "ERROR-Can-navigate-to-import-from-Google-Drive") (throw e)))) (fact "Can view questions dashboard" (try (wd/to "localhost:8080/users/funcTestUser123") (wait-for-title "funcTestUser123 | Objective[8]") (screenshot "objectives_list_as_a_writer_with_an_objective") (wd/click ".func--dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "questions_dashboard") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-can-view-questions-dashboard") (throw e))) => (contains {:page-title "Writer dashboard | Objective[8]" :page-source (every-checker (contains "Functional test question") (contains "Functional test answer"))})) (fact "Can add a writer note to an answer" (try (-> ".func--dashboard-writer-note-item-field" (wd/input-text "Functional test writer note on answer") wd/submit) (wait-for-title "Writer dashboard | Objective[8]") (screenshot "questions_dashboard_with_writer_note") (wd/text ".func--writer-note-text") (catch Exception e (screenshot "ERROR-can-add-a-writer-note-to-an-answer") (throw e))) => "Functional test writer note on answer") (fact "Can view comments dashboard" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--writer-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (wd/click ".func--comment-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "comments_dashboard") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-can-view-comments-dashboard") (throw e))) => (contains {:page-title "Writer dashboard | Objective[8]" :page-source (contains "Functional test comment text")})) (fact "Can add a writer note to a comment" (try (-> ".func--dashboard-writer-note-item-field" (wd/input-text "Functional test writer note on comment") wd/submit) (wait-for-title "Writer dashboard | Objective[8]") (screenshot "comment_dashboard_with_writer_note") (wd/text ".func--writer-note-text") (catch Exception e (screenshot "ERROR-can-add-a-writer-note-to-an-comment") (throw e))) => "Functional test writer note on comment") (fact "Can view writer note on objective comment" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "writer_note_on_objective_comment") (wd/page-source) (catch Exception e (screenshot "ERROR-can-view-writer-note-on-objective-comment") (throw e))) => (contains "Functional test writer note on comment")) (fact "Can view annotations dashboard" (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--writer-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (wd/click ".func--annotation-dashboard-link") (wait-for-title "Writer dashboard | Objective[8]") (screenshot "annotations_dashboard") {:page-title (wd/title) :page-source (wd/page-source) :annotation-count (wd/text ".func--item-count")} (catch Exception e (screenshot "ERROR-can-view-annotations-dashboard") (throw e))) => (contains {:page-title "Writer dashboard | Objective[8]" :page-source (contains "my draft section annotation") :annotation-count (contains "1")})) (fact "Can add a writer note to an annotation" (try (-> ".func--dashboard-writer-note-item-field" (wd/input-text "Functional test writer note on annotation") wd/submit) (wait-for-title "Writer dashboard | Objective[8]") (screenshot "annotation_dashboard_with_writer_note") (wd/text ".func--writer-note-text") (catch Exception e (screenshot "ERROR-can-add-a-writer-note-to-an-annotation") (throw e))) => "Functional test writer note on annotation") (fact "Annotation writer note appears alongside the annotation" (try (wd/to (str (:draft-url @journey-state) "/sections/" (:section-label @journey-state))) (wait-for-title "Draft section | Objective[8]") (screenshot "draft_section_with_annotation_with_writer_note") (wd/page-source) (catch Exception e (screenshot "ERROR-annotation-writer-note-appears-alongside-the-annotation") (throw e))) => (contains "Functional test writer note on annotation")) (fact "User with admin credentials can promote and demote an objective" (let [result (try (wd/click ".func--objectives") (wait-for-title "Objectives | Objective[8]") (screenshot "admins_objectives_page") (check-not-present ".clj-promoted-objectives-container") (wd/click ".func--toggle-promoted-objective-button") (wait-for-title "Objectives | Objective[8]") (wait-for-element ".func--promoted-objectives-container") (screenshot "promoted-objectives-list-page") (wd/click ".func--toggle-promoted-objective-button") (wait-for-title "Objectives | Objective[8]") (screenshot "demoted-objectives-list-page") (check-not-present ".clj-promoted-objectives-container") {:page-title (wd/title) :content (wd/page-source)} (catch Exception e (screenshot "ERROR-User-with-admin-credentials-can-promote-and-demote-an-objective") (throw e)))] (:page-title result) => "Objectives | Objective[8]")) (fact "Admin can delete a comment on an objective" (let [result (try (wd/to (:objective-url @journey-state)) (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_with_comments_to_remove") (wd/click ".func--remove-comment") (wait-for-title "Are you sure? | Objective[8]") (screenshot "objective_comment_removal_confirmation_page") (wd/click ".func--confirm-removal") (screenshot "objective_with_one_comment_removed") (wait-for-title "Functional test headline | Objective[8]") (wd/click ".func--remove-comment") (wait-for-title "Are you sure? | Objective[8]") (screenshot "another_objective_comment_removal_confirmation_page") (wd/click ".func--confirm-removal") (wait-for-title "Functional test headline | Objective[8]") (screenshot "objective_page_with_both_comments_removed") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-can-remove-comments") (throw e)))] (:content result) =not=> (contains "Functional test comment text"))) (future-fact "Admin can delete a comment on a draft" (let [result (try (wd/to (str (:objective-url @journey-state) "/drafts/latest")) (wait-for-title "Policy draft | Objective[8]") (screenshot "draft_with_comment_to_remove") (wd/click ".func--remove-comment") (wait-for-title "Are you sure? | Objective[8]") (screenshot "objective_comment_removal_confirmation_page") (wd/click ".func--confirm-removal") (screenshot "draft_with_one_comment_removed") {:page-title (wd/title) :page-source (wd/page-source)} (catch Exception e (screenshot "ERROR-Can-comment-on-a-draft") (throw e)))] (:content result =not=> (contains "my draft section annotation")))) (fact "User with admin credentials can remove an objective" (let [result (try (wd/click ".func--objectives") (wait-for-title "Objectives | Objective[8]") (wd/click ".func--remove-objective") (wait-for-title "Are you sure? | Objective[8]") (screenshot "admin_removal_confirmation_page") (wd/click ".func--confirm-removal") (wait-for-title "Objectives | Objective[8]") (screenshot "objectives_page_after_removing_the_only_objective") {:page-title (wd/title) :content (wd/page-source)} (catch Exception e (screenshot "ERROR-User-with-admin-credentials-can-remove-objective") (throw e)))] (:page-title result) => "Objectives | Objective[8]" (:content result) =not=> (contains "Functional test headline"))) (fact "Can view the removed objective on the admin-activity page" (let [objective-id (-> (:objective-url @journey-state) (string/split #"/") last) objective-uri (str "/objectives/" objective-id)] (try (wd/click ".func--admin-link") (wait-for-title "Admin activity | Objective[8]") (screenshot "admin_activity_page") (wd/page-source) (catch Exception e (screenshot "ERROR-Can-view-the-removed-objective-on-the-admin-activity-page") (throw e))) => (contains objective-uri))))
[ { "context": "username \"root\"\n :password \"123456\"\n :jdbc-url \"jdbc:mysql://1270.0.01:3", "end": 1000, "score": 0.9991805553436279, "start": 994, "tag": "PASSWORD", "value": "123456" }, { "context": "se-name \"test_db\"\n ;; :server-name \"192.210.170.12\"\n ;; :port-number 3306\n :register-mbea", "end": 1244, "score": 0.9572666883468628, "start": 1230, "tag": "IP_ADDRESS", "value": "192.210.170.12" } ]
lib/ol.hikari-cp.ig/src/ol/hikari_cp/ig.clj
Ramblurr/ol-system
0
(ns ol.hikari-cp.ig (:require [integrant.core :as ig] [hikari-cp.core :as cp] ;[next.jdbc.connection :as connection] [ol.system.ig-utils :as ig-utils] ) (:import (com.zaxxer.hikari HikariDataSource))) (defmethod ig/init-key ::hikari-connection [_ pool-spec] ;(connection/->pool HikariDataSource pool-spec) (cp/make-datasource pool-spec)) (defmethod ig/suspend-key! ::hikari-connection [_ _]) (defmethod ig/halt-key! ::hikari-connection [_ conn] (cp/close-datasource conn)) (defmethod ig/resume-key ::hikari-connection [key opts old-opts old-impl] (ig-utils/resume-handler key opts old-opts old-impl)) (comment ;; pool-spec-example {:auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "ds-pool" :username "root" :password "123456" :jdbc-url "jdbc:mysql://1270.0.01:3306/test_db?characterEncoding=utf8" :driver-class-name "com.mysql.jdbc.Driver" ;; :adapter "mysql" ;; :database-name "test_db" ;; :server-name "192.210.170.12" ;; :port-number 3306 :register-mbeans false} )
53040
(ns ol.hikari-cp.ig (:require [integrant.core :as ig] [hikari-cp.core :as cp] ;[next.jdbc.connection :as connection] [ol.system.ig-utils :as ig-utils] ) (:import (com.zaxxer.hikari HikariDataSource))) (defmethod ig/init-key ::hikari-connection [_ pool-spec] ;(connection/->pool HikariDataSource pool-spec) (cp/make-datasource pool-spec)) (defmethod ig/suspend-key! ::hikari-connection [_ _]) (defmethod ig/halt-key! ::hikari-connection [_ conn] (cp/close-datasource conn)) (defmethod ig/resume-key ::hikari-connection [key opts old-opts old-impl] (ig-utils/resume-handler key opts old-opts old-impl)) (comment ;; pool-spec-example {:auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "ds-pool" :username "root" :password "<PASSWORD>" :jdbc-url "jdbc:mysql://1270.0.01:3306/test_db?characterEncoding=utf8" :driver-class-name "com.mysql.jdbc.Driver" ;; :adapter "mysql" ;; :database-name "test_db" ;; :server-name "172.16.58.3" ;; :port-number 3306 :register-mbeans false} )
true
(ns ol.hikari-cp.ig (:require [integrant.core :as ig] [hikari-cp.core :as cp] ;[next.jdbc.connection :as connection] [ol.system.ig-utils :as ig-utils] ) (:import (com.zaxxer.hikari HikariDataSource))) (defmethod ig/init-key ::hikari-connection [_ pool-spec] ;(connection/->pool HikariDataSource pool-spec) (cp/make-datasource pool-spec)) (defmethod ig/suspend-key! ::hikari-connection [_ _]) (defmethod ig/halt-key! ::hikari-connection [_ conn] (cp/close-datasource conn)) (defmethod ig/resume-key ::hikari-connection [key opts old-opts old-impl] (ig-utils/resume-handler key opts old-opts old-impl)) (comment ;; pool-spec-example {:auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "ds-pool" :username "root" :password "PI:PASSWORD:<PASSWORD>END_PI" :jdbc-url "jdbc:mysql://1270.0.01:3306/test_db?characterEncoding=utf8" :driver-class-name "com.mysql.jdbc.Driver" ;; :adapter "mysql" ;; :database-name "test_db" ;; :server-name "PI:IP_ADDRESS:172.16.58.3END_PI" ;; :port-number 3306 :register-mbeans false} )
[ { "context": "; Copyright 2020 Mark Wardle and Eldrix Ltd\n;\n; Licensed under the Apache Li", "end": 28, "score": 0.9998562932014465, "start": 17, "tag": "NAME", "value": "Mark Wardle" } ]
cmd/com/eldrix/hermes/cmd/server.clj
pacharanero/hermes
0
; Copyright 2020 Mark Wardle and Eldrix Ltd ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;; (ns com.eldrix.hermes.cmd.server (:require [cheshire.core :as json] [cheshire.generate :as json-gen] [clojure.string :as str] [clojure.tools.logging.readable :as log] [com.eldrix.hermes.core :as hermes] [com.eldrix.hermes.snomed :as snomed] [io.pedestal.http :as http] [io.pedestal.http.content-negotiation :as conneg] [io.pedestal.http.route :as route] [io.pedestal.interceptor :as intc] [io.pedestal.interceptor.error :as intc-err]) (:import (java.time.format DateTimeFormatter) (java.time LocalDate) (com.fasterxml.jackson.core JsonGenerator) (java.util Locale) (com.eldrix.hermes.core Service))) (set! *warn-on-reflection* true) (def supported-types ["application/json" "application/edn"]) (def content-neg-intc (conneg/negotiate-content supported-types)) (defn response [status body & {:as headers}] {:status status :body body :headers headers}) (def ok (partial response 200)) (def not-found (partial response 404)) (defn accepted-type [context] (get-in context [:request :accept :field] "application/json")) (json-gen/add-encoder LocalDate (fn [^LocalDate o ^JsonGenerator out] (.writeString out (.format (DateTimeFormatter/ISO_DATE) o)))) (defn transform-content [body content-type] (case content-type "text/html" body "text/plain" body "application/edn" (.getBytes (pr-str body) "UTF-8") "application/json" (.getBytes (json/generate-string body) "UTF-8"))) (defn coerce-to [response content-type] (-> response (update :body transform-content content-type) (assoc-in [:headers "Content-Type"] content-type))) (def coerce-body {:name ::coerce-body :leave (fn [context] (if (get-in context [:response :headers "Content-Type"]) context (update-in context [:response] coerce-to (accepted-type context))))}) (defn inject-svc "A simple interceptor to inject terminology service 'svc' into the context." [svc] {:name ::inject-svc :enter (fn [context] (update context :request assoc ::service svc))}) (def entity-render "Interceptor to render an entity '(:result context)' into the response." {:name :entity-render :leave (fn [context] (if-let [item (:result context)] (assoc context :response (ok item)) context))}) (def service-error-handler (intc-err/error-dispatch [context err] [{:exception-type :java.lang.NumberFormatException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "Invalid search parameters; invalid number: " (ex-message (:exception (ex-data err))))}) [{:exception-type :java.lang.IllegalArgumentException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) [{:exception-type :clojure.lang.ExceptionInfo :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) :else (assoc context :io.pedestal.interceptor.chain/error err))) (def get-concept {:name ::get-concept :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (hermes/get-concept (get-in context [:request ::service]) concept-id)] (assoc context :result concept))))}) (def get-extended-concept {:name ::get-extended-concept :enter (fn [context] (let [svc (get-in context [:request ::service])] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (hermes/get-extended-concept svc concept-id)] (let [langs (or (get-in context [:request :headers "accept-language"] (.toLanguageTag (Locale/getDefault)))) preferred (hermes/get-preferred-synonym svc concept-id langs)] (assoc context :result (assoc concept :preferredDescription preferred)))))))}) (def get-historical {:name ::get-historical :enter (fn [context] (let [svc (get-in context [:request ::service])] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (assoc context :result (hermes/historical-associations svc concept-id)))))}) (def get-concept-reference-sets {:name ::get-concept-reference-sets :enter (fn [context] (let [svc (get-in context [:request ::service])] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (assoc context :result (hermes/get-component-refset-items svc concept-id)))))}) (def get-concept-descriptions {:name ::get-concept-descriptions :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [ds (hermes/get-descriptions (get-in context [:request ::service]) concept-id)] (assoc context :result ds))))}) (def get-concept-preferred-description {:name ::get-concept-preferred-description :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (let [langs (or (get-in context [:request :headers "accept-language"]) (.toLanguageTag (Locale/getDefault)))] (when-let [ds (hermes/get-preferred-synonym (get-in context [:request ::service]) concept-id langs)] (assoc context :result ds)))))}) (def get-map-to {:name ::get-map-to :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) refset-id (Long/parseLong (get-in context [:request :path-params :refset-id]))] (when (and concept-id refset-id) (when-let [rfs (hermes/get-component-refset-items (get-in context [:request ::service]) concept-id refset-id)] (assoc context :result rfs)))))}) (def get-map-from {:name ::get-map-from :enter (fn [context] (let [refset-id (Long/parseLong (get-in context [:request :path-params :refset-id])) code (get-in context [:request :path-params :code])] (when (and refset-id code) (when-let [rfs (hermes/reverse-map (get-in context [:request ::service]) refset-id (str/upper-case code))] (assoc context :result rfs)))))}) (def subsumed-by? {:name ::subsumed-by :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) subsumer-id (Long/parseLong (get-in context [:request :path-params :subsumer-id])) svc (get-in context [:request ::service])] (log/info "subsumed by request: is " concept-id "subsumed by" subsumer-id ", using svc:" svc "?") (assoc context :result {:subsumedBy (hermes/subsumed-by? svc concept-id subsumer-id)})))}) (defn parse-search-params [params] (let [{:keys [s maxHits isA refset constraint ecl fuzzy fallbackFuzzy]} params] (cond-> {} s (assoc :s s) constraint (assoc :constraint constraint) ecl (assoc :constraint ecl) maxHits (assoc :max-hits (Integer/parseInt maxHits)) (string? isA) (assoc :properties {snomed/IsA (Long/parseLong isA)}) (vector? isA) (assoc :properties {snomed/IsA (into [] (map #(Long/parseLong %) isA))}) (string? refset) (assoc :concept-refsets [(Long/parseLong refset)]) (vector? refset) (assoc :concept-refsets (into [] (map #(Long/parseLong %) refset))) (#{"true" "1"} fuzzy) (assoc :fuzzy 2) (#{"true" "1"} fallbackFuzzy) (assoc :fallback-fuzzy 2)))) (def get-search {:name ::get-search :enter (fn [context] (let [params (parse-search-params (get-in context [:request :params])) svc (get-in context [:request ::service]) max-hits (or (:max-hits params) 200)] (if (< 0 max-hits 10000) (assoc context :result (hermes/search svc (assoc params :max-hits max-hits))) (throw (IllegalArgumentException. "invalid parameter: maxHits")))))}) (def get-expand {:name ::get-expand :enter (fn [context] (let [ecl (get-in context [:request :params :ecl]) include-historic? (#{"true" "1"} (get-in context [:request :params :include-historic])) svc (get-in context [:request ::service]) max-hits (or (get-in context [:request :params :max-hits]) 500)] (if (< 0 max-hits 10000) (assoc context :result (if include-historic? (hermes/expand-ecl-historic svc ecl) (hermes/expand-ecl svc ecl))) (throw (IllegalArgumentException. "invalid parameter: maxHits")))))}) (def common-routes [coerce-body content-neg-intc entity-render]) (def routes (route/expand-routes #{["/v1/snomed/concepts/:concept-id" :get (conj common-routes get-concept) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/descriptions" :get (conj common-routes get-concept-descriptions) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/preferred" :get (conj common-routes get-concept-preferred-description) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/extended" :get (conj common-routes get-extended-concept) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/historical" :get (conj common-routes get-historical) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/refsets" :get (conj common-routes get-concept-reference-sets) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/map/:refset-id" :get (conj common-routes get-map-to) :constraints {:concept-id #"[0-9]+" :refset-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/subsumed-by/:subsumer-id" :get (conj common-routes subsumed-by?) :constraints {:concept-id #"[0-9]+" :subsumer-id #"[0-9]+"}] ["/v1/snomed/crossmap/:refset-id/:code" :get (conj common-routes get-map-from) :constraints {:refset-id #"[0-9]+"}] ["/v1/snomed/search" :get [service-error-handler coerce-body content-neg-intc entity-render get-search]] ["/v1/snomed/expand" :get [service-error-handler coerce-body content-neg-intc entity-render get-expand]]})) (def service-map {::http/routes routes ::http/type :jetty ::http/port 8080}) (defn start-server ([^Service svc {:keys [port bind-address join?] :as opts :or {join? true}}] (let [cfg (cond-> {} port (assoc ::http/port port) bind-address (assoc ::http/host bind-address))] (-> (merge service-map cfg) (assoc ::http/join? join?) (http/default-interceptors) (update ::http/interceptors conj (intc/interceptor (inject-svc svc))) http/create-server http/start)))) (defn stop-server [server] (http/stop server)) ;; For interactive development (defonce server (atom nil)) (defn start-dev [svc port] (reset! server (start-server svc {:port port :join? false}))) (defn stop-dev [] (http/stop @server)) (comment (require '[com.eldrix.hermes.core]) (def svc (com.eldrix.hermes.core/open "snomed.db")) (start-dev svc 8080) (stop-dev) )
18272
; Copyright 2020 <NAME> and Eldrix Ltd ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;; (ns com.eldrix.hermes.cmd.server (:require [cheshire.core :as json] [cheshire.generate :as json-gen] [clojure.string :as str] [clojure.tools.logging.readable :as log] [com.eldrix.hermes.core :as hermes] [com.eldrix.hermes.snomed :as snomed] [io.pedestal.http :as http] [io.pedestal.http.content-negotiation :as conneg] [io.pedestal.http.route :as route] [io.pedestal.interceptor :as intc] [io.pedestal.interceptor.error :as intc-err]) (:import (java.time.format DateTimeFormatter) (java.time LocalDate) (com.fasterxml.jackson.core JsonGenerator) (java.util Locale) (com.eldrix.hermes.core Service))) (set! *warn-on-reflection* true) (def supported-types ["application/json" "application/edn"]) (def content-neg-intc (conneg/negotiate-content supported-types)) (defn response [status body & {:as headers}] {:status status :body body :headers headers}) (def ok (partial response 200)) (def not-found (partial response 404)) (defn accepted-type [context] (get-in context [:request :accept :field] "application/json")) (json-gen/add-encoder LocalDate (fn [^LocalDate o ^JsonGenerator out] (.writeString out (.format (DateTimeFormatter/ISO_DATE) o)))) (defn transform-content [body content-type] (case content-type "text/html" body "text/plain" body "application/edn" (.getBytes (pr-str body) "UTF-8") "application/json" (.getBytes (json/generate-string body) "UTF-8"))) (defn coerce-to [response content-type] (-> response (update :body transform-content content-type) (assoc-in [:headers "Content-Type"] content-type))) (def coerce-body {:name ::coerce-body :leave (fn [context] (if (get-in context [:response :headers "Content-Type"]) context (update-in context [:response] coerce-to (accepted-type context))))}) (defn inject-svc "A simple interceptor to inject terminology service 'svc' into the context." [svc] {:name ::inject-svc :enter (fn [context] (update context :request assoc ::service svc))}) (def entity-render "Interceptor to render an entity '(:result context)' into the response." {:name :entity-render :leave (fn [context] (if-let [item (:result context)] (assoc context :response (ok item)) context))}) (def service-error-handler (intc-err/error-dispatch [context err] [{:exception-type :java.lang.NumberFormatException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "Invalid search parameters; invalid number: " (ex-message (:exception (ex-data err))))}) [{:exception-type :java.lang.IllegalArgumentException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) [{:exception-type :clojure.lang.ExceptionInfo :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) :else (assoc context :io.pedestal.interceptor.chain/error err))) (def get-concept {:name ::get-concept :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (hermes/get-concept (get-in context [:request ::service]) concept-id)] (assoc context :result concept))))}) (def get-extended-concept {:name ::get-extended-concept :enter (fn [context] (let [svc (get-in context [:request ::service])] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (hermes/get-extended-concept svc concept-id)] (let [langs (or (get-in context [:request :headers "accept-language"] (.toLanguageTag (Locale/getDefault)))) preferred (hermes/get-preferred-synonym svc concept-id langs)] (assoc context :result (assoc concept :preferredDescription preferred)))))))}) (def get-historical {:name ::get-historical :enter (fn [context] (let [svc (get-in context [:request ::service])] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (assoc context :result (hermes/historical-associations svc concept-id)))))}) (def get-concept-reference-sets {:name ::get-concept-reference-sets :enter (fn [context] (let [svc (get-in context [:request ::service])] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (assoc context :result (hermes/get-component-refset-items svc concept-id)))))}) (def get-concept-descriptions {:name ::get-concept-descriptions :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [ds (hermes/get-descriptions (get-in context [:request ::service]) concept-id)] (assoc context :result ds))))}) (def get-concept-preferred-description {:name ::get-concept-preferred-description :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (let [langs (or (get-in context [:request :headers "accept-language"]) (.toLanguageTag (Locale/getDefault)))] (when-let [ds (hermes/get-preferred-synonym (get-in context [:request ::service]) concept-id langs)] (assoc context :result ds)))))}) (def get-map-to {:name ::get-map-to :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) refset-id (Long/parseLong (get-in context [:request :path-params :refset-id]))] (when (and concept-id refset-id) (when-let [rfs (hermes/get-component-refset-items (get-in context [:request ::service]) concept-id refset-id)] (assoc context :result rfs)))))}) (def get-map-from {:name ::get-map-from :enter (fn [context] (let [refset-id (Long/parseLong (get-in context [:request :path-params :refset-id])) code (get-in context [:request :path-params :code])] (when (and refset-id code) (when-let [rfs (hermes/reverse-map (get-in context [:request ::service]) refset-id (str/upper-case code))] (assoc context :result rfs)))))}) (def subsumed-by? {:name ::subsumed-by :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) subsumer-id (Long/parseLong (get-in context [:request :path-params :subsumer-id])) svc (get-in context [:request ::service])] (log/info "subsumed by request: is " concept-id "subsumed by" subsumer-id ", using svc:" svc "?") (assoc context :result {:subsumedBy (hermes/subsumed-by? svc concept-id subsumer-id)})))}) (defn parse-search-params [params] (let [{:keys [s maxHits isA refset constraint ecl fuzzy fallbackFuzzy]} params] (cond-> {} s (assoc :s s) constraint (assoc :constraint constraint) ecl (assoc :constraint ecl) maxHits (assoc :max-hits (Integer/parseInt maxHits)) (string? isA) (assoc :properties {snomed/IsA (Long/parseLong isA)}) (vector? isA) (assoc :properties {snomed/IsA (into [] (map #(Long/parseLong %) isA))}) (string? refset) (assoc :concept-refsets [(Long/parseLong refset)]) (vector? refset) (assoc :concept-refsets (into [] (map #(Long/parseLong %) refset))) (#{"true" "1"} fuzzy) (assoc :fuzzy 2) (#{"true" "1"} fallbackFuzzy) (assoc :fallback-fuzzy 2)))) (def get-search {:name ::get-search :enter (fn [context] (let [params (parse-search-params (get-in context [:request :params])) svc (get-in context [:request ::service]) max-hits (or (:max-hits params) 200)] (if (< 0 max-hits 10000) (assoc context :result (hermes/search svc (assoc params :max-hits max-hits))) (throw (IllegalArgumentException. "invalid parameter: maxHits")))))}) (def get-expand {:name ::get-expand :enter (fn [context] (let [ecl (get-in context [:request :params :ecl]) include-historic? (#{"true" "1"} (get-in context [:request :params :include-historic])) svc (get-in context [:request ::service]) max-hits (or (get-in context [:request :params :max-hits]) 500)] (if (< 0 max-hits 10000) (assoc context :result (if include-historic? (hermes/expand-ecl-historic svc ecl) (hermes/expand-ecl svc ecl))) (throw (IllegalArgumentException. "invalid parameter: maxHits")))))}) (def common-routes [coerce-body content-neg-intc entity-render]) (def routes (route/expand-routes #{["/v1/snomed/concepts/:concept-id" :get (conj common-routes get-concept) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/descriptions" :get (conj common-routes get-concept-descriptions) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/preferred" :get (conj common-routes get-concept-preferred-description) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/extended" :get (conj common-routes get-extended-concept) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/historical" :get (conj common-routes get-historical) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/refsets" :get (conj common-routes get-concept-reference-sets) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/map/:refset-id" :get (conj common-routes get-map-to) :constraints {:concept-id #"[0-9]+" :refset-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/subsumed-by/:subsumer-id" :get (conj common-routes subsumed-by?) :constraints {:concept-id #"[0-9]+" :subsumer-id #"[0-9]+"}] ["/v1/snomed/crossmap/:refset-id/:code" :get (conj common-routes get-map-from) :constraints {:refset-id #"[0-9]+"}] ["/v1/snomed/search" :get [service-error-handler coerce-body content-neg-intc entity-render get-search]] ["/v1/snomed/expand" :get [service-error-handler coerce-body content-neg-intc entity-render get-expand]]})) (def service-map {::http/routes routes ::http/type :jetty ::http/port 8080}) (defn start-server ([^Service svc {:keys [port bind-address join?] :as opts :or {join? true}}] (let [cfg (cond-> {} port (assoc ::http/port port) bind-address (assoc ::http/host bind-address))] (-> (merge service-map cfg) (assoc ::http/join? join?) (http/default-interceptors) (update ::http/interceptors conj (intc/interceptor (inject-svc svc))) http/create-server http/start)))) (defn stop-server [server] (http/stop server)) ;; For interactive development (defonce server (atom nil)) (defn start-dev [svc port] (reset! server (start-server svc {:port port :join? false}))) (defn stop-dev [] (http/stop @server)) (comment (require '[com.eldrix.hermes.core]) (def svc (com.eldrix.hermes.core/open "snomed.db")) (start-dev svc 8080) (stop-dev) )
true
; Copyright 2020 PI:NAME:<NAME>END_PI and Eldrix Ltd ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;; (ns com.eldrix.hermes.cmd.server (:require [cheshire.core :as json] [cheshire.generate :as json-gen] [clojure.string :as str] [clojure.tools.logging.readable :as log] [com.eldrix.hermes.core :as hermes] [com.eldrix.hermes.snomed :as snomed] [io.pedestal.http :as http] [io.pedestal.http.content-negotiation :as conneg] [io.pedestal.http.route :as route] [io.pedestal.interceptor :as intc] [io.pedestal.interceptor.error :as intc-err]) (:import (java.time.format DateTimeFormatter) (java.time LocalDate) (com.fasterxml.jackson.core JsonGenerator) (java.util Locale) (com.eldrix.hermes.core Service))) (set! *warn-on-reflection* true) (def supported-types ["application/json" "application/edn"]) (def content-neg-intc (conneg/negotiate-content supported-types)) (defn response [status body & {:as headers}] {:status status :body body :headers headers}) (def ok (partial response 200)) (def not-found (partial response 404)) (defn accepted-type [context] (get-in context [:request :accept :field] "application/json")) (json-gen/add-encoder LocalDate (fn [^LocalDate o ^JsonGenerator out] (.writeString out (.format (DateTimeFormatter/ISO_DATE) o)))) (defn transform-content [body content-type] (case content-type "text/html" body "text/plain" body "application/edn" (.getBytes (pr-str body) "UTF-8") "application/json" (.getBytes (json/generate-string body) "UTF-8"))) (defn coerce-to [response content-type] (-> response (update :body transform-content content-type) (assoc-in [:headers "Content-Type"] content-type))) (def coerce-body {:name ::coerce-body :leave (fn [context] (if (get-in context [:response :headers "Content-Type"]) context (update-in context [:response] coerce-to (accepted-type context))))}) (defn inject-svc "A simple interceptor to inject terminology service 'svc' into the context." [svc] {:name ::inject-svc :enter (fn [context] (update context :request assoc ::service svc))}) (def entity-render "Interceptor to render an entity '(:result context)' into the response." {:name :entity-render :leave (fn [context] (if-let [item (:result context)] (assoc context :response (ok item)) context))}) (def service-error-handler (intc-err/error-dispatch [context err] [{:exception-type :java.lang.NumberFormatException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "Invalid search parameters; invalid number: " (ex-message (:exception (ex-data err))))}) [{:exception-type :java.lang.IllegalArgumentException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) [{:exception-type :clojure.lang.ExceptionInfo :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) :else (assoc context :io.pedestal.interceptor.chain/error err))) (def get-concept {:name ::get-concept :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (hermes/get-concept (get-in context [:request ::service]) concept-id)] (assoc context :result concept))))}) (def get-extended-concept {:name ::get-extended-concept :enter (fn [context] (let [svc (get-in context [:request ::service])] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (hermes/get-extended-concept svc concept-id)] (let [langs (or (get-in context [:request :headers "accept-language"] (.toLanguageTag (Locale/getDefault)))) preferred (hermes/get-preferred-synonym svc concept-id langs)] (assoc context :result (assoc concept :preferredDescription preferred)))))))}) (def get-historical {:name ::get-historical :enter (fn [context] (let [svc (get-in context [:request ::service])] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (assoc context :result (hermes/historical-associations svc concept-id)))))}) (def get-concept-reference-sets {:name ::get-concept-reference-sets :enter (fn [context] (let [svc (get-in context [:request ::service])] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (assoc context :result (hermes/get-component-refset-items svc concept-id)))))}) (def get-concept-descriptions {:name ::get-concept-descriptions :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [ds (hermes/get-descriptions (get-in context [:request ::service]) concept-id)] (assoc context :result ds))))}) (def get-concept-preferred-description {:name ::get-concept-preferred-description :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (let [langs (or (get-in context [:request :headers "accept-language"]) (.toLanguageTag (Locale/getDefault)))] (when-let [ds (hermes/get-preferred-synonym (get-in context [:request ::service]) concept-id langs)] (assoc context :result ds)))))}) (def get-map-to {:name ::get-map-to :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) refset-id (Long/parseLong (get-in context [:request :path-params :refset-id]))] (when (and concept-id refset-id) (when-let [rfs (hermes/get-component-refset-items (get-in context [:request ::service]) concept-id refset-id)] (assoc context :result rfs)))))}) (def get-map-from {:name ::get-map-from :enter (fn [context] (let [refset-id (Long/parseLong (get-in context [:request :path-params :refset-id])) code (get-in context [:request :path-params :code])] (when (and refset-id code) (when-let [rfs (hermes/reverse-map (get-in context [:request ::service]) refset-id (str/upper-case code))] (assoc context :result rfs)))))}) (def subsumed-by? {:name ::subsumed-by :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) subsumer-id (Long/parseLong (get-in context [:request :path-params :subsumer-id])) svc (get-in context [:request ::service])] (log/info "subsumed by request: is " concept-id "subsumed by" subsumer-id ", using svc:" svc "?") (assoc context :result {:subsumedBy (hermes/subsumed-by? svc concept-id subsumer-id)})))}) (defn parse-search-params [params] (let [{:keys [s maxHits isA refset constraint ecl fuzzy fallbackFuzzy]} params] (cond-> {} s (assoc :s s) constraint (assoc :constraint constraint) ecl (assoc :constraint ecl) maxHits (assoc :max-hits (Integer/parseInt maxHits)) (string? isA) (assoc :properties {snomed/IsA (Long/parseLong isA)}) (vector? isA) (assoc :properties {snomed/IsA (into [] (map #(Long/parseLong %) isA))}) (string? refset) (assoc :concept-refsets [(Long/parseLong refset)]) (vector? refset) (assoc :concept-refsets (into [] (map #(Long/parseLong %) refset))) (#{"true" "1"} fuzzy) (assoc :fuzzy 2) (#{"true" "1"} fallbackFuzzy) (assoc :fallback-fuzzy 2)))) (def get-search {:name ::get-search :enter (fn [context] (let [params (parse-search-params (get-in context [:request :params])) svc (get-in context [:request ::service]) max-hits (or (:max-hits params) 200)] (if (< 0 max-hits 10000) (assoc context :result (hermes/search svc (assoc params :max-hits max-hits))) (throw (IllegalArgumentException. "invalid parameter: maxHits")))))}) (def get-expand {:name ::get-expand :enter (fn [context] (let [ecl (get-in context [:request :params :ecl]) include-historic? (#{"true" "1"} (get-in context [:request :params :include-historic])) svc (get-in context [:request ::service]) max-hits (or (get-in context [:request :params :max-hits]) 500)] (if (< 0 max-hits 10000) (assoc context :result (if include-historic? (hermes/expand-ecl-historic svc ecl) (hermes/expand-ecl svc ecl))) (throw (IllegalArgumentException. "invalid parameter: maxHits")))))}) (def common-routes [coerce-body content-neg-intc entity-render]) (def routes (route/expand-routes #{["/v1/snomed/concepts/:concept-id" :get (conj common-routes get-concept) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/descriptions" :get (conj common-routes get-concept-descriptions) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/preferred" :get (conj common-routes get-concept-preferred-description) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/extended" :get (conj common-routes get-extended-concept) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/historical" :get (conj common-routes get-historical) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/refsets" :get (conj common-routes get-concept-reference-sets) :constraints {:concept-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/map/:refset-id" :get (conj common-routes get-map-to) :constraints {:concept-id #"[0-9]+" :refset-id #"[0-9]+"}] ["/v1/snomed/concepts/:concept-id/subsumed-by/:subsumer-id" :get (conj common-routes subsumed-by?) :constraints {:concept-id #"[0-9]+" :subsumer-id #"[0-9]+"}] ["/v1/snomed/crossmap/:refset-id/:code" :get (conj common-routes get-map-from) :constraints {:refset-id #"[0-9]+"}] ["/v1/snomed/search" :get [service-error-handler coerce-body content-neg-intc entity-render get-search]] ["/v1/snomed/expand" :get [service-error-handler coerce-body content-neg-intc entity-render get-expand]]})) (def service-map {::http/routes routes ::http/type :jetty ::http/port 8080}) (defn start-server ([^Service svc {:keys [port bind-address join?] :as opts :or {join? true}}] (let [cfg (cond-> {} port (assoc ::http/port port) bind-address (assoc ::http/host bind-address))] (-> (merge service-map cfg) (assoc ::http/join? join?) (http/default-interceptors) (update ::http/interceptors conj (intc/interceptor (inject-svc svc))) http/create-server http/start)))) (defn stop-server [server] (http/stop server)) ;; For interactive development (defonce server (atom nil)) (defn start-dev [svc port] (reset! server (start-server svc {:port port :join? false}))) (defn stop-dev [] (http/stop @server)) (comment (require '[com.eldrix.hermes.core]) (def svc (com.eldrix.hermes.core/open "snomed.db")) (start-dev svc 8080) (stop-dev) )
[ { "context": " :username (System/getenv \"CLOJARS_USER\")\n :password (Syst", "end": 1540, "score": 0.7172631025314331, "start": 1528, "tag": "USERNAME", "value": "CLOJARS_USER" }, { "context": " :password (System/getenv \"CLOJARS_PASS\")}])))\n\n(require\n '[orchestra.spec.test :refer [", "end": 1613, "score": 0.9437847137451172, "start": 1601, "tag": "PASSWORD", "value": "CLOJARS_PASS" }, { "context": "tation generator\"\n :url \"https://github.com/oakes/Dynadoc\"\n :license {\"Public Domain\" \"http:/", "end": 1961, "score": 0.938230037689209, "start": 1956, "tag": "USERNAME", "value": "oakes" } ]
build.boot
starcity-properties/Dynadoc
0
(defn read-deps-edn [aliases-to-include] (let [{:keys [paths deps aliases]} (-> "deps.edn" slurp clojure.edn/read-string) deps (->> (select-keys aliases aliases-to-include) vals (mapcat :extra-deps) (into deps) (reduce (fn [deps [artifact info]] (if-let [version (:mvn/version info)] (conj deps (transduce cat conj [artifact version] (select-keys info [:scope :exclusions]))) deps)) []))] {:dependencies deps :source-paths (set paths) :resource-paths (set paths)})) (let [{:keys [source-paths resource-paths dependencies]} (read-deps-edn [])] (set-env! :source-paths source-paths :resource-paths resource-paths :dependencies (into '[[adzerk/boot-cljs "2.1.4" :scope "test"] [adzerk/boot-reload "0.5.2" :scope "test"] [org.clojure/test.check "0.9.0" :scope "test"] [nightlight "RELEASE" :scope "test"] [javax.xml.bind/jaxb-api "2.3.0"] ; necessary for Java 9 compatibility [orchestra "2017.11.12-1" :scope "test"]] dependencies) :repositories (conj (get-env :repositories) ["clojars" {:url "https://clojars.org/repo/" :username (System/getenv "CLOJARS_USER") :password (System/getenv "CLOJARS_PASS")}]))) (require '[orchestra.spec.test :refer [instrument]] '[adzerk.boot-cljs :refer [cljs]] '[adzerk.boot-reload :refer [reload]] '[nightlight.boot :refer [nightlight]]) (task-options! pom {:project 'dynadoc :version "1.4.6-SNAPSHOT" :description "A dynamic documentation generator" :url "https://github.com/oakes/Dynadoc" :license {"Public Domain" "http://unlicense.org/UNLICENSE"}} push {:repo "clojars"} sift {:include #{#"dynadoc-public/main.out"} :invert true}) (deftask local [] (set-env! :resource-paths #(conj % "prod-resources")) (comp (cljs) (sift) (pom) (jar) (install))) (deftask deploy [] (set-env! :resource-paths #(conj % "prod-resources")) (comp (cljs) (sift) (pom) (jar) (push))) (deftask run [] (set-env! :resource-paths #(conj % "dev-resources")) (comp (watch) (nightlight :port 4000 :url "http://localhost:5000") (reload :asset-path "dynadoc-public") (cljs) (with-pass-thru _ (require '[dynadoc.core :refer [dev-start]]) (instrument) ((resolve 'dev-start) {:port 5000 :dev? true})) (target)))
121100
(defn read-deps-edn [aliases-to-include] (let [{:keys [paths deps aliases]} (-> "deps.edn" slurp clojure.edn/read-string) deps (->> (select-keys aliases aliases-to-include) vals (mapcat :extra-deps) (into deps) (reduce (fn [deps [artifact info]] (if-let [version (:mvn/version info)] (conj deps (transduce cat conj [artifact version] (select-keys info [:scope :exclusions]))) deps)) []))] {:dependencies deps :source-paths (set paths) :resource-paths (set paths)})) (let [{:keys [source-paths resource-paths dependencies]} (read-deps-edn [])] (set-env! :source-paths source-paths :resource-paths resource-paths :dependencies (into '[[adzerk/boot-cljs "2.1.4" :scope "test"] [adzerk/boot-reload "0.5.2" :scope "test"] [org.clojure/test.check "0.9.0" :scope "test"] [nightlight "RELEASE" :scope "test"] [javax.xml.bind/jaxb-api "2.3.0"] ; necessary for Java 9 compatibility [orchestra "2017.11.12-1" :scope "test"]] dependencies) :repositories (conj (get-env :repositories) ["clojars" {:url "https://clojars.org/repo/" :username (System/getenv "CLOJARS_USER") :password (System/getenv "<PASSWORD>")}]))) (require '[orchestra.spec.test :refer [instrument]] '[adzerk.boot-cljs :refer [cljs]] '[adzerk.boot-reload :refer [reload]] '[nightlight.boot :refer [nightlight]]) (task-options! pom {:project 'dynadoc :version "1.4.6-SNAPSHOT" :description "A dynamic documentation generator" :url "https://github.com/oakes/Dynadoc" :license {"Public Domain" "http://unlicense.org/UNLICENSE"}} push {:repo "clojars"} sift {:include #{#"dynadoc-public/main.out"} :invert true}) (deftask local [] (set-env! :resource-paths #(conj % "prod-resources")) (comp (cljs) (sift) (pom) (jar) (install))) (deftask deploy [] (set-env! :resource-paths #(conj % "prod-resources")) (comp (cljs) (sift) (pom) (jar) (push))) (deftask run [] (set-env! :resource-paths #(conj % "dev-resources")) (comp (watch) (nightlight :port 4000 :url "http://localhost:5000") (reload :asset-path "dynadoc-public") (cljs) (with-pass-thru _ (require '[dynadoc.core :refer [dev-start]]) (instrument) ((resolve 'dev-start) {:port 5000 :dev? true})) (target)))
true
(defn read-deps-edn [aliases-to-include] (let [{:keys [paths deps aliases]} (-> "deps.edn" slurp clojure.edn/read-string) deps (->> (select-keys aliases aliases-to-include) vals (mapcat :extra-deps) (into deps) (reduce (fn [deps [artifact info]] (if-let [version (:mvn/version info)] (conj deps (transduce cat conj [artifact version] (select-keys info [:scope :exclusions]))) deps)) []))] {:dependencies deps :source-paths (set paths) :resource-paths (set paths)})) (let [{:keys [source-paths resource-paths dependencies]} (read-deps-edn [])] (set-env! :source-paths source-paths :resource-paths resource-paths :dependencies (into '[[adzerk/boot-cljs "2.1.4" :scope "test"] [adzerk/boot-reload "0.5.2" :scope "test"] [org.clojure/test.check "0.9.0" :scope "test"] [nightlight "RELEASE" :scope "test"] [javax.xml.bind/jaxb-api "2.3.0"] ; necessary for Java 9 compatibility [orchestra "2017.11.12-1" :scope "test"]] dependencies) :repositories (conj (get-env :repositories) ["clojars" {:url "https://clojars.org/repo/" :username (System/getenv "CLOJARS_USER") :password (System/getenv "PI:PASSWORD:<PASSWORD>END_PI")}]))) (require '[orchestra.spec.test :refer [instrument]] '[adzerk.boot-cljs :refer [cljs]] '[adzerk.boot-reload :refer [reload]] '[nightlight.boot :refer [nightlight]]) (task-options! pom {:project 'dynadoc :version "1.4.6-SNAPSHOT" :description "A dynamic documentation generator" :url "https://github.com/oakes/Dynadoc" :license {"Public Domain" "http://unlicense.org/UNLICENSE"}} push {:repo "clojars"} sift {:include #{#"dynadoc-public/main.out"} :invert true}) (deftask local [] (set-env! :resource-paths #(conj % "prod-resources")) (comp (cljs) (sift) (pom) (jar) (install))) (deftask deploy [] (set-env! :resource-paths #(conj % "prod-resources")) (comp (cljs) (sift) (pom) (jar) (push))) (deftask run [] (set-env! :resource-paths #(conj % "dev-resources")) (comp (watch) (nightlight :port 4000 :url "http://localhost:5000") (reload :asset-path "dynadoc-public") (cljs) (with-pass-thru _ (require '[dynadoc.core :refer [dev-start]]) (instrument) ((resolve 'dev-start) {:port 5000 :dev? true})) (target)))
[ { "context": " with hold I\n\n ... elided paragraph last ...\n\n Frost Robert -----------------------\")\n\n(doall\n (map println ", "end": 233, "score": 0.9961028099060059, "start": 221, "tag": "NAME", "value": "Frost Robert" } ]
Task/Reverse-words-in-a-string/Clojure/reverse-words-in-a-string.clj
djgoku/RosettaCodeData
0
(def poem "---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert -----------------------") (doall (map println (map #(apply str (interpose " " (reverse (re-seq #"[^\s]+" %)))) (clojure.string/split poem #"\n"))))
101261
(def poem "---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... <NAME> -----------------------") (doall (map println (map #(apply str (interpose " " (reverse (re-seq #"[^\s]+" %)))) (clojure.string/split poem #"\n"))))
true
(def poem "---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... PI:NAME:<NAME>END_PI -----------------------") (doall (map println (map #(apply str (interpose " " (reverse (re-seq #"[^\s]+" %)))) (clojure.string/split poem #"\n"))))
[ { "context": "*\" version)))))\n\n;; from: https://gist.github.com/edw/5128978\n(defn delete-recursively [fname]\n (let [", "end": 793, "score": 0.9996387958526611, "start": 790, "tag": "USERNAME", "value": "edw" }, { "context": "on-data\n (let [data (make-security-data [{:user \"i2kweb\" :password nil :role \"query\"}\n ", "end": 15678, "score": 0.9783604145050049, "start": 15672, "tag": "USERNAME", "value": "i2kweb" }, { "context": "ata (make-security-data [{:user \"i2kweb\" :password nil :role \"query\"}\n ", "end": 15693, "score": 0.7376079559326172, "start": 15690, "tag": "PASSWORD", "value": "nil" }, { "context": "query\"}\n {:user \"i2kconduit-db\" :role \"upload\"}]\n ", "end": 15764, "score": 0.9338088035583496, "start": 15751, "tag": "USERNAME", "value": "i2kconduit-db" }, { "context": "tations.\"}))\n (commit!)\n (let [result (search* \"Leven\" {:df \"fulltext\" :request-handler \"/suggest\"} (wr", "end": 21463, "score": 0.9698368310928345, "start": 21458, "tag": "NAME", "value": "Leven" }, { "context": "))))]\n (println (format \"Best suggestion for \\\"Leven\\\": %s\" suggestion))\n (is (= suggestion \"Levens", "end": 21649, "score": 0.9565548300743103, "start": 21644, "tag": "NAME", "value": "Leven" }, { "context": "\"Leven\\\": %s\" suggestion))\n (is (= suggestion \"Levenshtein\")))\n\n\n (let [result (search* \"Leven\"\n ", "end": 21695, "score": 0.5534101724624634, "start": 21693, "tag": "NAME", "value": "Le" }, { "context": "stion \"Levenshtein\")))\n\n\n (let [result (search* \"Leven\"\n {:df \"fulltext\" :request", "end": 21741, "score": 0.9770321249961853, "start": 21736, "tag": "NAME", "value": "Leven" }, { "context": "nt/pprint suggestions))\n\n (let [result (search* \"Levenstein\" {:df \"fulltext\" :request-handler \"/spell\"} (wrap", "end": 22141, "score": 0.980421245098114, "start": 22131, "tag": "NAME", "value": "Levenstein" }, { "context": "ck (meta result))]\n (println (format \"Corrected Levenstein to %s\" (:collated-result spellcheck)))\n ", "end": 22296, "score": 0.7591881155967712, "start": 22294, "tag": "NAME", "value": "Le" }, { "context": "esult spellcheck)))\n (is (= {:collated-result \"Levenshtein\" \n :is-correctly-spelled? false\n ", "end": 22382, "score": 0.5966939926147461, "start": 22374, "tag": "NAME", "value": "Levensht" }, { "context": "rectly-spelled? false\n :alternatives {\"Levenstein\" {:num-found 1 :original-frequency 0 :start-offse", "end": 22467, "score": 0.6250521540641785, "start": 22457, "tag": "NAME", "value": "Levenstein" }, { "context": " spellcheck)))\n (let [result (search* \"Levenshte*\" {:df \"fulltext\" :request-handler \"/select-wi", "end": 22737, "score": 0.680953323841095, "start": 22731, "tag": "NAME", "value": "Levens" } ]
test/clojure_solr_test.clj
ejschoen/clojure-solr
1
(ns clojure-solr-test (:require [clojure.pprint] [clojure.java.io :as io] [clojure.string :as str]) (:import (java.util.jar Manifest)) (:import (org.apache.solr.client.solrj.embedded EmbeddedSolrServer)) (:import (org.apache.solr.core CoreContainer)) (:require [clj-time.core :as t]) (:require [clj-time.coerce :as tcoerce]) (:require [cheshire.core :as cheshire]) (:use [clojure.test]) (:use [clojure-solr]) (:use [clojure-solr.security]) (:use [clojure-solr.schema]) (:import [java.nio.charset StandardCharsets] [org.apache.commons.codec.binary Base64])) (defn get-solr-home-dir [] (let [version (get-solr-version)] (str "test-files/solr-" (second (re-matches #"(\d+)\..*" version))))) ;; from: https://gist.github.com/edw/5128978 (defn delete-recursively [fname] (let [func (fn [func f] (when (.isDirectory f) (doseq [f2 (.listFiles f)] (func func f2))) (try (clojure.java.io/delete-file f) (catch Exception _)))] (func func (clojure.java.io/file fname)))) (defn solr-server-fixture [f] (let [home-dir (get-solr-home-dir)] (delete-recursively (str home-dir "/data")) (System/setProperty "solr.solr.home" home-dir) (System/setProperty "solr.dist.dir" (str (System/getProperty "user.dir") "/test-files/dist")) (let [[_ major minor :as version] (re-matches #"(\d+)\.(\d+)\..*" (get-solr-version)) major (Integer/parseInt major) minor (Integer/parseInt minor)] (println (format "This is solr version %s" (first version))) (when (and (= major 7) (>= minor 4)) ;; https://issues.apache.org/jira/browse/SOLR-12858 (println "Using get as default method due to issue SOLR-12858") (set-default-method! :get) )) (with-connection (connect nil nil {:type EmbeddedSolrServer :core "clojure-solr" :home-dir (get-solr-home-dir)}) (f)))) (use-fixtures :each solr-server-fixture) (def sample-doc {:id "1" :type "pdf" :title "my title" :fulltext "my fulltext" :numeric 10 :updated (tcoerce/to-date (t/date-time 2015 02 27)) :terms ["Vocabulary 1/Term A" "Vocabulary 1/Term B" "Vocabulary 2/Term X/Term Y"]}) (deftest test-add-doc-with-lazyseq (add-document! {:id 2 :type "pdf" :related_s_mv (cheshire/parse-string "[\"abc\",\"def\"]")}) (commit!) (let [result (first (search "*" :facet-filters [{:name "id" :value "2"}] :df "fulltext"))] (is result) (is (vector? (:related_s_mv result))) (is (= #{"abc" "def"} (set (:related_s_mv result))))) ) (deftest test-add-document! (do (add-document! sample-doc) (commit!)) (is (= sample-doc (dissoc (first (search "my" :df "fulltext")) :_version_ :word))) (is (= {:start 0 :rows-set 1 :rows-total 1} (select-keys (meta (search "my" :df "fulltext")) [:start :rows-set :rows-total]))) (is (= [{:name "terms" :values [{:value "Vocabulary 1" :split-path ["Vocabulary 1"] :title "Vocabulary 1" :depth 1 :count 1} {:value "Vocabulary 1/Term A" :split-path ["Vocabulary 1" "Term A"] :title "Term A" :depth 2 :count 1} {:value "Vocabulary 1/Term B" :split-path ["Vocabulary 1" "Term B"] :title "Term B" :depth 2 :count 1} {:value "Vocabulary 2" :split-path ["Vocabulary 2"] :title "Vocabulary 2" :depth 1 :count 1} {:value "Vocabulary 2/Term X" :split-path ["Vocabulary 2" "Term X"] :title "Term X" :depth 2 :count 1} {:value "Vocabulary 2/Term X/Term Y" :split-path ["Vocabulary 2" "Term X" "Term Y"] :title "Term Y" :depth 3 :count 1}]}] (:facet-fields (meta (search "my" :facet-fields [:terms] :facet-hier-sep #"/" :df "fulltext")))))) (deftest test-update-document! (do (add-document! sample-doc) (commit!)) (atomically-update! 1 :id [{:attribute :title :func :set :value "my new title"}]) (commit!) (let [search-result (search "my" :df "fulltext")] (is (= (get (first search-result) :title) "my new title")))) (deftest test-quoted-search (do (add-document! sample-doc) (commit!)) (is (= sample-doc (dissoc (first (search "\"my fulltext\"" :df "fulltext")) :_version_ :word))) (is (empty? (search "\"fulltext my\"" :df "fulltext")))) (deftest test-quoted-search-mw (do (add-document! sample-doc) (commit!)) (is (= sample-doc (dissoc (first (search*-with-middleware "\"my fulltext\"" {:df "fulltext"})) :_version_ :word))) (is (empty? (search*-with-middleware "\"fulltext my\"" {:df "fulltext"})))) (deftest test-facet-query (let [query->map (fn [s] (let [params (str/split s #"&")] (into {} (map (fn [pair] (str/split pair #"=")) params))))] (do (add-document! sample-doc) (commit!)) (is (= [{:name "terms" :value "Vocabulary 1" :count 1}] (:facet-queries (meta (search "my" :facet-queries [{:name "terms" :value "Vocabulary 1"}] :df "fulltext"))))) (is (= (query->map "q=my&df=fulltext&facet-queries={:name+\"terms\",+:value+\"Vocabulary+1\"}&facet.query={!raw+f%3Dterms}Vocabulary+1&facet=true&facet.mincount=1") (query->map (search "my" :just-return-query? true :facet-queries [{:name "terms" :value "Vocabulary 1"}] :df "fulltext")))))) (deftest test-facet-prefix (do (add-document! sample-doc) (add-document! (assoc sample-doc :id "2" :numeric 11)) (add-document! (assoc sample-doc :id "3" :numeric 11)) (add-document! (assoc sample-doc :id "4" :numeric 15)) (add-document! (assoc sample-doc :id "5" :numeric 8)) (commit!)) (let [result (meta (search "my" :facet-fields [{:name "terms" :prefix "Voc"}] :df "fulltext"))] (is (not (empty? (:facet-fields result))))) (let [result (meta (search "my" :facet-fields [{:name "terms" :prefix "Vocabulary 1"}] :df "fulltext"))] (is (not (empty? (:facet-fields result)))) (is (= 3 (count (-> result :facet-fields first :values)))) (is (every? #(.startsWith (:value %) "Vocabulary 1") (-> result :facet-fields first :values)))) (let [result (meta (search "my" :facet-fields [{:name "terms" :prefix "Vocabulary 1" :result-formatter #(update-in % [:value] clojure.string/lower-case)}] :df "fulltext"))] (is (not (empty? (:facet-fields result)))) (is (= 3 (count (-> result :facet-fields first :values)))) (is (every? #(.startsWith (:value %) "vocabulary 1") (-> result :facet-fields first :values))))) (deftest test-facet-ranges (do (add-document! sample-doc) (add-document! (assoc sample-doc :id "2" :numeric 11)) (add-document! (assoc sample-doc :id "3" :numeric 11)) (add-document! (assoc sample-doc :id "4" :numeric 15)) (add-document! (assoc sample-doc :id "5" :numeric 8)) (commit!)) (let [result (meta (search "my" :facet-numeric-ranges [{:field "numeric" :start (Integer. 9) :end (Integer. 12) :gap (Integer. 3) :others ["before" "after"] :include "lower" :hardend false}] :facet-date-ranges [{:field "updated" :start (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 26) (t/time-zone-for-id "America/Chicago"))) :end (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 28) (t/time-zone-for-id "America/Chicago"))) :gap "+1DAY" :timezone (t/time-zone-for-id "America/Chicago") :others ["before" "after"]}] :df "fulltext"))] (is (= {:name "numeric", :values [{:count 1, :value "[* TO 9}", :min-inclusive nil, :max-noninclusive 9} {:max-noninclusive 12, :min-inclusive 9, :value "[9 TO 12}", :count 3} {:count 1, :value "[12 TO *]", :min-inclusive 12, :max-noninclusive nil}], :start 9, :end 12, :gap 3, :before 1, :after 1} (some #(and (= (:name %) "numeric") %) (:facet-range-fields result)))) (is (= {:name "updated" :values [{:min-inclusive (tcoerce/to-date "2015-02-26T06:00:00Z") :max-noninclusive (tcoerce/to-date "2015-02-27T06:00:00Z") :value "[2015-02-26T06:00:00Z TO 2015-02-27T06:00:00Z}", :count 5}] :start (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 26) (t/time-zone-for-id "America/Chicago"))) :end (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 28) (t/time-zone-for-id "America/Chicago"))) :gap "+1DAY" :before 0 :after 0} (first (filter #(= (:name %) "updated") (:facet-range-fields result))))))) (deftest test-pivot-faceting (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (commit!) (let [result (meta (search "my" :df "fulltext" :rows 0 :facet-date-ranges [{:field "updated" :tag "ts" :start (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 26) (t/time-zone-for-id "America/Chicago"))) :end (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 28) (t/time-zone-for-id "America/Chicago"))) :gap "+1DAY" :timezone (t/time-zone-for-id "America/Chicago") :others ["before" "after"]}] :facet-pivot-fields ["{!range=ts}type"])) pivot-fields (:facet-pivot-fields result)] (is (= 1 (count pivot-fields))) (is (get pivot-fields "type")) (is (= 2 (count (get pivot-fields "type")))) (is (= 1 (count (get-in pivot-fields ["type" :ranges "docx" "updated"])))) (is (= 1 (:count (first (get-in pivot-fields ["type" :ranges "docx" "updated"]))))) (is (= 1 (count (get-in pivot-fields ["type" :ranges "pdf" "updated"])))) (is (= 1 (:count (first (get-in pivot-fields ["type" :ranges "pdf" "updated"]))))) #_(clojure.pprint/pprint (:facet-pivot-fields result)))) (deftest test-luke-schema (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (commit!) (binding [*qf* "fulltext"] (let [fields (get-fields-via-luke)] (is (not-empty fields)) (is (map? (get fields "fulltext"))) (is (set? (get-in fields ["fulltext" :schema])))))) (deftest test-edismax-disjunction (add-document! (assoc sample-doc :id 1 :fulltext "This is a clinical trial.")) (add-document! (assoc sample-doc :id 2 :fulltext "This is a clinical study.")) (add-document! (assoc sample-doc :id 3 :fulltext "This is a clinical trial and a clinical study.")) (commit!) (let [ct (search* "\"clinical trial\"" {:df "fulltext" :defType "edismax" :fl "id"}) cs (search* "\"clinical study\"" {:df "fulltext" :defType "edismax" :fl "id"}) cts (search* "(\"clinical trial\" OR \"clinical study\")" {:df "fulltext" :defType "edismax" :fl "id" }) cts-plus (search* "+(\"clinical trial\" OR \"clinical study\")" {:df "fulltext" :defType "edismax" :fl "id" }) cts3 (search* "+(\"clinical trial\" OR \"clinical study\" OR \"foo baz\")" {:df "fulltext" :defType "edismax" :fl "id"}) ] (is (= 2 (count ct))) (is (= #{"1" "3"} (set (map :id ct)))) (is (= 2 (count cs))) (is (= #{"2" "3"} (set (map :id cs)))) (is (= 3 (count cts))) (is (= 3 (count cts-plus))) (is (= 3 (count cts3))) )) (deftest test-exclude-filter-faceting (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (commit!) (let [docs (search "my" :df "fulltext" :facet-filters [{:name "type" :value "pdf" :full-formatter format-standard-filter-query :tag "type"}] :facet-fields [{:name "type" :ex "type"}]) result (meta docs) facet-fields (:facet-fields result)] (is (= 1 (count docs))) (is (= 1 (count facet-fields))) (is (some #(= "type" (:name %)) facet-fields)) (is (= 2 (count (:values (first facet-fields))))) (let [type-facet (group-by :value (:values (first facet-fields)))] (is (= 1 (:count (first (get type-facet "pdf"))))) (is (= 1 (:count (first (get type-facet "docx")))))))) (deftest test-exclude-filter-faceting-complex (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (add-document! (assoc sample-doc :id 3 :type "pptx")) (commit!) (let [docs (search "my" :df "fulltext" :facet-filters [{:name "type" :value "{!tag=type}(type:pdf OR type:docx)" :full-formatter #(:value %) :tag "type"}] :facet-fields [{:name "type" :ex "type"}]) result (meta docs) facet-fields (:facet-fields result)] (is (= 2 (count docs))) (is (= 1 (count facet-fields))) (is (some #(= "type" (:name %)) facet-fields)) (is (= 3 (count (:values (first facet-fields))))) (let [type-facet (group-by :value (:values (first facet-fields)))] (is (= 1 (:count (first (get type-facet "pptx"))))) (is (= 1 (:count (first (get type-facet "pdf"))))) (is (= 1 (:count (first (get type-facet "docx")))))))) (deftest test-solr-npe-from-bad-query (clojure.pprint/pprint (meta (search "*:*" :df "fulltext" :debugQuery true :defType "edismax" :facet-filters [{:name "complex" :value "(source:SemanticScholar%20Commercial%20Use%20Subset AND type:application/json;schema=semantic-scholar)" :formatter (fn [_ value] value)}] :facet-fields [{:name "type" :ex "type"}])))) (deftest test-make-security-json-data (let [data (make-security-data [{:user "i2kweb" :password nil :role "query"} {:user "i2kconduit-db" :role "upload"}] [{:name "read" :role "*"} {:name "schema-read" :role "*"} {:name "update" :role "upload"} {:name "health" :role "health" :path "/admin/info/system" :methods ["GET"] :collection ""}])] (is (:credentials data)) (is (:authorization data)) (is (:authentication data)) (is (= (last (get-in data [:authorization :permissions])) {:role "health" :name "health" :methods ["GET"] :path "/admin/info/system" :collection nil})) (is (get-in data [:credentials "i2kweb" :hashed-password])) (is (get-in data [:credentials "i2kweb" :salt])) (is (get-in data [:credentials "i2kweb" :cleartext-password])) (is (= (get-in data [:credentials "i2kweb" :hashed-password]) (:hashed-password (generate-salted-hash (.getBytes (get-in data [:credentials "i2kweb" :cleartext-password]) StandardCharsets/UTF_8) (Base64/decodeBase64 (get-in data [:credentials "i2kweb" :salt])))))))) (deftest test-delete-doc-by-id (add-document! sample-doc) (commit!) (let [update-response (delete-id! "1") status (.getStatus update-response)] (is (= status 0)))) (deftest test-delete-doc-by-query (add-document! sample-doc) (commit!) (let [update-response (delete-query! "title:\"my title\"") status (.getStatus update-response) ] (is (= status 0)))) (deftest test-query-boolean-filter (add-document! {:id 1 :boolean_b true :type "pdf"}) (commit!) (is (= (count (search "*:*" :defType "edismax" :qf "title fulltext")) 1)) (is (= 1 (some #(and (= (:value %) "true") (:count %)) (:values (first (:facet-fields (meta (search "*:*" :defType "edismax" :qf "title fulltext" :facet-fields ["boolean_b"])))))))) (is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "true" :formatter format-standard-filter-query}] :qf "title fulltext" :defType "edismax")) 1)) ;; raw queries against boolean values apparently don't work correctly. #_(is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "true" :formatter format-raw-query}] :qf "title fulltext" )) 1)) #_(is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "true" :formatter format-raw-query}] :qf "title fulltext" :defType "edismax")) 1)) #_(is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "TRUE" :formatter format-raw-query}] :qf "title fulltext" :defType "edismax")) 1)) (clojure.pprint/pprint (meta (search "*:*" :facet-filters [{:name "boolean_b" :value "TRUE" :formatter format-raw-query}] :debugQuery true :qf "title fulltext" :defType "edismax"))) (clojure.pprint/pprint (meta (search "*:*" :facet-filters [{:name "boolean_b" :value true :formatter format-raw-query}] :debugQuery true :qf "title fulltext" :defType "edismax"))) (clojure.pprint/pprint (first (search "*:*" :facet-filters [{:name "boolean_b" :value true :formatter format-standard-filter-query}] :debugQuery true :qf "title fulltext" :defType "edismax"))) (clojure.pprint/pprint (meta (search "*:*" :facet-filters [{:name "boolean_b" :value true :formatter format-standard-filter-query}] :debugQuery true :qf "title fulltext" :defType "edismax")))) (deftest test-spellchecker (doseq [i (range 10)] (add-document! {:id i :type "Web Page" :fulltext "Many of the parameters relate to how this spell checker should query the index for term suggestions. The distanceMeasure defines the metric to use during the spell check query. The value \"internal\" uses the default Levenshtein metric, which is the same metric used with the other spell checker implementations."})) (commit!) (let [result (search* "Leven" {:df "fulltext" :request-handler "/suggest"} (wrap-suggest solr-app)) suggestion (:term (first (:suggestions (meta result))))] (println (format "Best suggestion for \"Leven\": %s" suggestion)) (is (= suggestion "Levenshtein"))) (let [result (search* "Leven" {:df "fulltext" :request-handler "/suggest" :suggest.buildAll true } (-> solr-app (wrap-suggest :suggester-name ["suggest" "context_suggest"]))) suggestions (:suggestions (meta result))] (clojure.pprint/pprint suggestions)) (let [result (search* "Levenstein" {:df "fulltext" :request-handler "/spell"} (wrap-spellcheck solr-app)) spellcheck (:spellcheck (meta result))] (println (format "Corrected Levenstein to %s" (:collated-result spellcheck))) (is (= {:collated-result "Levenshtein" :is-correctly-spelled? false :alternatives {"Levenstein" {:num-found 1 :original-frequency 0 :start-offset 0 :end-offset 10 :alternatives ["Levenshtein"] :alternative-frequencies [10]}}} spellcheck))) (let [result (search* "Levenshte*" {:df "fulltext" :request-handler "/select-with-spell-and-suggest"} (-> solr-app wrap-spellcheck wrap-suggest)) suggestions (:suggestions (meta result)) spellcheck (:spellcheck (meta result))] (is (= 10 (count result))) (is (not-empty suggestions)) (is spellcheck)) ) (deftest test-spellchecker-Volve-files (let [docs (with-open [s (io/input-stream "test/resources/Volve/docs.json") reader (io/reader s)] (doall (cheshire/parse-stream reader true))) docs (for [doc docs] (assoc doc :fulltext (str/join "/n/n" (map #(str/replace % #"\d+::" "") (get doc :pagetext)))))] (doseq [doc docs] (add-document! doc)) (commit!) (is (= 2 (count docs))) (is (every? (fn [d] (not-empty (:fulltext d))) docs)) (is (= 2 (count (search* "Equinor" {:df "fulltext"})))) (when (not (is (= 1 (count (search* "Equinor" {:df "word"}))))) (let [edocs (search* "Equinor" {:df "word"})] (doseq [doc edocs] (println (format "Found Equinor in doc id %s" (:id doc))))) ) (let [result (search* "Equiner" {:df "fulltext" :request-handler "/spell"} (wrap-spellcheck solr-app)) spellcheck (:spellcheck (meta result))] (println (format "Corrected Equiner to %s" (:collated-result spellcheck))) (is (empty? result)) (is (= {:collated-result "Equinor" :is-correctly-spelled? false :alternatives {"Equiner" {:num-found 1 :original-frequency 0 :start-offset 0 :end-offset 7 :alternatives ["Equinor"] :alternative-frequencies [1]}}} spellcheck))) (let [result (search* "Equiner" {:df "pagetext" :request-handler "/spell-mv"} (wrap-spellcheck solr-app)) spellcheck (:spellcheck (meta result))] (println (format "Corrected Equiner to %s" (:collated-result spellcheck))) (is (empty? result)) (is (= {:collated-result "Equinor" :is-correctly-spelled? false :alternatives {"Equiner" {:num-found 1 :original-frequency 0 :start-offset 0 :end-offset 7 :alternatives ["Equinor"] :alternative-frequencies [1]}}} spellcheck))) )) (deftest test-suggester (let [tags_1 ["drilling operation" "drilling fluids and materials" "drilling fluid chemistry" "drilling fluid property" "drilling fluid formulation" "drilling fluid selection and formulation" "drilling equipment" "drilling fluid management & disposal"] tags_2 ["drillstem testing" "drillstem/well testing"]] (doseq [i (range 10)] (add-document! {:suggestion tags_1 :client "drilling" :type "PDF" :id (str "doc" i)})) (doseq [i (range 10 20)] (add-document! {:suggestion tags_2 :client "testing" :type "PDF" :id (str "doc" i)})) (commit!) (let [result (search* "dril" {:df "fulltext" :request-handler "/suggest" :suggest.cfq "drilling" :suggest.build true} (-> solr-app (wrap-suggest :suggester-name "context_suggest_mv"))) suggestions (map :term (:suggestions (meta result)))] (is (= suggestions (map :term '({:term "drilling equipment", :weight 0} {:term "drilling fluid chemistry", :weight 0} {:term "drilling fluid formulation", :weight 0} {:term "drilling fluid management & disposal", :weight 0} {:term "drilling fluid property", :weight 0} {:term "drilling fluid selection and formulation", :weight 0} {:term "drilling fluids and materials", :weight 0} {:term "drilling operation", :weight 0})))) #_(clojure.pprint/pprint (meta result))) (let [result (search* "dril" {:df "fulltext" :request-handler "/suggest" :suggest.cfq "testing" :suggest.build true} (-> solr-app (wrap-suggest :suggester-name "context_suggest_mv"))) suggestions (map :term (:suggestions (meta result)))] (is (= suggestions (map :term '({:term "drillstem testing", :weight 0} {:term "drillstem/well testing", :weight 0})))) #_(clojure.pprint/pprint (meta result))) (let [result (search* "dril" {:df "fulltext" :request-handler "/suggest" :suggest.cfg "testing OR drilling" :suggest.build true} (-> solr-app (wrap-suggest :suggester-name "context_suggest_mv"))) suggestions (map :term (:suggestions (meta result)))] (is (= suggestions (map :term '({:term "drilling equipment", :weight 0} {:term "drilling fluid chemistry", :weight 0} {:term "drilling fluid formulation", :weight 0} {:term "drilling fluid management & disposal", :weight 0} {:term "drilling fluid property", :weight 0} {:term "drilling fluid selection and formulation", :weight 0} {:term "drilling fluids and materials", :weight 0} {:term "drilling operation", :weight 0} {:term "drillstem testing", :weight 0} {:term "drillstem/well testing", :weight 0})))) #_(clojure.pprint/pprint (meta result))))) (deftest test-id-number-search (add-document! {:id "doc0" :type "LAS File" :pagetext ["UWI . 12-345-67890 : UWI or API of well" "API . 0987654321 : API 10" "API . 314159265358 : API 12" "API . 27-182-818284590 : API 14 "]}) (commit!) (are [match-count query] (= match-count (count (search* query {:df "pagetext"}))) 1 "1234567890" ;; Finds text with embedded dashes 0 "09-876-54321" ;; Fails to find text without embedded dashes if we search w/ dashes. 1 "0987654321" ;; Matches literal text. 1 "27182818284590" 1 "27182818284*" ;; Wildcards work inside tokens. 1 "12-345-67890" ;; Matches dashed text if we search with dashed text. ) (is (= 1 (count (search* "1234567890" {:df "pagetext"})) )) )
67171
(ns clojure-solr-test (:require [clojure.pprint] [clojure.java.io :as io] [clojure.string :as str]) (:import (java.util.jar Manifest)) (:import (org.apache.solr.client.solrj.embedded EmbeddedSolrServer)) (:import (org.apache.solr.core CoreContainer)) (:require [clj-time.core :as t]) (:require [clj-time.coerce :as tcoerce]) (:require [cheshire.core :as cheshire]) (:use [clojure.test]) (:use [clojure-solr]) (:use [clojure-solr.security]) (:use [clojure-solr.schema]) (:import [java.nio.charset StandardCharsets] [org.apache.commons.codec.binary Base64])) (defn get-solr-home-dir [] (let [version (get-solr-version)] (str "test-files/solr-" (second (re-matches #"(\d+)\..*" version))))) ;; from: https://gist.github.com/edw/5128978 (defn delete-recursively [fname] (let [func (fn [func f] (when (.isDirectory f) (doseq [f2 (.listFiles f)] (func func f2))) (try (clojure.java.io/delete-file f) (catch Exception _)))] (func func (clojure.java.io/file fname)))) (defn solr-server-fixture [f] (let [home-dir (get-solr-home-dir)] (delete-recursively (str home-dir "/data")) (System/setProperty "solr.solr.home" home-dir) (System/setProperty "solr.dist.dir" (str (System/getProperty "user.dir") "/test-files/dist")) (let [[_ major minor :as version] (re-matches #"(\d+)\.(\d+)\..*" (get-solr-version)) major (Integer/parseInt major) minor (Integer/parseInt minor)] (println (format "This is solr version %s" (first version))) (when (and (= major 7) (>= minor 4)) ;; https://issues.apache.org/jira/browse/SOLR-12858 (println "Using get as default method due to issue SOLR-12858") (set-default-method! :get) )) (with-connection (connect nil nil {:type EmbeddedSolrServer :core "clojure-solr" :home-dir (get-solr-home-dir)}) (f)))) (use-fixtures :each solr-server-fixture) (def sample-doc {:id "1" :type "pdf" :title "my title" :fulltext "my fulltext" :numeric 10 :updated (tcoerce/to-date (t/date-time 2015 02 27)) :terms ["Vocabulary 1/Term A" "Vocabulary 1/Term B" "Vocabulary 2/Term X/Term Y"]}) (deftest test-add-doc-with-lazyseq (add-document! {:id 2 :type "pdf" :related_s_mv (cheshire/parse-string "[\"abc\",\"def\"]")}) (commit!) (let [result (first (search "*" :facet-filters [{:name "id" :value "2"}] :df "fulltext"))] (is result) (is (vector? (:related_s_mv result))) (is (= #{"abc" "def"} (set (:related_s_mv result))))) ) (deftest test-add-document! (do (add-document! sample-doc) (commit!)) (is (= sample-doc (dissoc (first (search "my" :df "fulltext")) :_version_ :word))) (is (= {:start 0 :rows-set 1 :rows-total 1} (select-keys (meta (search "my" :df "fulltext")) [:start :rows-set :rows-total]))) (is (= [{:name "terms" :values [{:value "Vocabulary 1" :split-path ["Vocabulary 1"] :title "Vocabulary 1" :depth 1 :count 1} {:value "Vocabulary 1/Term A" :split-path ["Vocabulary 1" "Term A"] :title "Term A" :depth 2 :count 1} {:value "Vocabulary 1/Term B" :split-path ["Vocabulary 1" "Term B"] :title "Term B" :depth 2 :count 1} {:value "Vocabulary 2" :split-path ["Vocabulary 2"] :title "Vocabulary 2" :depth 1 :count 1} {:value "Vocabulary 2/Term X" :split-path ["Vocabulary 2" "Term X"] :title "Term X" :depth 2 :count 1} {:value "Vocabulary 2/Term X/Term Y" :split-path ["Vocabulary 2" "Term X" "Term Y"] :title "Term Y" :depth 3 :count 1}]}] (:facet-fields (meta (search "my" :facet-fields [:terms] :facet-hier-sep #"/" :df "fulltext")))))) (deftest test-update-document! (do (add-document! sample-doc) (commit!)) (atomically-update! 1 :id [{:attribute :title :func :set :value "my new title"}]) (commit!) (let [search-result (search "my" :df "fulltext")] (is (= (get (first search-result) :title) "my new title")))) (deftest test-quoted-search (do (add-document! sample-doc) (commit!)) (is (= sample-doc (dissoc (first (search "\"my fulltext\"" :df "fulltext")) :_version_ :word))) (is (empty? (search "\"fulltext my\"" :df "fulltext")))) (deftest test-quoted-search-mw (do (add-document! sample-doc) (commit!)) (is (= sample-doc (dissoc (first (search*-with-middleware "\"my fulltext\"" {:df "fulltext"})) :_version_ :word))) (is (empty? (search*-with-middleware "\"fulltext my\"" {:df "fulltext"})))) (deftest test-facet-query (let [query->map (fn [s] (let [params (str/split s #"&")] (into {} (map (fn [pair] (str/split pair #"=")) params))))] (do (add-document! sample-doc) (commit!)) (is (= [{:name "terms" :value "Vocabulary 1" :count 1}] (:facet-queries (meta (search "my" :facet-queries [{:name "terms" :value "Vocabulary 1"}] :df "fulltext"))))) (is (= (query->map "q=my&df=fulltext&facet-queries={:name+\"terms\",+:value+\"Vocabulary+1\"}&facet.query={!raw+f%3Dterms}Vocabulary+1&facet=true&facet.mincount=1") (query->map (search "my" :just-return-query? true :facet-queries [{:name "terms" :value "Vocabulary 1"}] :df "fulltext")))))) (deftest test-facet-prefix (do (add-document! sample-doc) (add-document! (assoc sample-doc :id "2" :numeric 11)) (add-document! (assoc sample-doc :id "3" :numeric 11)) (add-document! (assoc sample-doc :id "4" :numeric 15)) (add-document! (assoc sample-doc :id "5" :numeric 8)) (commit!)) (let [result (meta (search "my" :facet-fields [{:name "terms" :prefix "Voc"}] :df "fulltext"))] (is (not (empty? (:facet-fields result))))) (let [result (meta (search "my" :facet-fields [{:name "terms" :prefix "Vocabulary 1"}] :df "fulltext"))] (is (not (empty? (:facet-fields result)))) (is (= 3 (count (-> result :facet-fields first :values)))) (is (every? #(.startsWith (:value %) "Vocabulary 1") (-> result :facet-fields first :values)))) (let [result (meta (search "my" :facet-fields [{:name "terms" :prefix "Vocabulary 1" :result-formatter #(update-in % [:value] clojure.string/lower-case)}] :df "fulltext"))] (is (not (empty? (:facet-fields result)))) (is (= 3 (count (-> result :facet-fields first :values)))) (is (every? #(.startsWith (:value %) "vocabulary 1") (-> result :facet-fields first :values))))) (deftest test-facet-ranges (do (add-document! sample-doc) (add-document! (assoc sample-doc :id "2" :numeric 11)) (add-document! (assoc sample-doc :id "3" :numeric 11)) (add-document! (assoc sample-doc :id "4" :numeric 15)) (add-document! (assoc sample-doc :id "5" :numeric 8)) (commit!)) (let [result (meta (search "my" :facet-numeric-ranges [{:field "numeric" :start (Integer. 9) :end (Integer. 12) :gap (Integer. 3) :others ["before" "after"] :include "lower" :hardend false}] :facet-date-ranges [{:field "updated" :start (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 26) (t/time-zone-for-id "America/Chicago"))) :end (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 28) (t/time-zone-for-id "America/Chicago"))) :gap "+1DAY" :timezone (t/time-zone-for-id "America/Chicago") :others ["before" "after"]}] :df "fulltext"))] (is (= {:name "numeric", :values [{:count 1, :value "[* TO 9}", :min-inclusive nil, :max-noninclusive 9} {:max-noninclusive 12, :min-inclusive 9, :value "[9 TO 12}", :count 3} {:count 1, :value "[12 TO *]", :min-inclusive 12, :max-noninclusive nil}], :start 9, :end 12, :gap 3, :before 1, :after 1} (some #(and (= (:name %) "numeric") %) (:facet-range-fields result)))) (is (= {:name "updated" :values [{:min-inclusive (tcoerce/to-date "2015-02-26T06:00:00Z") :max-noninclusive (tcoerce/to-date "2015-02-27T06:00:00Z") :value "[2015-02-26T06:00:00Z TO 2015-02-27T06:00:00Z}", :count 5}] :start (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 26) (t/time-zone-for-id "America/Chicago"))) :end (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 28) (t/time-zone-for-id "America/Chicago"))) :gap "+1DAY" :before 0 :after 0} (first (filter #(= (:name %) "updated") (:facet-range-fields result))))))) (deftest test-pivot-faceting (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (commit!) (let [result (meta (search "my" :df "fulltext" :rows 0 :facet-date-ranges [{:field "updated" :tag "ts" :start (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 26) (t/time-zone-for-id "America/Chicago"))) :end (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 28) (t/time-zone-for-id "America/Chicago"))) :gap "+1DAY" :timezone (t/time-zone-for-id "America/Chicago") :others ["before" "after"]}] :facet-pivot-fields ["{!range=ts}type"])) pivot-fields (:facet-pivot-fields result)] (is (= 1 (count pivot-fields))) (is (get pivot-fields "type")) (is (= 2 (count (get pivot-fields "type")))) (is (= 1 (count (get-in pivot-fields ["type" :ranges "docx" "updated"])))) (is (= 1 (:count (first (get-in pivot-fields ["type" :ranges "docx" "updated"]))))) (is (= 1 (count (get-in pivot-fields ["type" :ranges "pdf" "updated"])))) (is (= 1 (:count (first (get-in pivot-fields ["type" :ranges "pdf" "updated"]))))) #_(clojure.pprint/pprint (:facet-pivot-fields result)))) (deftest test-luke-schema (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (commit!) (binding [*qf* "fulltext"] (let [fields (get-fields-via-luke)] (is (not-empty fields)) (is (map? (get fields "fulltext"))) (is (set? (get-in fields ["fulltext" :schema])))))) (deftest test-edismax-disjunction (add-document! (assoc sample-doc :id 1 :fulltext "This is a clinical trial.")) (add-document! (assoc sample-doc :id 2 :fulltext "This is a clinical study.")) (add-document! (assoc sample-doc :id 3 :fulltext "This is a clinical trial and a clinical study.")) (commit!) (let [ct (search* "\"clinical trial\"" {:df "fulltext" :defType "edismax" :fl "id"}) cs (search* "\"clinical study\"" {:df "fulltext" :defType "edismax" :fl "id"}) cts (search* "(\"clinical trial\" OR \"clinical study\")" {:df "fulltext" :defType "edismax" :fl "id" }) cts-plus (search* "+(\"clinical trial\" OR \"clinical study\")" {:df "fulltext" :defType "edismax" :fl "id" }) cts3 (search* "+(\"clinical trial\" OR \"clinical study\" OR \"foo baz\")" {:df "fulltext" :defType "edismax" :fl "id"}) ] (is (= 2 (count ct))) (is (= #{"1" "3"} (set (map :id ct)))) (is (= 2 (count cs))) (is (= #{"2" "3"} (set (map :id cs)))) (is (= 3 (count cts))) (is (= 3 (count cts-plus))) (is (= 3 (count cts3))) )) (deftest test-exclude-filter-faceting (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (commit!) (let [docs (search "my" :df "fulltext" :facet-filters [{:name "type" :value "pdf" :full-formatter format-standard-filter-query :tag "type"}] :facet-fields [{:name "type" :ex "type"}]) result (meta docs) facet-fields (:facet-fields result)] (is (= 1 (count docs))) (is (= 1 (count facet-fields))) (is (some #(= "type" (:name %)) facet-fields)) (is (= 2 (count (:values (first facet-fields))))) (let [type-facet (group-by :value (:values (first facet-fields)))] (is (= 1 (:count (first (get type-facet "pdf"))))) (is (= 1 (:count (first (get type-facet "docx")))))))) (deftest test-exclude-filter-faceting-complex (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (add-document! (assoc sample-doc :id 3 :type "pptx")) (commit!) (let [docs (search "my" :df "fulltext" :facet-filters [{:name "type" :value "{!tag=type}(type:pdf OR type:docx)" :full-formatter #(:value %) :tag "type"}] :facet-fields [{:name "type" :ex "type"}]) result (meta docs) facet-fields (:facet-fields result)] (is (= 2 (count docs))) (is (= 1 (count facet-fields))) (is (some #(= "type" (:name %)) facet-fields)) (is (= 3 (count (:values (first facet-fields))))) (let [type-facet (group-by :value (:values (first facet-fields)))] (is (= 1 (:count (first (get type-facet "pptx"))))) (is (= 1 (:count (first (get type-facet "pdf"))))) (is (= 1 (:count (first (get type-facet "docx")))))))) (deftest test-solr-npe-from-bad-query (clojure.pprint/pprint (meta (search "*:*" :df "fulltext" :debugQuery true :defType "edismax" :facet-filters [{:name "complex" :value "(source:SemanticScholar%20Commercial%20Use%20Subset AND type:application/json;schema=semantic-scholar)" :formatter (fn [_ value] value)}] :facet-fields [{:name "type" :ex "type"}])))) (deftest test-make-security-json-data (let [data (make-security-data [{:user "i2kweb" :password <PASSWORD> :role "query"} {:user "i2kconduit-db" :role "upload"}] [{:name "read" :role "*"} {:name "schema-read" :role "*"} {:name "update" :role "upload"} {:name "health" :role "health" :path "/admin/info/system" :methods ["GET"] :collection ""}])] (is (:credentials data)) (is (:authorization data)) (is (:authentication data)) (is (= (last (get-in data [:authorization :permissions])) {:role "health" :name "health" :methods ["GET"] :path "/admin/info/system" :collection nil})) (is (get-in data [:credentials "i2kweb" :hashed-password])) (is (get-in data [:credentials "i2kweb" :salt])) (is (get-in data [:credentials "i2kweb" :cleartext-password])) (is (= (get-in data [:credentials "i2kweb" :hashed-password]) (:hashed-password (generate-salted-hash (.getBytes (get-in data [:credentials "i2kweb" :cleartext-password]) StandardCharsets/UTF_8) (Base64/decodeBase64 (get-in data [:credentials "i2kweb" :salt])))))))) (deftest test-delete-doc-by-id (add-document! sample-doc) (commit!) (let [update-response (delete-id! "1") status (.getStatus update-response)] (is (= status 0)))) (deftest test-delete-doc-by-query (add-document! sample-doc) (commit!) (let [update-response (delete-query! "title:\"my title\"") status (.getStatus update-response) ] (is (= status 0)))) (deftest test-query-boolean-filter (add-document! {:id 1 :boolean_b true :type "pdf"}) (commit!) (is (= (count (search "*:*" :defType "edismax" :qf "title fulltext")) 1)) (is (= 1 (some #(and (= (:value %) "true") (:count %)) (:values (first (:facet-fields (meta (search "*:*" :defType "edismax" :qf "title fulltext" :facet-fields ["boolean_b"])))))))) (is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "true" :formatter format-standard-filter-query}] :qf "title fulltext" :defType "edismax")) 1)) ;; raw queries against boolean values apparently don't work correctly. #_(is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "true" :formatter format-raw-query}] :qf "title fulltext" )) 1)) #_(is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "true" :formatter format-raw-query}] :qf "title fulltext" :defType "edismax")) 1)) #_(is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "TRUE" :formatter format-raw-query}] :qf "title fulltext" :defType "edismax")) 1)) (clojure.pprint/pprint (meta (search "*:*" :facet-filters [{:name "boolean_b" :value "TRUE" :formatter format-raw-query}] :debugQuery true :qf "title fulltext" :defType "edismax"))) (clojure.pprint/pprint (meta (search "*:*" :facet-filters [{:name "boolean_b" :value true :formatter format-raw-query}] :debugQuery true :qf "title fulltext" :defType "edismax"))) (clojure.pprint/pprint (first (search "*:*" :facet-filters [{:name "boolean_b" :value true :formatter format-standard-filter-query}] :debugQuery true :qf "title fulltext" :defType "edismax"))) (clojure.pprint/pprint (meta (search "*:*" :facet-filters [{:name "boolean_b" :value true :formatter format-standard-filter-query}] :debugQuery true :qf "title fulltext" :defType "edismax")))) (deftest test-spellchecker (doseq [i (range 10)] (add-document! {:id i :type "Web Page" :fulltext "Many of the parameters relate to how this spell checker should query the index for term suggestions. The distanceMeasure defines the metric to use during the spell check query. The value \"internal\" uses the default Levenshtein metric, which is the same metric used with the other spell checker implementations."})) (commit!) (let [result (search* "<NAME>" {:df "fulltext" :request-handler "/suggest"} (wrap-suggest solr-app)) suggestion (:term (first (:suggestions (meta result))))] (println (format "Best suggestion for \"<NAME>\": %s" suggestion)) (is (= suggestion "<NAME>venshtein"))) (let [result (search* "<NAME>" {:df "fulltext" :request-handler "/suggest" :suggest.buildAll true } (-> solr-app (wrap-suggest :suggester-name ["suggest" "context_suggest"]))) suggestions (:suggestions (meta result))] (clojure.pprint/pprint suggestions)) (let [result (search* "<NAME>" {:df "fulltext" :request-handler "/spell"} (wrap-spellcheck solr-app)) spellcheck (:spellcheck (meta result))] (println (format "Corrected <NAME>venstein to %s" (:collated-result spellcheck))) (is (= {:collated-result "<NAME>ein" :is-correctly-spelled? false :alternatives {"<NAME>" {:num-found 1 :original-frequency 0 :start-offset 0 :end-offset 10 :alternatives ["Levenshtein"] :alternative-frequencies [10]}}} spellcheck))) (let [result (search* "<NAME>hte*" {:df "fulltext" :request-handler "/select-with-spell-and-suggest"} (-> solr-app wrap-spellcheck wrap-suggest)) suggestions (:suggestions (meta result)) spellcheck (:spellcheck (meta result))] (is (= 10 (count result))) (is (not-empty suggestions)) (is spellcheck)) ) (deftest test-spellchecker-Volve-files (let [docs (with-open [s (io/input-stream "test/resources/Volve/docs.json") reader (io/reader s)] (doall (cheshire/parse-stream reader true))) docs (for [doc docs] (assoc doc :fulltext (str/join "/n/n" (map #(str/replace % #"\d+::" "") (get doc :pagetext)))))] (doseq [doc docs] (add-document! doc)) (commit!) (is (= 2 (count docs))) (is (every? (fn [d] (not-empty (:fulltext d))) docs)) (is (= 2 (count (search* "Equinor" {:df "fulltext"})))) (when (not (is (= 1 (count (search* "Equinor" {:df "word"}))))) (let [edocs (search* "Equinor" {:df "word"})] (doseq [doc edocs] (println (format "Found Equinor in doc id %s" (:id doc))))) ) (let [result (search* "Equiner" {:df "fulltext" :request-handler "/spell"} (wrap-spellcheck solr-app)) spellcheck (:spellcheck (meta result))] (println (format "Corrected Equiner to %s" (:collated-result spellcheck))) (is (empty? result)) (is (= {:collated-result "Equinor" :is-correctly-spelled? false :alternatives {"Equiner" {:num-found 1 :original-frequency 0 :start-offset 0 :end-offset 7 :alternatives ["Equinor"] :alternative-frequencies [1]}}} spellcheck))) (let [result (search* "Equiner" {:df "pagetext" :request-handler "/spell-mv"} (wrap-spellcheck solr-app)) spellcheck (:spellcheck (meta result))] (println (format "Corrected Equiner to %s" (:collated-result spellcheck))) (is (empty? result)) (is (= {:collated-result "Equinor" :is-correctly-spelled? false :alternatives {"Equiner" {:num-found 1 :original-frequency 0 :start-offset 0 :end-offset 7 :alternatives ["Equinor"] :alternative-frequencies [1]}}} spellcheck))) )) (deftest test-suggester (let [tags_1 ["drilling operation" "drilling fluids and materials" "drilling fluid chemistry" "drilling fluid property" "drilling fluid formulation" "drilling fluid selection and formulation" "drilling equipment" "drilling fluid management & disposal"] tags_2 ["drillstem testing" "drillstem/well testing"]] (doseq [i (range 10)] (add-document! {:suggestion tags_1 :client "drilling" :type "PDF" :id (str "doc" i)})) (doseq [i (range 10 20)] (add-document! {:suggestion tags_2 :client "testing" :type "PDF" :id (str "doc" i)})) (commit!) (let [result (search* "dril" {:df "fulltext" :request-handler "/suggest" :suggest.cfq "drilling" :suggest.build true} (-> solr-app (wrap-suggest :suggester-name "context_suggest_mv"))) suggestions (map :term (:suggestions (meta result)))] (is (= suggestions (map :term '({:term "drilling equipment", :weight 0} {:term "drilling fluid chemistry", :weight 0} {:term "drilling fluid formulation", :weight 0} {:term "drilling fluid management & disposal", :weight 0} {:term "drilling fluid property", :weight 0} {:term "drilling fluid selection and formulation", :weight 0} {:term "drilling fluids and materials", :weight 0} {:term "drilling operation", :weight 0})))) #_(clojure.pprint/pprint (meta result))) (let [result (search* "dril" {:df "fulltext" :request-handler "/suggest" :suggest.cfq "testing" :suggest.build true} (-> solr-app (wrap-suggest :suggester-name "context_suggest_mv"))) suggestions (map :term (:suggestions (meta result)))] (is (= suggestions (map :term '({:term "drillstem testing", :weight 0} {:term "drillstem/well testing", :weight 0})))) #_(clojure.pprint/pprint (meta result))) (let [result (search* "dril" {:df "fulltext" :request-handler "/suggest" :suggest.cfg "testing OR drilling" :suggest.build true} (-> solr-app (wrap-suggest :suggester-name "context_suggest_mv"))) suggestions (map :term (:suggestions (meta result)))] (is (= suggestions (map :term '({:term "drilling equipment", :weight 0} {:term "drilling fluid chemistry", :weight 0} {:term "drilling fluid formulation", :weight 0} {:term "drilling fluid management & disposal", :weight 0} {:term "drilling fluid property", :weight 0} {:term "drilling fluid selection and formulation", :weight 0} {:term "drilling fluids and materials", :weight 0} {:term "drilling operation", :weight 0} {:term "drillstem testing", :weight 0} {:term "drillstem/well testing", :weight 0})))) #_(clojure.pprint/pprint (meta result))))) (deftest test-id-number-search (add-document! {:id "doc0" :type "LAS File" :pagetext ["UWI . 12-345-67890 : UWI or API of well" "API . 0987654321 : API 10" "API . 314159265358 : API 12" "API . 27-182-818284590 : API 14 "]}) (commit!) (are [match-count query] (= match-count (count (search* query {:df "pagetext"}))) 1 "1234567890" ;; Finds text with embedded dashes 0 "09-876-54321" ;; Fails to find text without embedded dashes if we search w/ dashes. 1 "0987654321" ;; Matches literal text. 1 "27182818284590" 1 "27182818284*" ;; Wildcards work inside tokens. 1 "12-345-67890" ;; Matches dashed text if we search with dashed text. ) (is (= 1 (count (search* "1234567890" {:df "pagetext"})) )) )
true
(ns clojure-solr-test (:require [clojure.pprint] [clojure.java.io :as io] [clojure.string :as str]) (:import (java.util.jar Manifest)) (:import (org.apache.solr.client.solrj.embedded EmbeddedSolrServer)) (:import (org.apache.solr.core CoreContainer)) (:require [clj-time.core :as t]) (:require [clj-time.coerce :as tcoerce]) (:require [cheshire.core :as cheshire]) (:use [clojure.test]) (:use [clojure-solr]) (:use [clojure-solr.security]) (:use [clojure-solr.schema]) (:import [java.nio.charset StandardCharsets] [org.apache.commons.codec.binary Base64])) (defn get-solr-home-dir [] (let [version (get-solr-version)] (str "test-files/solr-" (second (re-matches #"(\d+)\..*" version))))) ;; from: https://gist.github.com/edw/5128978 (defn delete-recursively [fname] (let [func (fn [func f] (when (.isDirectory f) (doseq [f2 (.listFiles f)] (func func f2))) (try (clojure.java.io/delete-file f) (catch Exception _)))] (func func (clojure.java.io/file fname)))) (defn solr-server-fixture [f] (let [home-dir (get-solr-home-dir)] (delete-recursively (str home-dir "/data")) (System/setProperty "solr.solr.home" home-dir) (System/setProperty "solr.dist.dir" (str (System/getProperty "user.dir") "/test-files/dist")) (let [[_ major minor :as version] (re-matches #"(\d+)\.(\d+)\..*" (get-solr-version)) major (Integer/parseInt major) minor (Integer/parseInt minor)] (println (format "This is solr version %s" (first version))) (when (and (= major 7) (>= minor 4)) ;; https://issues.apache.org/jira/browse/SOLR-12858 (println "Using get as default method due to issue SOLR-12858") (set-default-method! :get) )) (with-connection (connect nil nil {:type EmbeddedSolrServer :core "clojure-solr" :home-dir (get-solr-home-dir)}) (f)))) (use-fixtures :each solr-server-fixture) (def sample-doc {:id "1" :type "pdf" :title "my title" :fulltext "my fulltext" :numeric 10 :updated (tcoerce/to-date (t/date-time 2015 02 27)) :terms ["Vocabulary 1/Term A" "Vocabulary 1/Term B" "Vocabulary 2/Term X/Term Y"]}) (deftest test-add-doc-with-lazyseq (add-document! {:id 2 :type "pdf" :related_s_mv (cheshire/parse-string "[\"abc\",\"def\"]")}) (commit!) (let [result (first (search "*" :facet-filters [{:name "id" :value "2"}] :df "fulltext"))] (is result) (is (vector? (:related_s_mv result))) (is (= #{"abc" "def"} (set (:related_s_mv result))))) ) (deftest test-add-document! (do (add-document! sample-doc) (commit!)) (is (= sample-doc (dissoc (first (search "my" :df "fulltext")) :_version_ :word))) (is (= {:start 0 :rows-set 1 :rows-total 1} (select-keys (meta (search "my" :df "fulltext")) [:start :rows-set :rows-total]))) (is (= [{:name "terms" :values [{:value "Vocabulary 1" :split-path ["Vocabulary 1"] :title "Vocabulary 1" :depth 1 :count 1} {:value "Vocabulary 1/Term A" :split-path ["Vocabulary 1" "Term A"] :title "Term A" :depth 2 :count 1} {:value "Vocabulary 1/Term B" :split-path ["Vocabulary 1" "Term B"] :title "Term B" :depth 2 :count 1} {:value "Vocabulary 2" :split-path ["Vocabulary 2"] :title "Vocabulary 2" :depth 1 :count 1} {:value "Vocabulary 2/Term X" :split-path ["Vocabulary 2" "Term X"] :title "Term X" :depth 2 :count 1} {:value "Vocabulary 2/Term X/Term Y" :split-path ["Vocabulary 2" "Term X" "Term Y"] :title "Term Y" :depth 3 :count 1}]}] (:facet-fields (meta (search "my" :facet-fields [:terms] :facet-hier-sep #"/" :df "fulltext")))))) (deftest test-update-document! (do (add-document! sample-doc) (commit!)) (atomically-update! 1 :id [{:attribute :title :func :set :value "my new title"}]) (commit!) (let [search-result (search "my" :df "fulltext")] (is (= (get (first search-result) :title) "my new title")))) (deftest test-quoted-search (do (add-document! sample-doc) (commit!)) (is (= sample-doc (dissoc (first (search "\"my fulltext\"" :df "fulltext")) :_version_ :word))) (is (empty? (search "\"fulltext my\"" :df "fulltext")))) (deftest test-quoted-search-mw (do (add-document! sample-doc) (commit!)) (is (= sample-doc (dissoc (first (search*-with-middleware "\"my fulltext\"" {:df "fulltext"})) :_version_ :word))) (is (empty? (search*-with-middleware "\"fulltext my\"" {:df "fulltext"})))) (deftest test-facet-query (let [query->map (fn [s] (let [params (str/split s #"&")] (into {} (map (fn [pair] (str/split pair #"=")) params))))] (do (add-document! sample-doc) (commit!)) (is (= [{:name "terms" :value "Vocabulary 1" :count 1}] (:facet-queries (meta (search "my" :facet-queries [{:name "terms" :value "Vocabulary 1"}] :df "fulltext"))))) (is (= (query->map "q=my&df=fulltext&facet-queries={:name+\"terms\",+:value+\"Vocabulary+1\"}&facet.query={!raw+f%3Dterms}Vocabulary+1&facet=true&facet.mincount=1") (query->map (search "my" :just-return-query? true :facet-queries [{:name "terms" :value "Vocabulary 1"}] :df "fulltext")))))) (deftest test-facet-prefix (do (add-document! sample-doc) (add-document! (assoc sample-doc :id "2" :numeric 11)) (add-document! (assoc sample-doc :id "3" :numeric 11)) (add-document! (assoc sample-doc :id "4" :numeric 15)) (add-document! (assoc sample-doc :id "5" :numeric 8)) (commit!)) (let [result (meta (search "my" :facet-fields [{:name "terms" :prefix "Voc"}] :df "fulltext"))] (is (not (empty? (:facet-fields result))))) (let [result (meta (search "my" :facet-fields [{:name "terms" :prefix "Vocabulary 1"}] :df "fulltext"))] (is (not (empty? (:facet-fields result)))) (is (= 3 (count (-> result :facet-fields first :values)))) (is (every? #(.startsWith (:value %) "Vocabulary 1") (-> result :facet-fields first :values)))) (let [result (meta (search "my" :facet-fields [{:name "terms" :prefix "Vocabulary 1" :result-formatter #(update-in % [:value] clojure.string/lower-case)}] :df "fulltext"))] (is (not (empty? (:facet-fields result)))) (is (= 3 (count (-> result :facet-fields first :values)))) (is (every? #(.startsWith (:value %) "vocabulary 1") (-> result :facet-fields first :values))))) (deftest test-facet-ranges (do (add-document! sample-doc) (add-document! (assoc sample-doc :id "2" :numeric 11)) (add-document! (assoc sample-doc :id "3" :numeric 11)) (add-document! (assoc sample-doc :id "4" :numeric 15)) (add-document! (assoc sample-doc :id "5" :numeric 8)) (commit!)) (let [result (meta (search "my" :facet-numeric-ranges [{:field "numeric" :start (Integer. 9) :end (Integer. 12) :gap (Integer. 3) :others ["before" "after"] :include "lower" :hardend false}] :facet-date-ranges [{:field "updated" :start (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 26) (t/time-zone-for-id "America/Chicago"))) :end (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 28) (t/time-zone-for-id "America/Chicago"))) :gap "+1DAY" :timezone (t/time-zone-for-id "America/Chicago") :others ["before" "after"]}] :df "fulltext"))] (is (= {:name "numeric", :values [{:count 1, :value "[* TO 9}", :min-inclusive nil, :max-noninclusive 9} {:max-noninclusive 12, :min-inclusive 9, :value "[9 TO 12}", :count 3} {:count 1, :value "[12 TO *]", :min-inclusive 12, :max-noninclusive nil}], :start 9, :end 12, :gap 3, :before 1, :after 1} (some #(and (= (:name %) "numeric") %) (:facet-range-fields result)))) (is (= {:name "updated" :values [{:min-inclusive (tcoerce/to-date "2015-02-26T06:00:00Z") :max-noninclusive (tcoerce/to-date "2015-02-27T06:00:00Z") :value "[2015-02-26T06:00:00Z TO 2015-02-27T06:00:00Z}", :count 5}] :start (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 26) (t/time-zone-for-id "America/Chicago"))) :end (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 28) (t/time-zone-for-id "America/Chicago"))) :gap "+1DAY" :before 0 :after 0} (first (filter #(= (:name %) "updated") (:facet-range-fields result))))))) (deftest test-pivot-faceting (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (commit!) (let [result (meta (search "my" :df "fulltext" :rows 0 :facet-date-ranges [{:field "updated" :tag "ts" :start (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 26) (t/time-zone-for-id "America/Chicago"))) :end (tcoerce/to-date (t/from-time-zone (t/date-time 2015 02 28) (t/time-zone-for-id "America/Chicago"))) :gap "+1DAY" :timezone (t/time-zone-for-id "America/Chicago") :others ["before" "after"]}] :facet-pivot-fields ["{!range=ts}type"])) pivot-fields (:facet-pivot-fields result)] (is (= 1 (count pivot-fields))) (is (get pivot-fields "type")) (is (= 2 (count (get pivot-fields "type")))) (is (= 1 (count (get-in pivot-fields ["type" :ranges "docx" "updated"])))) (is (= 1 (:count (first (get-in pivot-fields ["type" :ranges "docx" "updated"]))))) (is (= 1 (count (get-in pivot-fields ["type" :ranges "pdf" "updated"])))) (is (= 1 (:count (first (get-in pivot-fields ["type" :ranges "pdf" "updated"]))))) #_(clojure.pprint/pprint (:facet-pivot-fields result)))) (deftest test-luke-schema (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (commit!) (binding [*qf* "fulltext"] (let [fields (get-fields-via-luke)] (is (not-empty fields)) (is (map? (get fields "fulltext"))) (is (set? (get-in fields ["fulltext" :schema])))))) (deftest test-edismax-disjunction (add-document! (assoc sample-doc :id 1 :fulltext "This is a clinical trial.")) (add-document! (assoc sample-doc :id 2 :fulltext "This is a clinical study.")) (add-document! (assoc sample-doc :id 3 :fulltext "This is a clinical trial and a clinical study.")) (commit!) (let [ct (search* "\"clinical trial\"" {:df "fulltext" :defType "edismax" :fl "id"}) cs (search* "\"clinical study\"" {:df "fulltext" :defType "edismax" :fl "id"}) cts (search* "(\"clinical trial\" OR \"clinical study\")" {:df "fulltext" :defType "edismax" :fl "id" }) cts-plus (search* "+(\"clinical trial\" OR \"clinical study\")" {:df "fulltext" :defType "edismax" :fl "id" }) cts3 (search* "+(\"clinical trial\" OR \"clinical study\" OR \"foo baz\")" {:df "fulltext" :defType "edismax" :fl "id"}) ] (is (= 2 (count ct))) (is (= #{"1" "3"} (set (map :id ct)))) (is (= 2 (count cs))) (is (= #{"2" "3"} (set (map :id cs)))) (is (= 3 (count cts))) (is (= 3 (count cts-plus))) (is (= 3 (count cts3))) )) (deftest test-exclude-filter-faceting (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (commit!) (let [docs (search "my" :df "fulltext" :facet-filters [{:name "type" :value "pdf" :full-formatter format-standard-filter-query :tag "type"}] :facet-fields [{:name "type" :ex "type"}]) result (meta docs) facet-fields (:facet-fields result)] (is (= 1 (count docs))) (is (= 1 (count facet-fields))) (is (some #(= "type" (:name %)) facet-fields)) (is (= 2 (count (:values (first facet-fields))))) (let [type-facet (group-by :value (:values (first facet-fields)))] (is (= 1 (:count (first (get type-facet "pdf"))))) (is (= 1 (:count (first (get type-facet "docx")))))))) (deftest test-exclude-filter-faceting-complex (add-document! sample-doc) (add-document! (assoc sample-doc :id 2 :type "docx")) (add-document! (assoc sample-doc :id 3 :type "pptx")) (commit!) (let [docs (search "my" :df "fulltext" :facet-filters [{:name "type" :value "{!tag=type}(type:pdf OR type:docx)" :full-formatter #(:value %) :tag "type"}] :facet-fields [{:name "type" :ex "type"}]) result (meta docs) facet-fields (:facet-fields result)] (is (= 2 (count docs))) (is (= 1 (count facet-fields))) (is (some #(= "type" (:name %)) facet-fields)) (is (= 3 (count (:values (first facet-fields))))) (let [type-facet (group-by :value (:values (first facet-fields)))] (is (= 1 (:count (first (get type-facet "pptx"))))) (is (= 1 (:count (first (get type-facet "pdf"))))) (is (= 1 (:count (first (get type-facet "docx")))))))) (deftest test-solr-npe-from-bad-query (clojure.pprint/pprint (meta (search "*:*" :df "fulltext" :debugQuery true :defType "edismax" :facet-filters [{:name "complex" :value "(source:SemanticScholar%20Commercial%20Use%20Subset AND type:application/json;schema=semantic-scholar)" :formatter (fn [_ value] value)}] :facet-fields [{:name "type" :ex "type"}])))) (deftest test-make-security-json-data (let [data (make-security-data [{:user "i2kweb" :password PI:PASSWORD:<PASSWORD>END_PI :role "query"} {:user "i2kconduit-db" :role "upload"}] [{:name "read" :role "*"} {:name "schema-read" :role "*"} {:name "update" :role "upload"} {:name "health" :role "health" :path "/admin/info/system" :methods ["GET"] :collection ""}])] (is (:credentials data)) (is (:authorization data)) (is (:authentication data)) (is (= (last (get-in data [:authorization :permissions])) {:role "health" :name "health" :methods ["GET"] :path "/admin/info/system" :collection nil})) (is (get-in data [:credentials "i2kweb" :hashed-password])) (is (get-in data [:credentials "i2kweb" :salt])) (is (get-in data [:credentials "i2kweb" :cleartext-password])) (is (= (get-in data [:credentials "i2kweb" :hashed-password]) (:hashed-password (generate-salted-hash (.getBytes (get-in data [:credentials "i2kweb" :cleartext-password]) StandardCharsets/UTF_8) (Base64/decodeBase64 (get-in data [:credentials "i2kweb" :salt])))))))) (deftest test-delete-doc-by-id (add-document! sample-doc) (commit!) (let [update-response (delete-id! "1") status (.getStatus update-response)] (is (= status 0)))) (deftest test-delete-doc-by-query (add-document! sample-doc) (commit!) (let [update-response (delete-query! "title:\"my title\"") status (.getStatus update-response) ] (is (= status 0)))) (deftest test-query-boolean-filter (add-document! {:id 1 :boolean_b true :type "pdf"}) (commit!) (is (= (count (search "*:*" :defType "edismax" :qf "title fulltext")) 1)) (is (= 1 (some #(and (= (:value %) "true") (:count %)) (:values (first (:facet-fields (meta (search "*:*" :defType "edismax" :qf "title fulltext" :facet-fields ["boolean_b"])))))))) (is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "true" :formatter format-standard-filter-query}] :qf "title fulltext" :defType "edismax")) 1)) ;; raw queries against boolean values apparently don't work correctly. #_(is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "true" :formatter format-raw-query}] :qf "title fulltext" )) 1)) #_(is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "true" :formatter format-raw-query}] :qf "title fulltext" :defType "edismax")) 1)) #_(is (= (count (search "*:*" :facet-filters [{:name "boolean_b" :value "TRUE" :formatter format-raw-query}] :qf "title fulltext" :defType "edismax")) 1)) (clojure.pprint/pprint (meta (search "*:*" :facet-filters [{:name "boolean_b" :value "TRUE" :formatter format-raw-query}] :debugQuery true :qf "title fulltext" :defType "edismax"))) (clojure.pprint/pprint (meta (search "*:*" :facet-filters [{:name "boolean_b" :value true :formatter format-raw-query}] :debugQuery true :qf "title fulltext" :defType "edismax"))) (clojure.pprint/pprint (first (search "*:*" :facet-filters [{:name "boolean_b" :value true :formatter format-standard-filter-query}] :debugQuery true :qf "title fulltext" :defType "edismax"))) (clojure.pprint/pprint (meta (search "*:*" :facet-filters [{:name "boolean_b" :value true :formatter format-standard-filter-query}] :debugQuery true :qf "title fulltext" :defType "edismax")))) (deftest test-spellchecker (doseq [i (range 10)] (add-document! {:id i :type "Web Page" :fulltext "Many of the parameters relate to how this spell checker should query the index for term suggestions. The distanceMeasure defines the metric to use during the spell check query. The value \"internal\" uses the default Levenshtein metric, which is the same metric used with the other spell checker implementations."})) (commit!) (let [result (search* "PI:NAME:<NAME>END_PI" {:df "fulltext" :request-handler "/suggest"} (wrap-suggest solr-app)) suggestion (:term (first (:suggestions (meta result))))] (println (format "Best suggestion for \"PI:NAME:<NAME>END_PI\": %s" suggestion)) (is (= suggestion "PI:NAME:<NAME>END_PIvenshtein"))) (let [result (search* "PI:NAME:<NAME>END_PI" {:df "fulltext" :request-handler "/suggest" :suggest.buildAll true } (-> solr-app (wrap-suggest :suggester-name ["suggest" "context_suggest"]))) suggestions (:suggestions (meta result))] (clojure.pprint/pprint suggestions)) (let [result (search* "PI:NAME:<NAME>END_PI" {:df "fulltext" :request-handler "/spell"} (wrap-spellcheck solr-app)) spellcheck (:spellcheck (meta result))] (println (format "Corrected PI:NAME:<NAME>END_PIvenstein to %s" (:collated-result spellcheck))) (is (= {:collated-result "PI:NAME:<NAME>END_PIein" :is-correctly-spelled? false :alternatives {"PI:NAME:<NAME>END_PI" {:num-found 1 :original-frequency 0 :start-offset 0 :end-offset 10 :alternatives ["Levenshtein"] :alternative-frequencies [10]}}} spellcheck))) (let [result (search* "PI:NAME:<NAME>END_PIhte*" {:df "fulltext" :request-handler "/select-with-spell-and-suggest"} (-> solr-app wrap-spellcheck wrap-suggest)) suggestions (:suggestions (meta result)) spellcheck (:spellcheck (meta result))] (is (= 10 (count result))) (is (not-empty suggestions)) (is spellcheck)) ) (deftest test-spellchecker-Volve-files (let [docs (with-open [s (io/input-stream "test/resources/Volve/docs.json") reader (io/reader s)] (doall (cheshire/parse-stream reader true))) docs (for [doc docs] (assoc doc :fulltext (str/join "/n/n" (map #(str/replace % #"\d+::" "") (get doc :pagetext)))))] (doseq [doc docs] (add-document! doc)) (commit!) (is (= 2 (count docs))) (is (every? (fn [d] (not-empty (:fulltext d))) docs)) (is (= 2 (count (search* "Equinor" {:df "fulltext"})))) (when (not (is (= 1 (count (search* "Equinor" {:df "word"}))))) (let [edocs (search* "Equinor" {:df "word"})] (doseq [doc edocs] (println (format "Found Equinor in doc id %s" (:id doc))))) ) (let [result (search* "Equiner" {:df "fulltext" :request-handler "/spell"} (wrap-spellcheck solr-app)) spellcheck (:spellcheck (meta result))] (println (format "Corrected Equiner to %s" (:collated-result spellcheck))) (is (empty? result)) (is (= {:collated-result "Equinor" :is-correctly-spelled? false :alternatives {"Equiner" {:num-found 1 :original-frequency 0 :start-offset 0 :end-offset 7 :alternatives ["Equinor"] :alternative-frequencies [1]}}} spellcheck))) (let [result (search* "Equiner" {:df "pagetext" :request-handler "/spell-mv"} (wrap-spellcheck solr-app)) spellcheck (:spellcheck (meta result))] (println (format "Corrected Equiner to %s" (:collated-result spellcheck))) (is (empty? result)) (is (= {:collated-result "Equinor" :is-correctly-spelled? false :alternatives {"Equiner" {:num-found 1 :original-frequency 0 :start-offset 0 :end-offset 7 :alternatives ["Equinor"] :alternative-frequencies [1]}}} spellcheck))) )) (deftest test-suggester (let [tags_1 ["drilling operation" "drilling fluids and materials" "drilling fluid chemistry" "drilling fluid property" "drilling fluid formulation" "drilling fluid selection and formulation" "drilling equipment" "drilling fluid management & disposal"] tags_2 ["drillstem testing" "drillstem/well testing"]] (doseq [i (range 10)] (add-document! {:suggestion tags_1 :client "drilling" :type "PDF" :id (str "doc" i)})) (doseq [i (range 10 20)] (add-document! {:suggestion tags_2 :client "testing" :type "PDF" :id (str "doc" i)})) (commit!) (let [result (search* "dril" {:df "fulltext" :request-handler "/suggest" :suggest.cfq "drilling" :suggest.build true} (-> solr-app (wrap-suggest :suggester-name "context_suggest_mv"))) suggestions (map :term (:suggestions (meta result)))] (is (= suggestions (map :term '({:term "drilling equipment", :weight 0} {:term "drilling fluid chemistry", :weight 0} {:term "drilling fluid formulation", :weight 0} {:term "drilling fluid management & disposal", :weight 0} {:term "drilling fluid property", :weight 0} {:term "drilling fluid selection and formulation", :weight 0} {:term "drilling fluids and materials", :weight 0} {:term "drilling operation", :weight 0})))) #_(clojure.pprint/pprint (meta result))) (let [result (search* "dril" {:df "fulltext" :request-handler "/suggest" :suggest.cfq "testing" :suggest.build true} (-> solr-app (wrap-suggest :suggester-name "context_suggest_mv"))) suggestions (map :term (:suggestions (meta result)))] (is (= suggestions (map :term '({:term "drillstem testing", :weight 0} {:term "drillstem/well testing", :weight 0})))) #_(clojure.pprint/pprint (meta result))) (let [result (search* "dril" {:df "fulltext" :request-handler "/suggest" :suggest.cfg "testing OR drilling" :suggest.build true} (-> solr-app (wrap-suggest :suggester-name "context_suggest_mv"))) suggestions (map :term (:suggestions (meta result)))] (is (= suggestions (map :term '({:term "drilling equipment", :weight 0} {:term "drilling fluid chemistry", :weight 0} {:term "drilling fluid formulation", :weight 0} {:term "drilling fluid management & disposal", :weight 0} {:term "drilling fluid property", :weight 0} {:term "drilling fluid selection and formulation", :weight 0} {:term "drilling fluids and materials", :weight 0} {:term "drilling operation", :weight 0} {:term "drillstem testing", :weight 0} {:term "drillstem/well testing", :weight 0})))) #_(clojure.pprint/pprint (meta result))))) (deftest test-id-number-search (add-document! {:id "doc0" :type "LAS File" :pagetext ["UWI . 12-345-67890 : UWI or API of well" "API . 0987654321 : API 10" "API . 314159265358 : API 12" "API . 27-182-818284590 : API 14 "]}) (commit!) (are [match-count query] (= match-count (count (search* query {:df "pagetext"}))) 1 "1234567890" ;; Finds text with embedded dashes 0 "09-876-54321" ;; Fails to find text without embedded dashes if we search w/ dashes. 1 "0987654321" ;; Matches literal text. 1 "27182818284590" 1 "27182818284*" ;; Wildcards work inside tokens. 1 "12-345-67890" ;; Matches dashed text if we search with dashed text. ) (is (= 1 (count (search* "1234567890" {:df "pagetext"})) )) )
[ { "context": "mbinatory logic - internals\n\n; Copyright (c) 2019 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 92, "score": 0.9998641610145569, "start": 78, "tag": "NAME", "value": "Burkhardt Renz" } ]
src/lwb/cl/impl.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Combinatory logic - internals ; Copyright (c) 2019 Burkhardt Renz, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.cl.impl (:refer-clojure :exclude [==]) (:require [clojure.walk :as walk] [clojure.spec.alpha :as s] [clojure.core.logic :refer :all] [clojure.set :as set] [lwb.nd.error :refer :all] [clojure.zip :as zip])) ; ----------------------------------------------------------------------------- ;; # Handling of parentheses (defn add-parens "Adds left-associative parentheses to a seq of symbols or subterms." [[first second & more]] (let [ret (list first second)] (if more (recur (list* ret more)) ret))) (defn rm-outer-parens "Removes all outer parens of a seq" [tseq] (if (= 1 (count tseq)) (if (seq? (first tseq)) (recur (first tseq)) tseq) tseq)) (defn max-parens-seq [seq] (walk/postwalk #(if (seq? %) (let [seq' (rm-outer-parens %)] (if (= 1 (count seq')) seq' (add-parens seq'))) %) seq)) (defn min-parens-seq [seq] (let [seqn (max-parens-seq seq)] (walk/postwalk #(if (seq? %) (let [f (first %)] (if (seq? f) (concat f (rest %)) %)) %) seqn))) ; ----------------------------------------------------------------------------- ;; # Logic relation for combinators (defn vars "The set of variables in `term`." [term] (->> (flatten term) (filter #(s/valid? :lwb.cl.spec/variable %)) (into #{}))) (defn gen-fresh-args "Vector of fresh variables for the relation to be constructed" [redex effect] (let [r-vars (vars redex) e-vars (vars effect)] (vec (set/union r-vars e-vars)))) (defn gen-cl-term' "Code from a sequence with all parentheses" [seqterm] (map (fn [item] (if (seq? item) (list* 'list (gen-cl-term' item)) (if (s/valid? :lwb.cl.spec/combinator item) (list 'quote item) item))) seqterm)) (defn gen-cl-term "Code from a term without all parentheses" [term] (let [seqterm (max-parens-seq (seq term)) result (gen-cl-term' seqterm)] (if (= 1 (count result)) (first result) (list* 'list result)))) (defn gen-cl-rel [redex effect] ;; both terms (let [fresh-args (gen-fresh-args redex effect) redex-term (gen-cl-term redex) effect-term (gen-cl-term effect)] (list 'fn (vector 'term 'q) (list 'fresh fresh-args (list '== 'term redex-term) (list '== 'q effect-term))))) ; ----------------------------------------------------------------------------- ;; # Arity of combinators (defn arity "Arity of redex" [redex] (if (and (= 1 (count redex)) (symbol? (first redex))) ; just one symbol 0 (loop [sterm (max-parens-seq (seq redex)) arity 0] (if (symbol? sterm) arity (recur (first sterm) (inc arity)))))) ; ----------------------------------------------------------------------------- ;; # Storage for combinators (def combinator-store (atom {})) (defn combs "The set of combinators in `term`." [term] (->> (flatten term) (filter #(s/valid? :lwb.cl.spec/combinator %)) (into #{}))) (defn combs-keys "The set of combinator keys in `term`." [term] (set (map keyword (combs term)))) (defn make-comb [redex effect nickname] (let [combs (combs redex) key (keyword (first combs))] (if-not key (throw (AssertionError. (str "Redex '" redex "' has no combinator!"))) (hash-map key {:redex redex :effect effect :arity (arity redex) :nickname nickname :logic-rel (binding [*ns* (find-ns 'lwb.cl.impl)] (eval (gen-cl-rel redex effect)))})))) (defn get-rule-fn "Get logic function from combinator store." [comb-key] (if-let [f (get-in @combinator-store [comb-key :logic-rel])] f (throw (ex-error (str "Combinator " comb-key " not defined."))))) (defn get-arity [comb-key] (get-in @combinator-store [comb-key :arity])) ; ----------------------------------------------------------------------------- ;; Application of logic relation for one-step expansion or reduction (defn apply' [rule-fn seqterm mode] (if (= mode :red) (run 1 [q] (rule-fn seqterm q)) (run 1 [q] (rule-fn q seqterm)))) (defn apply* [term rule-fn i mode] ;; Pre: term has max parentheses (let [counter (atom 0)] (walk/prewalk #(let [rep (apply' rule-fn % mode)] ;(println "replace " % " -> " rep) (if (and (not (vector? %)) (not-empty rep)) (if (= i (swap! counter inc)) (first rep) %) %)) term))) (defn reducible? "Is the given sterm reducible with combinator comb with arity arity?" [sterm comb arity] (loop [count 0 st sterm] (cond (= arity count) (if (= st comb) true false) ; test this first! (not (seq? st)) false ; don't test on list? since sterm may be a lazy seq! :else (recur (inc count) (first st))))) ;; an alternative check: (= comb (first (flatten sterm))) ; could be even faster, but not so selective (defn apply** "Lookup for first combinator in term and try to reduce" [sterm] (let [comb (->> (flatten sterm) (filter #(s/valid? :lwb.cl.spec/combinator %)) (first))] (when-not (nil? comb) (let [comb-key (keyword comb) rule-fn (get-rule-fn comb-key)] (first (apply' rule-fn sterm :red)))))) (defn apply-z "One-step reduction (with first combinator in sterm)" [sterm] (loop [loc (zip/seq-zip sterm)] (let [node (zip/node loc) new-node (if-let [r (apply** node)] r node) new? (not= new-node node) new-loc (if new? (zip/replace loc new-node) loc) new-state (if new? :stop) next-loc (zip/next new-loc)] (if (or (zip/end? loc) (= :stop new-state)) (zip/root new-loc) (recur next-loc))))) ; ----------------------------------------------------------------------------- ;; # Weak reduction (defn vec' [sterm] (if (symbol? sterm) [sterm] (vec sterm))) (defn weak-reduce "Reduce the `sterm`" [sterm counter limit cycle trace] (let [steps (atom [])] (loop [current-sterm sterm result {:reduced sterm :no-steps 0 :cycle :unknown :overrun false} counter counter] (if cycle (swap! steps conj current-sterm)) (let [red (apply-z current-sterm) ;; one step with apply found (when-not (= red current-sterm) red)] ;; reduced term found (if (and found trace) (println (str counter ": " (vec' (min-parens-seq found))))) (cond (nil? found) result ;; timeout? -> Exception, the result is never returned (.isInterrupted (Thread/currentThread)) (assoc result :result found :timeout true :no-steps counter) ;; overrun (>= counter limit 1) (assoc result :reduced found :no-steps counter :overrun true) ;; cycle (and cycle (some #(= found %) @steps)) (assoc result :reduced found :cycle true :steps @steps :no-steps counter) :else (recur found (assoc result :reduced found :no-steps counter) (inc counter)))))))
73365
; lwb Logic WorkBench -- Combinatory logic - internals ; Copyright (c) 2019 <NAME>, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.cl.impl (:refer-clojure :exclude [==]) (:require [clojure.walk :as walk] [clojure.spec.alpha :as s] [clojure.core.logic :refer :all] [clojure.set :as set] [lwb.nd.error :refer :all] [clojure.zip :as zip])) ; ----------------------------------------------------------------------------- ;; # Handling of parentheses (defn add-parens "Adds left-associative parentheses to a seq of symbols or subterms." [[first second & more]] (let [ret (list first second)] (if more (recur (list* ret more)) ret))) (defn rm-outer-parens "Removes all outer parens of a seq" [tseq] (if (= 1 (count tseq)) (if (seq? (first tseq)) (recur (first tseq)) tseq) tseq)) (defn max-parens-seq [seq] (walk/postwalk #(if (seq? %) (let [seq' (rm-outer-parens %)] (if (= 1 (count seq')) seq' (add-parens seq'))) %) seq)) (defn min-parens-seq [seq] (let [seqn (max-parens-seq seq)] (walk/postwalk #(if (seq? %) (let [f (first %)] (if (seq? f) (concat f (rest %)) %)) %) seqn))) ; ----------------------------------------------------------------------------- ;; # Logic relation for combinators (defn vars "The set of variables in `term`." [term] (->> (flatten term) (filter #(s/valid? :lwb.cl.spec/variable %)) (into #{}))) (defn gen-fresh-args "Vector of fresh variables for the relation to be constructed" [redex effect] (let [r-vars (vars redex) e-vars (vars effect)] (vec (set/union r-vars e-vars)))) (defn gen-cl-term' "Code from a sequence with all parentheses" [seqterm] (map (fn [item] (if (seq? item) (list* 'list (gen-cl-term' item)) (if (s/valid? :lwb.cl.spec/combinator item) (list 'quote item) item))) seqterm)) (defn gen-cl-term "Code from a term without all parentheses" [term] (let [seqterm (max-parens-seq (seq term)) result (gen-cl-term' seqterm)] (if (= 1 (count result)) (first result) (list* 'list result)))) (defn gen-cl-rel [redex effect] ;; both terms (let [fresh-args (gen-fresh-args redex effect) redex-term (gen-cl-term redex) effect-term (gen-cl-term effect)] (list 'fn (vector 'term 'q) (list 'fresh fresh-args (list '== 'term redex-term) (list '== 'q effect-term))))) ; ----------------------------------------------------------------------------- ;; # Arity of combinators (defn arity "Arity of redex" [redex] (if (and (= 1 (count redex)) (symbol? (first redex))) ; just one symbol 0 (loop [sterm (max-parens-seq (seq redex)) arity 0] (if (symbol? sterm) arity (recur (first sterm) (inc arity)))))) ; ----------------------------------------------------------------------------- ;; # Storage for combinators (def combinator-store (atom {})) (defn combs "The set of combinators in `term`." [term] (->> (flatten term) (filter #(s/valid? :lwb.cl.spec/combinator %)) (into #{}))) (defn combs-keys "The set of combinator keys in `term`." [term] (set (map keyword (combs term)))) (defn make-comb [redex effect nickname] (let [combs (combs redex) key (keyword (first combs))] (if-not key (throw (AssertionError. (str "Redex '" redex "' has no combinator!"))) (hash-map key {:redex redex :effect effect :arity (arity redex) :nickname nickname :logic-rel (binding [*ns* (find-ns 'lwb.cl.impl)] (eval (gen-cl-rel redex effect)))})))) (defn get-rule-fn "Get logic function from combinator store." [comb-key] (if-let [f (get-in @combinator-store [comb-key :logic-rel])] f (throw (ex-error (str "Combinator " comb-key " not defined."))))) (defn get-arity [comb-key] (get-in @combinator-store [comb-key :arity])) ; ----------------------------------------------------------------------------- ;; Application of logic relation for one-step expansion or reduction (defn apply' [rule-fn seqterm mode] (if (= mode :red) (run 1 [q] (rule-fn seqterm q)) (run 1 [q] (rule-fn q seqterm)))) (defn apply* [term rule-fn i mode] ;; Pre: term has max parentheses (let [counter (atom 0)] (walk/prewalk #(let [rep (apply' rule-fn % mode)] ;(println "replace " % " -> " rep) (if (and (not (vector? %)) (not-empty rep)) (if (= i (swap! counter inc)) (first rep) %) %)) term))) (defn reducible? "Is the given sterm reducible with combinator comb with arity arity?" [sterm comb arity] (loop [count 0 st sterm] (cond (= arity count) (if (= st comb) true false) ; test this first! (not (seq? st)) false ; don't test on list? since sterm may be a lazy seq! :else (recur (inc count) (first st))))) ;; an alternative check: (= comb (first (flatten sterm))) ; could be even faster, but not so selective (defn apply** "Lookup for first combinator in term and try to reduce" [sterm] (let [comb (->> (flatten sterm) (filter #(s/valid? :lwb.cl.spec/combinator %)) (first))] (when-not (nil? comb) (let [comb-key (keyword comb) rule-fn (get-rule-fn comb-key)] (first (apply' rule-fn sterm :red)))))) (defn apply-z "One-step reduction (with first combinator in sterm)" [sterm] (loop [loc (zip/seq-zip sterm)] (let [node (zip/node loc) new-node (if-let [r (apply** node)] r node) new? (not= new-node node) new-loc (if new? (zip/replace loc new-node) loc) new-state (if new? :stop) next-loc (zip/next new-loc)] (if (or (zip/end? loc) (= :stop new-state)) (zip/root new-loc) (recur next-loc))))) ; ----------------------------------------------------------------------------- ;; # Weak reduction (defn vec' [sterm] (if (symbol? sterm) [sterm] (vec sterm))) (defn weak-reduce "Reduce the `sterm`" [sterm counter limit cycle trace] (let [steps (atom [])] (loop [current-sterm sterm result {:reduced sterm :no-steps 0 :cycle :unknown :overrun false} counter counter] (if cycle (swap! steps conj current-sterm)) (let [red (apply-z current-sterm) ;; one step with apply found (when-not (= red current-sterm) red)] ;; reduced term found (if (and found trace) (println (str counter ": " (vec' (min-parens-seq found))))) (cond (nil? found) result ;; timeout? -> Exception, the result is never returned (.isInterrupted (Thread/currentThread)) (assoc result :result found :timeout true :no-steps counter) ;; overrun (>= counter limit 1) (assoc result :reduced found :no-steps counter :overrun true) ;; cycle (and cycle (some #(= found %) @steps)) (assoc result :reduced found :cycle true :steps @steps :no-steps counter) :else (recur found (assoc result :reduced found :no-steps counter) (inc counter)))))))
true
; lwb Logic WorkBench -- Combinatory logic - internals ; Copyright (c) 2019 PI:NAME:<NAME>END_PI, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.cl.impl (:refer-clojure :exclude [==]) (:require [clojure.walk :as walk] [clojure.spec.alpha :as s] [clojure.core.logic :refer :all] [clojure.set :as set] [lwb.nd.error :refer :all] [clojure.zip :as zip])) ; ----------------------------------------------------------------------------- ;; # Handling of parentheses (defn add-parens "Adds left-associative parentheses to a seq of symbols or subterms." [[first second & more]] (let [ret (list first second)] (if more (recur (list* ret more)) ret))) (defn rm-outer-parens "Removes all outer parens of a seq" [tseq] (if (= 1 (count tseq)) (if (seq? (first tseq)) (recur (first tseq)) tseq) tseq)) (defn max-parens-seq [seq] (walk/postwalk #(if (seq? %) (let [seq' (rm-outer-parens %)] (if (= 1 (count seq')) seq' (add-parens seq'))) %) seq)) (defn min-parens-seq [seq] (let [seqn (max-parens-seq seq)] (walk/postwalk #(if (seq? %) (let [f (first %)] (if (seq? f) (concat f (rest %)) %)) %) seqn))) ; ----------------------------------------------------------------------------- ;; # Logic relation for combinators (defn vars "The set of variables in `term`." [term] (->> (flatten term) (filter #(s/valid? :lwb.cl.spec/variable %)) (into #{}))) (defn gen-fresh-args "Vector of fresh variables for the relation to be constructed" [redex effect] (let [r-vars (vars redex) e-vars (vars effect)] (vec (set/union r-vars e-vars)))) (defn gen-cl-term' "Code from a sequence with all parentheses" [seqterm] (map (fn [item] (if (seq? item) (list* 'list (gen-cl-term' item)) (if (s/valid? :lwb.cl.spec/combinator item) (list 'quote item) item))) seqterm)) (defn gen-cl-term "Code from a term without all parentheses" [term] (let [seqterm (max-parens-seq (seq term)) result (gen-cl-term' seqterm)] (if (= 1 (count result)) (first result) (list* 'list result)))) (defn gen-cl-rel [redex effect] ;; both terms (let [fresh-args (gen-fresh-args redex effect) redex-term (gen-cl-term redex) effect-term (gen-cl-term effect)] (list 'fn (vector 'term 'q) (list 'fresh fresh-args (list '== 'term redex-term) (list '== 'q effect-term))))) ; ----------------------------------------------------------------------------- ;; # Arity of combinators (defn arity "Arity of redex" [redex] (if (and (= 1 (count redex)) (symbol? (first redex))) ; just one symbol 0 (loop [sterm (max-parens-seq (seq redex)) arity 0] (if (symbol? sterm) arity (recur (first sterm) (inc arity)))))) ; ----------------------------------------------------------------------------- ;; # Storage for combinators (def combinator-store (atom {})) (defn combs "The set of combinators in `term`." [term] (->> (flatten term) (filter #(s/valid? :lwb.cl.spec/combinator %)) (into #{}))) (defn combs-keys "The set of combinator keys in `term`." [term] (set (map keyword (combs term)))) (defn make-comb [redex effect nickname] (let [combs (combs redex) key (keyword (first combs))] (if-not key (throw (AssertionError. (str "Redex '" redex "' has no combinator!"))) (hash-map key {:redex redex :effect effect :arity (arity redex) :nickname nickname :logic-rel (binding [*ns* (find-ns 'lwb.cl.impl)] (eval (gen-cl-rel redex effect)))})))) (defn get-rule-fn "Get logic function from combinator store." [comb-key] (if-let [f (get-in @combinator-store [comb-key :logic-rel])] f (throw (ex-error (str "Combinator " comb-key " not defined."))))) (defn get-arity [comb-key] (get-in @combinator-store [comb-key :arity])) ; ----------------------------------------------------------------------------- ;; Application of logic relation for one-step expansion or reduction (defn apply' [rule-fn seqterm mode] (if (= mode :red) (run 1 [q] (rule-fn seqterm q)) (run 1 [q] (rule-fn q seqterm)))) (defn apply* [term rule-fn i mode] ;; Pre: term has max parentheses (let [counter (atom 0)] (walk/prewalk #(let [rep (apply' rule-fn % mode)] ;(println "replace " % " -> " rep) (if (and (not (vector? %)) (not-empty rep)) (if (= i (swap! counter inc)) (first rep) %) %)) term))) (defn reducible? "Is the given sterm reducible with combinator comb with arity arity?" [sterm comb arity] (loop [count 0 st sterm] (cond (= arity count) (if (= st comb) true false) ; test this first! (not (seq? st)) false ; don't test on list? since sterm may be a lazy seq! :else (recur (inc count) (first st))))) ;; an alternative check: (= comb (first (flatten sterm))) ; could be even faster, but not so selective (defn apply** "Lookup for first combinator in term and try to reduce" [sterm] (let [comb (->> (flatten sterm) (filter #(s/valid? :lwb.cl.spec/combinator %)) (first))] (when-not (nil? comb) (let [comb-key (keyword comb) rule-fn (get-rule-fn comb-key)] (first (apply' rule-fn sterm :red)))))) (defn apply-z "One-step reduction (with first combinator in sterm)" [sterm] (loop [loc (zip/seq-zip sterm)] (let [node (zip/node loc) new-node (if-let [r (apply** node)] r node) new? (not= new-node node) new-loc (if new? (zip/replace loc new-node) loc) new-state (if new? :stop) next-loc (zip/next new-loc)] (if (or (zip/end? loc) (= :stop new-state)) (zip/root new-loc) (recur next-loc))))) ; ----------------------------------------------------------------------------- ;; # Weak reduction (defn vec' [sterm] (if (symbol? sterm) [sterm] (vec sterm))) (defn weak-reduce "Reduce the `sterm`" [sterm counter limit cycle trace] (let [steps (atom [])] (loop [current-sterm sterm result {:reduced sterm :no-steps 0 :cycle :unknown :overrun false} counter counter] (if cycle (swap! steps conj current-sterm)) (let [red (apply-z current-sterm) ;; one step with apply found (when-not (= red current-sterm) red)] ;; reduced term found (if (and found trace) (println (str counter ": " (vec' (min-parens-seq found))))) (cond (nil? found) result ;; timeout? -> Exception, the result is never returned (.isInterrupted (Thread/currentThread)) (assoc result :result found :timeout true :no-steps counter) ;; overrun (>= counter limit 1) (assoc result :reduced found :no-steps counter :overrun true) ;; cycle (and cycle (some #(= found %) @steps)) (assoc result :reduced found :cycle true :steps @steps :no-steps counter) :else (recur found (assoc result :reduced found :no-steps counter) (inc counter)))))))
[ { "context": ".coerce :refer [to-long]]))\n\n(def month-names\n [\"Gener\"\n \"Febrer\"\n \"Març\"\n \"Abril\"\n \"Maig\"\n \"J", "end": 203, "score": 0.9187753200531006, "start": 198, "tag": "NAME", "value": "Gener" }, { "context": "fer [to-long]]))\n\n(def month-names\n [\"Gener\"\n \"Febrer\"\n \"Març\"\n \"Abril\"\n \"Maig\"\n \"Juny\"\n \"Jul", "end": 215, "score": 0.9367572665214539, "start": 209, "tag": "NAME", "value": "Febrer" }, { "context": "]]))\n\n(def month-names\n [\"Gener\"\n \"Febrer\"\n \"Març\"\n \"Abril\"\n \"Maig\"\n \"Juny\"\n \"Juliol\"\n \"A", "end": 225, "score": 0.9968889951705933, "start": 221, "tag": "NAME", "value": "Març" }, { "context": " month-names\n [\"Gener\"\n \"Febrer\"\n \"Març\"\n \"Abril\"\n \"Maig\"\n \"Juny\"\n \"Juliol\"\n \"Augost\"\n \"", "end": 236, "score": 0.9975473284721375, "start": 231, "tag": "NAME", "value": "Abril" }, { "context": "s\n [\"Gener\"\n \"Febrer\"\n \"Març\"\n \"Abril\"\n \"Maig\"\n \"Juny\"\n \"Juliol\"\n \"Augost\"\n \"Setembre\"\n", "end": 246, "score": 0.993874192237854, "start": 242, "tag": "NAME", "value": "Maig" }, { "context": "r\"\n \"Febrer\"\n \"Març\"\n \"Abril\"\n \"Maig\"\n \"Juny\"\n \"Juliol\"\n \"Augost\"\n \"Setembre\"\n \"Octubr", "end": 256, "score": 0.9664831161499023, "start": 252, "tag": "NAME", "value": "Juny" }, { "context": "rer\"\n \"Març\"\n \"Abril\"\n \"Maig\"\n \"Juny\"\n \"Juliol\"\n \"Augost\"\n \"Setembre\"\n \"Octubre\"\n \"Novem", "end": 268, "score": 0.8680393099784851, "start": 262, "tag": "NAME", "value": "Juliol" }, { "context": "ç\"\n \"Abril\"\n \"Maig\"\n \"Juny\"\n \"Juliol\"\n \"Augost\"\n \"Setembre\"\n \"Octubre\"\n \"Novembre\"\n \"Des", "end": 280, "score": 0.9486756920814514, "start": 274, "tag": "NAME", "value": "Augost" }, { "context": "\"\n \"Maig\"\n \"Juny\"\n \"Juliol\"\n \"Augost\"\n \"Setembre\"\n \"Octubre\"\n \"Novembre\"\n \"Desembre\"])\n\n(def", "end": 294, "score": 0.9645072817802429, "start": 286, "tag": "NAME", "value": "Setembre" }, { "context": "t\"\n \"Setembre\"\n \"Octubre\"\n \"Novembre\"\n \"Desembre\"])\n\n(def week-days\n [\"dl\" \"dt\" \"dc\" \"dj\" \"dv\" \"d", "end": 335, "score": 0.78720623254776, "start": 329, "tag": "NAME", "value": "sembre" } ]
src/rpi_wall/calendar/build_calendar.cljs
gthar/rpi_wall
0
(ns rpi-wall.calendar.build-calendar (:require [cljs-time.core :refer [day month year date-time day-of-week plus months]] [cljs-time.coerce :refer [to-long]])) (def month-names ["Gener" "Febrer" "Març" "Abril" "Maig" "Juny" "Juliol" "Augost" "Setembre" "Octubre" "Novembre" "Desembre"]) (def week-days ["dl" "dt" "dc" "dj" "dv" "ds" "dg"]) (defn get-first-week-day [current-month current-year] (day-of-week (date-time current-year current-month 1))) (defn get-days-in-this-month [current-month current-year] (let [this-month (date-time current-year current-month 1) next-month (date-time current-year (inc current-month) 1)] (js/Math.round (/ (- (to-long next-month) (to-long this-month)) (* 1000 60 60 24))))) (defn col-builder [x current-day busy-days] (let [day (:day x) is-today (= day current-day) is-busy (some (partial = x) busy-days) tag (cond (and is-today is-busy) :td.current-day.busy-day is-today :td.current-day is-busy :td.busy-day :else :td)] [tag day])) (defn get-empty-days [first-week-day days-in-month] (- (count week-days) (inc (mod (+ (dec first-week-day) (dec days-in-month)) (count week-days))))) (defn make-day-vals [first-week-day days-in-month] (concat (repeat (dec first-week-day) "") (range 1 (inc days-in-month)) (repeat (get-empty-days first-week-day days-in-month) ""))) (defn make-cal-body [current-day current-month current-year busy-days] (let [days-in-this-month (get-days-in-this-month current-month current-year) first-week-day (get-first-week-day current-month current-year) day-vals (make-day-vals first-week-day days-in-this-month) cols (map (fn [x] (col-builder {:day x :month current-month :year current-year} current-day busy-days)) day-vals)] (into [:tbody] (map #(into [:tr] %) (partition (count week-days) cols))))) (def days-row (into [:tr] (map (partial vector :th.day-names) week-days))) (defn make-header [current-month current-year] [:thead [:tr [:th {:col-span 7} (nth month-names (dec current-month)) " " current-year]] days-row]) (defn make-month [d n busy-days] (let [date (plus d (months n)) current-day (if (= n 0) (day date) nil) current-month (month date) current-year (year date) header (make-header current-month current-year) body (make-cal-body current-day current-month current-year busy-days)] [:div.month [:table#month header body]]))
111900
(ns rpi-wall.calendar.build-calendar (:require [cljs-time.core :refer [day month year date-time day-of-week plus months]] [cljs-time.coerce :refer [to-long]])) (def month-names ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "Octubre" "Novembre" "De<NAME>"]) (def week-days ["dl" "dt" "dc" "dj" "dv" "ds" "dg"]) (defn get-first-week-day [current-month current-year] (day-of-week (date-time current-year current-month 1))) (defn get-days-in-this-month [current-month current-year] (let [this-month (date-time current-year current-month 1) next-month (date-time current-year (inc current-month) 1)] (js/Math.round (/ (- (to-long next-month) (to-long this-month)) (* 1000 60 60 24))))) (defn col-builder [x current-day busy-days] (let [day (:day x) is-today (= day current-day) is-busy (some (partial = x) busy-days) tag (cond (and is-today is-busy) :td.current-day.busy-day is-today :td.current-day is-busy :td.busy-day :else :td)] [tag day])) (defn get-empty-days [first-week-day days-in-month] (- (count week-days) (inc (mod (+ (dec first-week-day) (dec days-in-month)) (count week-days))))) (defn make-day-vals [first-week-day days-in-month] (concat (repeat (dec first-week-day) "") (range 1 (inc days-in-month)) (repeat (get-empty-days first-week-day days-in-month) ""))) (defn make-cal-body [current-day current-month current-year busy-days] (let [days-in-this-month (get-days-in-this-month current-month current-year) first-week-day (get-first-week-day current-month current-year) day-vals (make-day-vals first-week-day days-in-this-month) cols (map (fn [x] (col-builder {:day x :month current-month :year current-year} current-day busy-days)) day-vals)] (into [:tbody] (map #(into [:tr] %) (partition (count week-days) cols))))) (def days-row (into [:tr] (map (partial vector :th.day-names) week-days))) (defn make-header [current-month current-year] [:thead [:tr [:th {:col-span 7} (nth month-names (dec current-month)) " " current-year]] days-row]) (defn make-month [d n busy-days] (let [date (plus d (months n)) current-day (if (= n 0) (day date) nil) current-month (month date) current-year (year date) header (make-header current-month current-year) body (make-cal-body current-day current-month current-year busy-days)] [:div.month [:table#month header body]]))
true
(ns rpi-wall.calendar.build-calendar (:require [cljs-time.core :refer [day month year date-time day-of-week plus months]] [cljs-time.coerce :refer [to-long]])) (def month-names ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Octubre" "Novembre" "DePI:NAME:<NAME>END_PI"]) (def week-days ["dl" "dt" "dc" "dj" "dv" "ds" "dg"]) (defn get-first-week-day [current-month current-year] (day-of-week (date-time current-year current-month 1))) (defn get-days-in-this-month [current-month current-year] (let [this-month (date-time current-year current-month 1) next-month (date-time current-year (inc current-month) 1)] (js/Math.round (/ (- (to-long next-month) (to-long this-month)) (* 1000 60 60 24))))) (defn col-builder [x current-day busy-days] (let [day (:day x) is-today (= day current-day) is-busy (some (partial = x) busy-days) tag (cond (and is-today is-busy) :td.current-day.busy-day is-today :td.current-day is-busy :td.busy-day :else :td)] [tag day])) (defn get-empty-days [first-week-day days-in-month] (- (count week-days) (inc (mod (+ (dec first-week-day) (dec days-in-month)) (count week-days))))) (defn make-day-vals [first-week-day days-in-month] (concat (repeat (dec first-week-day) "") (range 1 (inc days-in-month)) (repeat (get-empty-days first-week-day days-in-month) ""))) (defn make-cal-body [current-day current-month current-year busy-days] (let [days-in-this-month (get-days-in-this-month current-month current-year) first-week-day (get-first-week-day current-month current-year) day-vals (make-day-vals first-week-day days-in-this-month) cols (map (fn [x] (col-builder {:day x :month current-month :year current-year} current-day busy-days)) day-vals)] (into [:tbody] (map #(into [:tr] %) (partition (count week-days) cols))))) (def days-row (into [:tr] (map (partial vector :th.day-names) week-days))) (defn make-header [current-month current-year] [:thead [:tr [:th {:col-span 7} (nth month-names (dec current-month)) " " current-year]] days-row]) (defn make-month [d n busy-days] (let [date (plus d (months n)) current-day (if (= n 0) (day date) nil) current-month (month date) current-year (year date) header (make-header current-month current-year) body (make-cal-body current-day current-month current-year busy-days)] [:div.month [:table#month header body]]))
[ { "context": ".ring-buffer)\n\n(defn- make-array* [size]\n ; TODO(Richo): This would probably be faster using a native ar", "end": 82, "score": 0.9857151508331299, "start": 77, "tag": "NAME", "value": "Richo" } ]
middleware/server/src/middleware/device/utils/ring_buffer.cljc
GIRA/PhysicalBits
2
(ns middleware.device.utils.ring-buffer) (defn- make-array* [size] ; TODO(Richo): This would probably be faster using a native array, but for now it works #?(:clj (apply vector-of :double (repeat size 0)) :cljs (vec (repeat size 0)))) (defn make-ring-buffer [size] (atom {:array (make-array* size), :index 0})) (defn push! [ring-buffer ^double new] (swap! ring-buffer (fn [{:keys [array ^long index] :as rb}] (let [size (count array)] (-> rb (update :array (fn [^doubles arr] (assoc arr (rem index size) new))) (update :index (fn [^long i] (rem (inc i) size)))))))) (defn- sum ^double [array] (reduce + array)) (defn avg ^double [ring-buffer] (let [{:keys [array]} @ring-buffer len (count array)] (if (zero? len) 0 (/ (sum array) len)))) (comment (def ring-buffer (make-ring-buffer 10)) (double (avg ring-buffer)) (push! ring-buffer 20.5) (time (dotimes [_ 10000] (push! ring-buffer (rand-int 100)))) (:array @ring-buffer) ,)
2580
(ns middleware.device.utils.ring-buffer) (defn- make-array* [size] ; TODO(<NAME>): This would probably be faster using a native array, but for now it works #?(:clj (apply vector-of :double (repeat size 0)) :cljs (vec (repeat size 0)))) (defn make-ring-buffer [size] (atom {:array (make-array* size), :index 0})) (defn push! [ring-buffer ^double new] (swap! ring-buffer (fn [{:keys [array ^long index] :as rb}] (let [size (count array)] (-> rb (update :array (fn [^doubles arr] (assoc arr (rem index size) new))) (update :index (fn [^long i] (rem (inc i) size)))))))) (defn- sum ^double [array] (reduce + array)) (defn avg ^double [ring-buffer] (let [{:keys [array]} @ring-buffer len (count array)] (if (zero? len) 0 (/ (sum array) len)))) (comment (def ring-buffer (make-ring-buffer 10)) (double (avg ring-buffer)) (push! ring-buffer 20.5) (time (dotimes [_ 10000] (push! ring-buffer (rand-int 100)))) (:array @ring-buffer) ,)
true
(ns middleware.device.utils.ring-buffer) (defn- make-array* [size] ; TODO(PI:NAME:<NAME>END_PI): This would probably be faster using a native array, but for now it works #?(:clj (apply vector-of :double (repeat size 0)) :cljs (vec (repeat size 0)))) (defn make-ring-buffer [size] (atom {:array (make-array* size), :index 0})) (defn push! [ring-buffer ^double new] (swap! ring-buffer (fn [{:keys [array ^long index] :as rb}] (let [size (count array)] (-> rb (update :array (fn [^doubles arr] (assoc arr (rem index size) new))) (update :index (fn [^long i] (rem (inc i) size)))))))) (defn- sum ^double [array] (reduce + array)) (defn avg ^double [ring-buffer] (let [{:keys [array]} @ring-buffer len (count array)] (if (zero? len) 0 (/ (sum array) len)))) (comment (def ring-buffer (make-ring-buffer 10)) (double (avg ring-buffer)) (push! ring-buffer 20.5) (time (dotimes [_ 10000] (push! ring-buffer (rand-int 100)))) (:array @ring-buffer) ,)
[ { "context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2016 Richard Hull\n;;\n;; Permission is hereby granted, free of charg", "end": 62, "score": 0.9997938275337219, "start": 50, "tag": "NAME", "value": "Richard Hull" } ]
src/helpmate/sgml.cljc
rm-hull/helpmate
1
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 Richard Hull ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to rpermit 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 helpmate.sgml (:refer-clojure :exclude [comment])) (def ^:private doctype-declarations {:html5 "html" :html-4.01-strict "HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"" :html-4.01-transitional "HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"" :html-4.01-frameset "HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\"" :xhtml-1.0-strict "html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"" :xhtml-1.0-transitional "html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"" :xhtml-1.0-frameset "html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\"" :xhtml-1.1 "html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\""}) (defn doctype "The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag. The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in. In HTML 4.01, the <!DOCTYPE> declaration refers to a DTD, because HTML 4.01 was based on SGML. The DTD specifies the rules for the markup language, so that the browsers render the content correctly. HTML5 is not based on SGML, and therefore does not require a reference to a DTD. Tip: Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect. Valid keyword shortcut values are shown below. If the value is a string then that will be used instead. :html5 :html-4.01-strict :html-4.01-transitional :html-4.01-frameset :xhtml-1.0-strict :xhtml-1.0-transitional :xhtml-1.0-frameset :xhtml-1.1" [value] (str "<!DOCTYPE" (get doctype-declarations value value) ">")) (defn cdata "The CDATASection interface represents a CDATA section that can be used within XML to include extended portions of unescaped text, such that the symbols < and & do not need escaping as they normally do within XML when used as text." [value] (str "<![CDATA[" value "]]>")) (defn comment "The Comment interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. Comments are represented in HTML and XML as content between '<!--' and '-->'. In XML, the character sequence '--' cannot be used within a comment." [value] (str "<!-- " value " -->"))
60611
;; 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 rpermit 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 helpmate.sgml (:refer-clojure :exclude [comment])) (def ^:private doctype-declarations {:html5 "html" :html-4.01-strict "HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"" :html-4.01-transitional "HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"" :html-4.01-frameset "HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\"" :xhtml-1.0-strict "html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"" :xhtml-1.0-transitional "html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"" :xhtml-1.0-frameset "html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\"" :xhtml-1.1 "html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\""}) (defn doctype "The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag. The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in. In HTML 4.01, the <!DOCTYPE> declaration refers to a DTD, because HTML 4.01 was based on SGML. The DTD specifies the rules for the markup language, so that the browsers render the content correctly. HTML5 is not based on SGML, and therefore does not require a reference to a DTD. Tip: Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect. Valid keyword shortcut values are shown below. If the value is a string then that will be used instead. :html5 :html-4.01-strict :html-4.01-transitional :html-4.01-frameset :xhtml-1.0-strict :xhtml-1.0-transitional :xhtml-1.0-frameset :xhtml-1.1" [value] (str "<!DOCTYPE" (get doctype-declarations value value) ">")) (defn cdata "The CDATASection interface represents a CDATA section that can be used within XML to include extended portions of unescaped text, such that the symbols < and & do not need escaping as they normally do within XML when used as text." [value] (str "<![CDATA[" value "]]>")) (defn comment "The Comment interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. Comments are represented in HTML and XML as content between '<!--' and '-->'. In XML, the character sequence '--' cannot be used within a comment." [value] (str "<!-- " value " -->"))
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 rpermit 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 helpmate.sgml (:refer-clojure :exclude [comment])) (def ^:private doctype-declarations {:html5 "html" :html-4.01-strict "HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"" :html-4.01-transitional "HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"" :html-4.01-frameset "HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\"" :xhtml-1.0-strict "html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"" :xhtml-1.0-transitional "html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"" :xhtml-1.0-frameset "html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\"" :xhtml-1.1 "html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\""}) (defn doctype "The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag. The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in. In HTML 4.01, the <!DOCTYPE> declaration refers to a DTD, because HTML 4.01 was based on SGML. The DTD specifies the rules for the markup language, so that the browsers render the content correctly. HTML5 is not based on SGML, and therefore does not require a reference to a DTD. Tip: Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect. Valid keyword shortcut values are shown below. If the value is a string then that will be used instead. :html5 :html-4.01-strict :html-4.01-transitional :html-4.01-frameset :xhtml-1.0-strict :xhtml-1.0-transitional :xhtml-1.0-frameset :xhtml-1.1" [value] (str "<!DOCTYPE" (get doctype-declarations value value) ">")) (defn cdata "The CDATASection interface represents a CDATA section that can be used within XML to include extended portions of unescaped text, such that the symbols < and & do not need escaping as they normally do within XML when used as text." [value] (str "<![CDATA[" value "]]>")) (defn comment "The Comment interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. Comments are represented in HTML and XML as content between '<!--' and '-->'. In XML, the character sequence '--' cannot be used within a comment." [value] (str "<!-- " value " -->"))
[ { "context": "using Genetic Algorithms\n;;;;\n;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal\n;;;; -------", "end": 402, "score": 0.9998824000358582, "start": 390, "tag": "NAME", "value": "Dennis Drown" } ]
apps/say_sila/priv/fnode/say/src/say/optimize.clj
dendrown/say_sila
0
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; Ontology optimization using Genetic Algorithms ;;;; ;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns say.optimize (:require [say.genie :refer :all] [say.check :as chk] [say.log :as log] [say.senti :as senti]) (:import (io.jenetics BitChromosome Genotype Mutator RouletteWheelSelector SinglePointCrossover) (io.jenetics.engine Engine Evaluator EvolutionResult EvolutionStatistics Limits))) ;;; TODO: The say-senti ontology is currently acting as a prototype in the ;;; Say-Sila project. The functionality in this module needs to be ;;; generalized. (set! *warn-on-reflection* true) (def ^:const INIT-POPULATION-SIZE 10) (def ^:const INIT-MUTATION-RATE 0.25) ;;; -------------------------------------------------------------------------- (defn make-evaluator "Returns a Jenetics Evaluator to determine the fitness of an individual." [arff solns] (log/fmt-debug "Evaluate on ~a: cnt[~a]" (type solns) (count solns)) (reify Evaluator (eval [_ geno] (let [geno ^Genotype geno ones (-> (.getChromosome geno) (.as BitChromosome) (.ones)) trial (reduce #(conj %1 (nth %2 solns)) ones) audit (chk/eval-senti arff trial)] (log/fmt-info "Evaluating ~a solutions: f1[~4$]" (count ones) (.fMeasure audit)) ;; TODO: Score on F1, not rule count (count ones))))) ;;; -------------------------------------------------------------------------- (defn evolve "Runs Jenetics GA to determine ideal solutions." [arff solns] (let [plan (doto (Engine/builder (make-evaluator arff solns) (BitChromosome/of (count solns))) (.populationSize INIT-POPULATION-SIZE) (.selector (RouletteWheelSelector.)) (.alterers (Mutator. INIT-MUTATION-RATE) (SinglePointCrossover.))) stats (EvolutionStatistics/ofNumber) result (doto (.build plan) (.stream) (.limit (Limits/bySteadyFitness 5)) ; TODO: config (.limit 100) ; TODO: config (.peek stats) (.collect (EvolutionResult/toBestEvolutionResult)))] (log/info "Evolution:\n" stats) (log/info "Result:\n" result))) ;;; -------------------------------------------------------------------------- (defn judge-senti "Uses a genetic algorithm to detemine an ideal subset of solutions for identifying positive texts using the say-senti ontology." [] (let [arff "resources/emo-sa/sentiment-analysis.Sentiment140.r24816.train.000.arff" ; FIXME! solns (senti/read-solutions)] (log/fmt-info "GA selection: arff[~a] solns[~a]" arff (count solns)) (evolve arff solns)))
61195
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; Ontology optimization using Genetic Algorithms ;;;; ;;;; @copyright 2020 <NAME> et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns say.optimize (:require [say.genie :refer :all] [say.check :as chk] [say.log :as log] [say.senti :as senti]) (:import (io.jenetics BitChromosome Genotype Mutator RouletteWheelSelector SinglePointCrossover) (io.jenetics.engine Engine Evaluator EvolutionResult EvolutionStatistics Limits))) ;;; TODO: The say-senti ontology is currently acting as a prototype in the ;;; Say-Sila project. The functionality in this module needs to be ;;; generalized. (set! *warn-on-reflection* true) (def ^:const INIT-POPULATION-SIZE 10) (def ^:const INIT-MUTATION-RATE 0.25) ;;; -------------------------------------------------------------------------- (defn make-evaluator "Returns a Jenetics Evaluator to determine the fitness of an individual." [arff solns] (log/fmt-debug "Evaluate on ~a: cnt[~a]" (type solns) (count solns)) (reify Evaluator (eval [_ geno] (let [geno ^Genotype geno ones (-> (.getChromosome geno) (.as BitChromosome) (.ones)) trial (reduce #(conj %1 (nth %2 solns)) ones) audit (chk/eval-senti arff trial)] (log/fmt-info "Evaluating ~a solutions: f1[~4$]" (count ones) (.fMeasure audit)) ;; TODO: Score on F1, not rule count (count ones))))) ;;; -------------------------------------------------------------------------- (defn evolve "Runs Jenetics GA to determine ideal solutions." [arff solns] (let [plan (doto (Engine/builder (make-evaluator arff solns) (BitChromosome/of (count solns))) (.populationSize INIT-POPULATION-SIZE) (.selector (RouletteWheelSelector.)) (.alterers (Mutator. INIT-MUTATION-RATE) (SinglePointCrossover.))) stats (EvolutionStatistics/ofNumber) result (doto (.build plan) (.stream) (.limit (Limits/bySteadyFitness 5)) ; TODO: config (.limit 100) ; TODO: config (.peek stats) (.collect (EvolutionResult/toBestEvolutionResult)))] (log/info "Evolution:\n" stats) (log/info "Result:\n" result))) ;;; -------------------------------------------------------------------------- (defn judge-senti "Uses a genetic algorithm to detemine an ideal subset of solutions for identifying positive texts using the say-senti ontology." [] (let [arff "resources/emo-sa/sentiment-analysis.Sentiment140.r24816.train.000.arff" ; FIXME! solns (senti/read-solutions)] (log/fmt-info "GA selection: arff[~a] solns[~a]" arff (count solns)) (evolve arff solns)))
true
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; Ontology optimization using Genetic Algorithms ;;;; ;;;; @copyright 2020 PI:NAME:<NAME>END_PI et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns say.optimize (:require [say.genie :refer :all] [say.check :as chk] [say.log :as log] [say.senti :as senti]) (:import (io.jenetics BitChromosome Genotype Mutator RouletteWheelSelector SinglePointCrossover) (io.jenetics.engine Engine Evaluator EvolutionResult EvolutionStatistics Limits))) ;;; TODO: The say-senti ontology is currently acting as a prototype in the ;;; Say-Sila project. The functionality in this module needs to be ;;; generalized. (set! *warn-on-reflection* true) (def ^:const INIT-POPULATION-SIZE 10) (def ^:const INIT-MUTATION-RATE 0.25) ;;; -------------------------------------------------------------------------- (defn make-evaluator "Returns a Jenetics Evaluator to determine the fitness of an individual." [arff solns] (log/fmt-debug "Evaluate on ~a: cnt[~a]" (type solns) (count solns)) (reify Evaluator (eval [_ geno] (let [geno ^Genotype geno ones (-> (.getChromosome geno) (.as BitChromosome) (.ones)) trial (reduce #(conj %1 (nth %2 solns)) ones) audit (chk/eval-senti arff trial)] (log/fmt-info "Evaluating ~a solutions: f1[~4$]" (count ones) (.fMeasure audit)) ;; TODO: Score on F1, not rule count (count ones))))) ;;; -------------------------------------------------------------------------- (defn evolve "Runs Jenetics GA to determine ideal solutions." [arff solns] (let [plan (doto (Engine/builder (make-evaluator arff solns) (BitChromosome/of (count solns))) (.populationSize INIT-POPULATION-SIZE) (.selector (RouletteWheelSelector.)) (.alterers (Mutator. INIT-MUTATION-RATE) (SinglePointCrossover.))) stats (EvolutionStatistics/ofNumber) result (doto (.build plan) (.stream) (.limit (Limits/bySteadyFitness 5)) ; TODO: config (.limit 100) ; TODO: config (.peek stats) (.collect (EvolutionResult/toBestEvolutionResult)))] (log/info "Evolution:\n" stats) (log/info "Result:\n" result))) ;;; -------------------------------------------------------------------------- (defn judge-senti "Uses a genetic algorithm to detemine an ideal subset of solutions for identifying positive texts using the say-senti ontology." [] (let [arff "resources/emo-sa/sentiment-analysis.Sentiment140.r24816.train.000.arff" ; FIXME! solns (senti/read-solutions)] (log/fmt-info "GA selection: arff[~a] solns[~a]" arff (count solns)) (evolve arff solns)))
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis", "end": 33, "score": 0.9998555779457092, "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.9998395442962646, "start": 35, "tag": "NAME", "value": "Rich Hickey" } ]
src/lucid/legacy/analyzer/ast.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.ast "Utilities for AST walking/updating" (:require [lucid.legacy.analyzer.utils :refer [into! rseqv]])) (defn cycling "Combine the given passes in a single pass that will be repeatedly applied 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)))) (defmulti -update-children (fn [ast f] (:op ast))) (defmulti -update-children-r (fn [ast f] (:op ast))) (defmethod -update-children :default [ast f] (persistent! (reduce (fn [ast [k v]] (assoc! ast k (if (vector? v) (mapv f v) (f v)))) (transient ast) (children* ast)))) (defmethod -update-children-r :default [ast f] (persistent! (reduce (fn [ast [k v]] (assoc! ast k (if (vector? v) (rseqv (mapv f (rseq v))) (f v)))) (transient ast) (rseq (children* ast))))) (defn update-children "Applies `f` to the nodes in the AST nodes children. Optionally applies `fix` to the children before applying `f` to the children nodes and then applies `fix` to the update children. An example of a useful `fix` function is `rseq`." ([ast f] (update-children ast f false)) ([ast f reversed?] (if (:children ast) (if reversed? (-update-children-r ast f) (-update-children ast f)) ast))) (defn walk "Walk the ast applying pre when entering the nodes, and post when exiting. If reversed? is not-nil, pre and post will be applied starting from the last children of the AST node to the first one." ([ast pre post] (walk ast pre post false)) ([ast pre post reversed?] (let [walk #(walk % pre post reversed?)] (post (update-children (pre ast) walk reversed?))))) (defn prewalk "Shorthand for (walk ast f identity)" [ast f] (let [walk #(prewalk % f)] (update-children (f ast) walk))) (defn postwalk "Shorthand for (walk ast identity f reversed?)" ([ast f] (postwalk ast f false)) ([ast f reversed?] (let [walk #(postwalk % f reversed?)] (f (update-children ast walk 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)))
96300
;; 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.ast "Utilities for AST walking/updating" (:require [lucid.legacy.analyzer.utils :refer [into! rseqv]])) (defn cycling "Combine the given passes in a single pass that will be repeatedly applied 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)))) (defmulti -update-children (fn [ast f] (:op ast))) (defmulti -update-children-r (fn [ast f] (:op ast))) (defmethod -update-children :default [ast f] (persistent! (reduce (fn [ast [k v]] (assoc! ast k (if (vector? v) (mapv f v) (f v)))) (transient ast) (children* ast)))) (defmethod -update-children-r :default [ast f] (persistent! (reduce (fn [ast [k v]] (assoc! ast k (if (vector? v) (rseqv (mapv f (rseq v))) (f v)))) (transient ast) (rseq (children* ast))))) (defn update-children "Applies `f` to the nodes in the AST nodes children. Optionally applies `fix` to the children before applying `f` to the children nodes and then applies `fix` to the update children. An example of a useful `fix` function is `rseq`." ([ast f] (update-children ast f false)) ([ast f reversed?] (if (:children ast) (if reversed? (-update-children-r ast f) (-update-children ast f)) ast))) (defn walk "Walk the ast applying pre when entering the nodes, and post when exiting. If reversed? is not-nil, pre and post will be applied starting from the last children of the AST node to the first one." ([ast pre post] (walk ast pre post false)) ([ast pre post reversed?] (let [walk #(walk % pre post reversed?)] (post (update-children (pre ast) walk reversed?))))) (defn prewalk "Shorthand for (walk ast f identity)" [ast f] (let [walk #(prewalk % f)] (update-children (f ast) walk))) (defn postwalk "Shorthand for (walk ast identity f reversed?)" ([ast f] (postwalk ast f false)) ([ast f reversed?] (let [walk #(postwalk % f reversed?)] (f (update-children ast walk 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 lucid.legacy.analyzer.ast "Utilities for AST walking/updating" (:require [lucid.legacy.analyzer.utils :refer [into! rseqv]])) (defn cycling "Combine the given passes in a single pass that will be repeatedly applied 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)))) (defmulti -update-children (fn [ast f] (:op ast))) (defmulti -update-children-r (fn [ast f] (:op ast))) (defmethod -update-children :default [ast f] (persistent! (reduce (fn [ast [k v]] (assoc! ast k (if (vector? v) (mapv f v) (f v)))) (transient ast) (children* ast)))) (defmethod -update-children-r :default [ast f] (persistent! (reduce (fn [ast [k v]] (assoc! ast k (if (vector? v) (rseqv (mapv f (rseq v))) (f v)))) (transient ast) (rseq (children* ast))))) (defn update-children "Applies `f` to the nodes in the AST nodes children. Optionally applies `fix` to the children before applying `f` to the children nodes and then applies `fix` to the update children. An example of a useful `fix` function is `rseq`." ([ast f] (update-children ast f false)) ([ast f reversed?] (if (:children ast) (if reversed? (-update-children-r ast f) (-update-children ast f)) ast))) (defn walk "Walk the ast applying pre when entering the nodes, and post when exiting. If reversed? is not-nil, pre and post will be applied starting from the last children of the AST node to the first one." ([ast pre post] (walk ast pre post false)) ([ast pre post reversed?] (let [walk #(walk % pre post reversed?)] (post (update-children (pre ast) walk reversed?))))) (defn prewalk "Shorthand for (walk ast f identity)" [ast f] (let [walk #(prewalk % f)] (update-children (f ast) walk))) (defn postwalk "Shorthand for (walk ast identity f reversed?)" ([ast f] (postwalk ast f false)) ([ast f reversed?] (let [walk #(postwalk % f reversed?)] (f (update-children ast walk 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": "word-list.core\n (:gen-class))\n\n(def word-list '(\"Jack\" \"Bauer\" \"Tony\" \"almeida\" ))\n\n(defn random-from-l", "end": 58, "score": 0.9998278021812439, "start": 54, "tag": "NAME", "value": "Jack" }, { "context": "st.core\n (:gen-class))\n\n(def word-list '(\"Jack\" \"Bauer\" \"Tony\" \"almeida\" ))\n\n(defn random-from-list [lis", "end": 66, "score": 0.9996500611305237, "start": 61, "tag": "NAME", "value": "Bauer" }, { "context": " (:gen-class))\n\n(def word-list '(\"Jack\" \"Bauer\" \"Tony\" \"almeida\" ))\n\n(defn random-from-list [list]\n (", "end": 73, "score": 0.9995905756950378, "start": 69, "tag": "NAME", "value": "Tony" }, { "context": "-class))\n\n(def word-list '(\"Jack\" \"Bauer\" \"Tony\" \"almeida\" ))\n\n(defn random-from-list [list]\n (nth list\n ", "end": 83, "score": 0.9996597170829773, "start": 76, "tag": "NAME", "value": "almeida" } ]
codes/chap-04/word-list/src/word_list/core.clj
bearrundr/functionalLanguage
0
(ns word-list.core (:gen-class)) (def word-list '("Jack" "Bauer" "Tony" "almeida" )) (defn random-from-list [list] (nth list (rand-int (count list))) ) (defn infinite-word [word-list] (cons (random-from-list word-list) (lazy-seq (infinite-word word-list)) ) ) (defn bigfile-write [] (with-open [w (clojure.java.io/writer "/bigfile.txt")] (doseq [word (take 20000000 (infinite-word word-list))] (.write w (str word "\n")))) ) (defn doitslow [x] (Thread/sleep 1000) (println x) (+ 1 x) ) ; dorun, doall (defn slowly [x] (Thread/sleep 1000) (+ x 1)) (defn -main [& args] (println (random-from-list word-list)) (println (random-from-list word-list)) (println (take 3 (infinite-word word-list)) ) (println "bigfile write") ; take long time for writing bigfile so it is commented ; (bigfile-write) (doseq [elem '(1 2 3)] (println elem) ) ; lazy (println "lazy for act") (def lazylist (for [elem '(1 2 3)] (doitslow elem)) ; not run ) (println (realized? lazylist)) ; not run (println lazylist) ; run (println (realized? lazylist)) ; run check is true (println "not lazy for act") ; not lazy act (def notlazylist (doseq [elem '(1 2 3)] (doitslow elem)) ;; directly run ) (println "dorun doall compare") (def foo (map slowly [1 2 3])) (println (realized? foo)) (println foo) (println (realized? foo)) (println "doall") (def foo1 (doall (map slowly [1 2 3]))) (println (realized? foo1)) (println foo1) (println "(type foo1)=" (type foo1)) (def foo2 (dorun (map println [1 2 3]))) (println "(type foo2)=" (type foo2)) )
42400
(ns word-list.core (:gen-class)) (def word-list '("<NAME>" "<NAME>" "<NAME>" "<NAME>" )) (defn random-from-list [list] (nth list (rand-int (count list))) ) (defn infinite-word [word-list] (cons (random-from-list word-list) (lazy-seq (infinite-word word-list)) ) ) (defn bigfile-write [] (with-open [w (clojure.java.io/writer "/bigfile.txt")] (doseq [word (take 20000000 (infinite-word word-list))] (.write w (str word "\n")))) ) (defn doitslow [x] (Thread/sleep 1000) (println x) (+ 1 x) ) ; dorun, doall (defn slowly [x] (Thread/sleep 1000) (+ x 1)) (defn -main [& args] (println (random-from-list word-list)) (println (random-from-list word-list)) (println (take 3 (infinite-word word-list)) ) (println "bigfile write") ; take long time for writing bigfile so it is commented ; (bigfile-write) (doseq [elem '(1 2 3)] (println elem) ) ; lazy (println "lazy for act") (def lazylist (for [elem '(1 2 3)] (doitslow elem)) ; not run ) (println (realized? lazylist)) ; not run (println lazylist) ; run (println (realized? lazylist)) ; run check is true (println "not lazy for act") ; not lazy act (def notlazylist (doseq [elem '(1 2 3)] (doitslow elem)) ;; directly run ) (println "dorun doall compare") (def foo (map slowly [1 2 3])) (println (realized? foo)) (println foo) (println (realized? foo)) (println "doall") (def foo1 (doall (map slowly [1 2 3]))) (println (realized? foo1)) (println foo1) (println "(type foo1)=" (type foo1)) (def foo2 (dorun (map println [1 2 3]))) (println "(type foo2)=" (type foo2)) )
true
(ns word-list.core (:gen-class)) (def word-list '("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" )) (defn random-from-list [list] (nth list (rand-int (count list))) ) (defn infinite-word [word-list] (cons (random-from-list word-list) (lazy-seq (infinite-word word-list)) ) ) (defn bigfile-write [] (with-open [w (clojure.java.io/writer "/bigfile.txt")] (doseq [word (take 20000000 (infinite-word word-list))] (.write w (str word "\n")))) ) (defn doitslow [x] (Thread/sleep 1000) (println x) (+ 1 x) ) ; dorun, doall (defn slowly [x] (Thread/sleep 1000) (+ x 1)) (defn -main [& args] (println (random-from-list word-list)) (println (random-from-list word-list)) (println (take 3 (infinite-word word-list)) ) (println "bigfile write") ; take long time for writing bigfile so it is commented ; (bigfile-write) (doseq [elem '(1 2 3)] (println elem) ) ; lazy (println "lazy for act") (def lazylist (for [elem '(1 2 3)] (doitslow elem)) ; not run ) (println (realized? lazylist)) ; not run (println lazylist) ; run (println (realized? lazylist)) ; run check is true (println "not lazy for act") ; not lazy act (def notlazylist (doseq [elem '(1 2 3)] (doitslow elem)) ;; directly run ) (println "dorun doall compare") (def foo (map slowly [1 2 3])) (println (realized? foo)) (println foo) (println (realized? foo)) (println "doall") (def foo1 (doall (map slowly [1 2 3]))) (println (realized? foo1)) (println foo1) (println "(type foo1)=" (type foo1)) (def foo2 (dorun (map println [1 2 3]))) (println "(type foo2)=" (type foo2)) )
[ { "context": " :required true}}}]})\n\n(def json1-item {:name \"Fred\" :info {:odor \"wet dog\" :human? true}})\n\n(deftest", "end": 2292, "score": 0.9997529983520508, "start": 2288, "tag": "NAME", "value": "Fred" }, { "context": "ired false}}))]\n (is (validate s {:id 1 :name \"john\" :address \"street\"})\n \"should validate wit", "end": 4127, "score": 0.9981732368469238, "start": 4123, "tag": "NAME", "value": "john" }, { "context": " non-required\")\n (is (validate s {:id 1 :name \"john\" :address \"street\" :address2 \"country\"})\n ", "end": 4232, "score": 0.9991419911384583, "start": 4228, "tag": "NAME", "value": "john" }, { "context": "present\" )\n (is (not (validate s {:id 1 :name \"john\" :address2 \"country\"}))\n \"should not valid", "end": 4367, "score": 0.9989810585975647, "start": 4363, "tag": "NAME", "value": "john" }, { "context": "f \"test1.json\"}]\n (is (validate schema {:name \"Jao\" :info {:odor \"roses\" :human? true}}))\n (is (v", "end": 12526, "score": 0.5659982562065125, "start": 12523, "tag": "NAME", "value": "Jao" }, { "context": ":human? true}}))\n (is (validate schema {:name \"Fido\" :info {:odor \"wet dog\" :human? false}}))\n (is", "end": 12603, "score": 0.6564300060272217, "start": 12599, "tag": "NAME", "value": "Fido" }, { "context": "? false}}))\n (is (not (validate schema {:name \"Fido\" :info {:odor 4 :human? false}})))\n (is (not (", "end": 12688, "score": 0.7479574680328369, "start": 12684, "tag": "NAME", "value": "Fido" }, { "context": "false}})))\n (is (not (validate schema {:name \"Jao\" :info {:odor \"roses\" :hu? true}})))\n (is (not", "end": 12765, "score": 0.5494371056556702, "start": 12763, "tag": "NAME", "value": "ao" }, { "context": " 3])))\n (is (validate union-schema {:first-name \"charles\" :last-name \"parker\"}))\n (is (not (validate unio", "end": 13300, "score": 0.9997552633285522, "start": 13293, "tag": "NAME", "value": "charles" }, { "context": "e union-schema {:first-name \"charles\" :last-name \"parker\"}))\n (is (not (validate union-schema {:first-nam", "end": 13320, "score": 0.998600423336029, "start": 13314, "tag": "NAME", "value": "parker" }, { "context": ")\n (is (not (validate union-schema {:first-name \"charles\" :last \"parker\"})))\n (is (not (validate union-sc", "end": 13380, "score": 0.999750018119812, "start": 13373, "tag": "NAME", "value": "charles" }, { "context": "lidate union-schema {:first-name \"charles\" :last \"parker\"})))\n (is (not (validate union-schema {:first-na", "end": 13395, "score": 0.9972845315933228, "start": 13389, "tag": "NAME", "value": "parker" }, { "context": ")\n (is (not (validate union-schema {:first-name \"charles\" :last-name 4})))\n (is (not (validate union-sche", "end": 13456, "score": 0.999750018119812, "start": 13449, "tag": "NAME", "value": "charles" }, { "context": "lidate union-schema {:first-name true :last-name \"parker\"}))))\n\n(deftest array-union\n (is (validate union", "end": 13545, "score": 0.9989851117134094, "start": 13539, "tag": "NAME", "value": "parker" } ]
test/closchema/test/core.clj
jaor/closchema
0
(ns closchema.test.core (:require (cheshire [core :as cheshire]) (closchema [core :as closchema :refer [validate]]) (clojure.java [io :as io])) (:use clojure.test)) (def base-schema {:type "object" :required true :properties {:id {:type "number" :required true} :name {:type "string" :required true} :description {:type "string"}}}) ;; Union type containing either an ID number or a first and last name (def union-schema {:type ["integer" {:type "object" :required true :properties {:first-name {:type "string" :required true} :last-name {:type "string" :required true}}}] :required true}) (def read-schema {:type "object" :required true :properties {:person {:$ref "test1.json" :required true} :dog-name {:type "string" :required true}}}) (def union-array {:type "array" :required true :items {:type ["integer" {:$ref "test1.json"}]}}) (def self-ref (cheshire/decode (slurp (io/resource "self-ref.json")) true)) (def extends-schema {:type "object" :required true :extends {:$ref "test2.json"} :properties {:id {:type "integer" :required true}}}) (def extends-mult {:type "object" :required true :extends [{:$ref "test2.json"} {:type "object" :required true :properties {:name {:type "string" :required true}}}]}) (def json1-item {:name "Fred" :info {:odor "wet dog" :human? true}}) (deftest validate-properties (let [s base-schema] (is (validate s {:id 1 :name "shoe"}) "should accept object with only required properties") (is (validate s {:id 1 :name "shoe" :description "style"}) "should accept object with optional properties") (is (not (validate s {:id 1})) "should not accept when required property is not present") (is (not (validate s {:id "1" :name "bag"})) "should not accept when property type is incorrect") (is (validate s {:id 1 :name "test" :description nil}) "should accept an optional property with value null"))) (deftest validate-false-additional-properties (let [s (merge base-schema {:additionalProperties false})] (is (not (validate s {:id 1 :name "wine" :age "13 years"})) "should not allow any properties that are not defined in schema") (is (validate s {:id 1 :name "wine" :description "good"}) "should allow any properties that are defined in schema as optional"))) (deftest validate-additional-properties-schema (let [s (merge base-schema {:additionalProperties {:type "string"}})] (is (and (validate s {:id 1 :name "wine" :age "13 years" :country "france"}) (not (validate s {:id 1 :name "wine" :age 13}))) "should enforce that all extra properties conform to the schema"))) (deftest validate-additional-properties-fields (let [s (assoc base-schema :properties (merge (base-schema :properties) {:address {:type "string" :required false} :address2 {:type "string" :requires "address" :required false}}))] (is (validate s {:id 1 :name "john" :address "street"}) "should validate with non-required") (is (validate s {:id 1 :name "john" :address "street" :address2 "country"}) "should validate when both are present" ) (is (not (validate s {:id 1 :name "john" :address2 "country"})) "should not validate nem required is not present"))) (deftest validate-pattern-properties (let [s (merge base-schema {:additionalProperties false :patternProperties {"^tes(t)+$" {:type "string"}}})] (is (not (validate s {:id 1 :name "wine" :age "13 years"})) "should not allow any properties that are not defined in schema") (is (validate s {:id 1 :name "wine" :test "good"}) "should allow any properties that are defined in pattern"))) (deftest validate-items-any (is (and (validate {:type "array"} [ 1 2 3]) (validate {:type "array" :items []} [1 "2" 3]) (validate {:type "array"} (map identity [1 2 3])) (validate {:type "array"} #{1 2 3})) "should allow any items")) (deftest validate-items-with-object-schema (let [s1 {:type "array" :items {:type "string"}} s2 {:type "array" :items {:type "object" :required true :properties {:name {:type "string" :required true}}}}] (is (validate s1 []) "should accept empty array") (is (and (validate s1 ["a" "b" "c"]) (validate s2 [{:name "half"} {:name "life"}])) "should accept homogenous array") (is (not (validate s1 ["a" "b" 3])) "should not accept heterogenous array") (is (not (validate s2 [{:name "quake"} {:id 1}])) "should not accept if inner item does not follow item schema"))) (deftest validate-items-with-schema-array (let [s {:type "array" :items [{:type "string" :required true} {:type "string" :required true}]}] (is (and (validate s ["a" "b"]) (not (validate s ["a"])) (not (validate s ["a" 1]))) "should enforce tuple typing") (is (and (validate s ["a" "b" "c"]) (validate s ["a" "b" 1 2 3 {}])) "should allow additional properties to be defined by default"))) (deftest validate-items-with-additional-properties (let [s {:type "array" :items [{:type "number"}] :additionalProperties {:type "string"}}] (is (and (validate s [1 "a" "b" "c"]) (not (validate s [1 2 "a"]))) "should ensure type schema for additional properties") (is (not (validate s ["a" 1])) "should still enforce tuple typing"))) (deftest validate-items-with-additional-properties-disabled (let [s {:type "array" :items [{:type "number"}] :additionalProperties false}] (is (validate s [1]) "should be strict about tuple typing") (is (not (validate s [1 "a"])) "should be strict about tuple typing"))) (deftest validate-items-with-unique-items-set (let [s {:type "array" :uniqueItems true}] (is (validate s [1 2 3]) "of type numbers") (is (validate s ["a" "b"]) "of type strings") (is (validate s [{:a 1} {:b 1} {:a 2}]) "of type objects") (is (not (validate s [1 1])) "of type numbers") (is (not (validate s ["a" "b" "c" "b"])) "of type strings") (is (not (validate s [{:a 1} {:a 2} {:a 1}])) "of type objects"))) (deftest validate-items-with-bounds (let [s1 {:type "array" :minItems 2 :items {:type "number"}} s2 {:type "array" :maxItems 4 :items {:type "number"}} s11 {:type "array" :minItems 2 :maxItems 2 :items {:type "string"}} s12 (merge s1 s2)] (is (validate s1 [1 2]) "minimum length") (is (validate s12 [1 2]) "minimum length") (is (validate s11 ["1" "2"]) "minimum length") (is (validate s2 []) "minimum length") (is (not (validate s1 [1])) "minimum length") (is (not (validate s12 [1])) "minimum length") (is (not (validate s11 ["3"])) "minimum length") (is (validate s1 [1 2 3 4 5]) "maximum length") (is (validate s12 [1 2 3]) "maximum length") (is (validate s11 ["1" "2"]) "maximum length") (is (validate s2 []) "maximum length") (is (not (validate s2 [1 3 4 5 6 7])) "maximum length") (is (not (validate s12 [1 2 3 4 5])) "maximum length") (is (not (validate s11 ["1" "2" "3"])) "maximum length"))) (deftest validate-common-string (let [s {:type "string"}] (is (validate s "foobar") "should validate with string"))) (deftest validate-minimum-string (let [s {:type "string" :minLength 3}] (is (validate s "foobar") "validate if within the lengths") (is (not (validate s "fo")) "not validate if not within the lengths"))) (deftest validate-maximum-string (let [s {:type "string" :maxLength 5}] (is (validate s "fooba") "validate if within the lengths") (is (not (validate s "foobar")) "not validate if not within the lengths"))) (deftest validate-min-max-string (let [s {:type "string" :maxLength 5 :minLength 3}] (is (and (validate s "foo") (validate s "fooba")) "validate if within the lengths" ) (is (and (not (validate s "fo")) (not (validate s "foobar"))) "not validate if not within the lengths"))) (deftest validate-string-pattern (let [s {:type "string" :pattern "^[a-zA-Z0-9]+$"}] (is (and (validate s "fooBar") (validate s "fooBar123") (validate s "123fooBar")) "pattern matches") (is (and (not (validate s "foo-Bar")) (not (validate s "foo_bar"))) "pattern doesn't match")) (is (validate {:type "string" :pattern "es"} "expression"))) (deftest validate-common-numbers (let [s {:type "number"}] (is (and (validate s 1) (validate s -2) (validate s 3.5)) "is a number") (is (not (validate s "2")) "not a number"))) (deftest validate-max-number (let [s {:type '"number" :maximum 5 :exclusiveMaximum true} t {:type '"integer" :maximum 5}] (is (validate s 4) "lower than maximum") (is (and (not (validate s 6)) (not (validate s 5))) "greater or equal than maximum") (is (validate t 4) "lower than maximum") (is (and (not (validate t 6)) (validate t 5)) "greater or equal than maximum"))) (deftest validate-min-number (let [s {:type '"number" :minimum 2 :exclusiveMinimum true} t {:type '"integer" :minimum 2}] (is (validate s 3) "above minimum") (is (and (not (validate s 1)) (not (validate s 2))) "less or equal than minimum") (is (validate t 3) "above minimum") (is (and (not (validate t 1)) (validate t 2)) "less or equal than minimum"))) (deftest validate-max-number (let [s {:type '"number" :maximum 5} t {:type '"integer" :maximum 5}] (is (and (validate s 5) (validate s 4)) "should validate if is lower or equal maximum") (is (not (validate s 6)) "should not validate if not lower nor equal maximum") (is (and (validate t 5) (validate t 4)) "should validate if is lower or equal maximum") (is (not (validate t 6)) "should not validate if not lower nor equal maximum"))) (deftest validate-min-number (let [s {:type '"number" :minimum 2} t {:type '"integer" :minimum 2}] (is (and (validate s 3) (validate s 2)) "should validate if is above or equal minimum") (is (not (validate s 1)) "should not validate if not above nor equal minimum") (is (and (validate t 3) (validate t 2)) "should validate if is above or equal minimum") (is (not (validate t 1)) "should not validate if not above nor equal minimum"))) (deftest validate-divisible-number (let [s {:type "number" :divisibleBy 2} t {:type "integer" :divisibleBy 2}] (is (validate s 4) "number is divisible by 2") (is (not (validate s 5)) "if number it not divisible by 2") (is (validate t 4) "number is divisible by 2") (is (not (validate t 5)) "if number it not divisible by 2"))) (deftest validate-booleans (let [s {:type "boolean"}] (is (validate s false)) (is (validate s true)) (is (not (validate s "2")))) (let [s {:type "object" :properties {:header {:type "boolean"}}}] (is (validate s {:header true})) (is (validate s {:header false})) (is (not (validate s {:header 42}))))) (deftest reference (let [schema {:$ref "test1.json"}] (is (validate schema {:name "Jao" :info {:odor "roses" :human? true}})) (is (validate schema {:name "Fido" :info {:odor "wet dog" :human? false}})) (is (not (validate schema {:name "Fido" :info {:odor 4 :human? false}}))) (is (not (validate schema {:name "Jao" :info {:odor "roses" :hu? true}}))) (is (not (validate schema {:info {:odor "roses" :human? true}})))) (is (validate read-schema {:person json1-item :dog-name "wrinkles"})) (is (not (validate read-schema {:person 5 :dog-name "wrinkles"}))) (is (not (validate read-schema {:person json1-item})))) (deftest union (is (validate union-schema 5)) (is (validate union-schema 123124)) (is (not (validate union-schema 123.124))) (is (not (validate union-schema [1 2 3]))) (is (validate union-schema {:first-name "charles" :last-name "parker"})) (is (not (validate union-schema {:first-name "charles" :last "parker"}))) (is (not (validate union-schema {:first-name "charles" :last-name 4}))) (is (not (validate union-schema {:first-name true :last-name "parker"})))) (deftest array-union (is (validate union-array [1 2 3])) (is (validate union-array [1 2232 314567])) (is (validate union-array [10])) (is (validate union-array [10 json1-item 1423])) (is (validate union-array [json1-item json1-item])) (is (not (validate union-array [json1-item 23.5 json1-item]))) (is (not (validate union-array [1 (assoc json1-item :name false) 2]))) (is (not (validate union-array [1 "yes" 2 3])))) (deftest array-self-ref (is (validate self-ref {:id 1})) (is (validate self-ref {:id 1 :children [{:id 5}]})) (is (validate self-ref {:id 1 :children [{:id 5} {:id 4}]})) (is (validate self-ref {:id 1 :children [{:id 5} {:id 4 :children [{:id 6}]}]})) (is (not (validate self-ref {:id 1 :children [3 4 5]}))) (is (not (validate self-ref {:id 1.5 :children [{:id 5} {:id 4}]}))) (is (not (validate self-ref {:id 1 :children [{:id 5} {:id "a"}]}))) (is (not (validate self-ref {:id 1 :children [{:id 5} {:id 4 :children [{:i 6}]}]}))) (is (not (validate self-ref {:id 1 :children [{:id 5} {:id "a" :children [{:id 6}]}]})))) (deftest null-in-objects (is (validate {:type "object" :properties {:id {:type "null"}}} {:id nil})) (is (not (validate {:type "object" :properties {:id {:type "null"}}} {:id 4}))) (is (not (validate {:type "object" :properties {:id {:type "null"}}} {:id "a"}))) (is (validate {:type "array" :items [{:type "null"} {:type "integer"}]} [nil 1])) (is (not (validate {:type "array" :items [{:type "null"} {:type "integer"}]} [1 nil]))) (is (validate {:type "array" :items [{:type "null"} {:type ["integer" "null"]}]} [nil nil]))) (deftest extends (is (validate extends-schema {:id 1 :human? false :odor "wet dog"})) (is (validate extends-schema {:id -1 :human? true :odor "roses"})) (is (not (validate extends-schema {:id 1 :humn? false :odor "wet-dog"}))) (is (not (validate extends-schema {:id 1 :human? false :odor "rozes"}))) (is (not (validate extends-schema {:id 1.1 :human? false :odor "roses"})))) (deftest multiple-inheritance (is (validate extends-mult {:name "a" :human? false :odor "wet dog"})) (is (validate extends-mult {:name "b" :human? true :odor "roses"})) (is (not (validate extends-mult {:name "a" :odor "wet-dog"}))) (is (not (validate extends-mult {:name 1 :human? false :odor "rozes"}))) (is (not (validate extends-mult {:human? false :odor "roses"})))) (deftest validate-any-type (is (validate {:type "any"} 1)) (is (validate {:type "any"} [1 2 3])) (is (validate {:type "any"} {:a 3}))) (deftest validate-type-string-with-length-limits (is (not (validate {:type "string" :minLength 3} 1))) (is (not (validate {:type "string" :minLength 3} "ab"))) (is (not (validate {:type "string" :maxLength 3} "abcd"))) (is (not (validate {:type "string" :minLength 5 :maxLength 4} "abcde"))) (is (validate {:type "string" :minLength 3 :maxLength 8} "abc")) (is (validate {:type "string" :minLength 3 :maxLength 8} "abcdef"))) (deftest validate-type-integer-with-vector-input (is (not (validate {:type "integer" :minimum 0} [1 2 3])))) (deftest validate-type-array-with-number-input (is (not (validate {:type "array" :items {:type "integer"}} 1)))) ;; Test all combinations of :required array (deftest validate-with-new-required-keys ;; With no :required params, the key is not required (let [schema {:type "object" :properties {:id {:type "integer"}}}] (is (validate schema {}))) ;; With an empty :required param, the key is not required (let [schema {:type "object" :required [] :properties {:id {:type "integer"}}}] (is (validate schema {}))) ;; With a :required param, the key is required (let [schema {:type "object" :required ["id"] :properties {:id {:type "integer"}}}] (is (not (validate schema {})))) ;; With a :required param, a keyword key is accepted (let [schema {:type "object" :required ["id"] :properties {:id {:type "integer"}}}] (is (validate schema {:id 12345}))) ;; With a :required param, a string key is accepted (let [schema {:type "object" :required ["id"] :properties {:id {:type "integer"}}}] (is (validate schema {"id" 12345})))) ;; Test all combinations of :optional and :required (deftest validate-with-required-or-optional-keys ;; With no :required or :optional params, the key is not required (let [schema {:type "object" :properties {:id {:type "integer"}}}] (is (validate schema {}))) ;; With a ":required true" param, the key is required (let [schema {:type "object" :properties {:id {:type "integer" :required true}}}] (is (not (validate schema {})))) ;; With a ":required false" param, the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :required false}}}] (is (validate schema {}))) ;; With an ":optional true" param, the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :optional true}}}] (is (validate schema {}))) ;; With an ":optional false" param, the key is required (let [schema {:type "object" :properties {:id {:type "integer" :optional false}}}] (is (not (validate schema {})))) ;; With ":required false" and ":optional true", the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :required false :optional true}}}] (is (validate schema {}))) ;; With ":required true" and ":optional false", the key is required (let [schema {:type "object" :properties {:id {:type "integer" :required true :optional false}}}] (is (not (validate schema {})))) ;; :required has precedence over :optional ;; With a ":required false" ":optional false" param, the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :required false :optional false}}}] (is (validate schema {}))) ;; :required has precedence over :optional ;; With a ":required true" ":optional true" param, the key is required (let [schema {:type "object" :properties {:id {:type "integer" :required true :optional true}}}] (is (not (validate schema {}))))) (deftest validate-extra-validators (let [schema {:type "object" :properties {:id {:type "integer" :required true}}}] (is (not (validate schema {:id "banana"}))) (is (validate schema {:id "banana"} :extra-validators {"integer" (fn [_] true)})) (is (not (validate schema {:id 10M}))) (is (validate schema {:id 10M} :extra-validators {"integer" (fn [x] (instance? BigDecimal x))}))))
78993
(ns closchema.test.core (:require (cheshire [core :as cheshire]) (closchema [core :as closchema :refer [validate]]) (clojure.java [io :as io])) (:use clojure.test)) (def base-schema {:type "object" :required true :properties {:id {:type "number" :required true} :name {:type "string" :required true} :description {:type "string"}}}) ;; Union type containing either an ID number or a first and last name (def union-schema {:type ["integer" {:type "object" :required true :properties {:first-name {:type "string" :required true} :last-name {:type "string" :required true}}}] :required true}) (def read-schema {:type "object" :required true :properties {:person {:$ref "test1.json" :required true} :dog-name {:type "string" :required true}}}) (def union-array {:type "array" :required true :items {:type ["integer" {:$ref "test1.json"}]}}) (def self-ref (cheshire/decode (slurp (io/resource "self-ref.json")) true)) (def extends-schema {:type "object" :required true :extends {:$ref "test2.json"} :properties {:id {:type "integer" :required true}}}) (def extends-mult {:type "object" :required true :extends [{:$ref "test2.json"} {:type "object" :required true :properties {:name {:type "string" :required true}}}]}) (def json1-item {:name "<NAME>" :info {:odor "wet dog" :human? true}}) (deftest validate-properties (let [s base-schema] (is (validate s {:id 1 :name "shoe"}) "should accept object with only required properties") (is (validate s {:id 1 :name "shoe" :description "style"}) "should accept object with optional properties") (is (not (validate s {:id 1})) "should not accept when required property is not present") (is (not (validate s {:id "1" :name "bag"})) "should not accept when property type is incorrect") (is (validate s {:id 1 :name "test" :description nil}) "should accept an optional property with value null"))) (deftest validate-false-additional-properties (let [s (merge base-schema {:additionalProperties false})] (is (not (validate s {:id 1 :name "wine" :age "13 years"})) "should not allow any properties that are not defined in schema") (is (validate s {:id 1 :name "wine" :description "good"}) "should allow any properties that are defined in schema as optional"))) (deftest validate-additional-properties-schema (let [s (merge base-schema {:additionalProperties {:type "string"}})] (is (and (validate s {:id 1 :name "wine" :age "13 years" :country "france"}) (not (validate s {:id 1 :name "wine" :age 13}))) "should enforce that all extra properties conform to the schema"))) (deftest validate-additional-properties-fields (let [s (assoc base-schema :properties (merge (base-schema :properties) {:address {:type "string" :required false} :address2 {:type "string" :requires "address" :required false}}))] (is (validate s {:id 1 :name "<NAME>" :address "street"}) "should validate with non-required") (is (validate s {:id 1 :name "<NAME>" :address "street" :address2 "country"}) "should validate when both are present" ) (is (not (validate s {:id 1 :name "<NAME>" :address2 "country"})) "should not validate nem required is not present"))) (deftest validate-pattern-properties (let [s (merge base-schema {:additionalProperties false :patternProperties {"^tes(t)+$" {:type "string"}}})] (is (not (validate s {:id 1 :name "wine" :age "13 years"})) "should not allow any properties that are not defined in schema") (is (validate s {:id 1 :name "wine" :test "good"}) "should allow any properties that are defined in pattern"))) (deftest validate-items-any (is (and (validate {:type "array"} [ 1 2 3]) (validate {:type "array" :items []} [1 "2" 3]) (validate {:type "array"} (map identity [1 2 3])) (validate {:type "array"} #{1 2 3})) "should allow any items")) (deftest validate-items-with-object-schema (let [s1 {:type "array" :items {:type "string"}} s2 {:type "array" :items {:type "object" :required true :properties {:name {:type "string" :required true}}}}] (is (validate s1 []) "should accept empty array") (is (and (validate s1 ["a" "b" "c"]) (validate s2 [{:name "half"} {:name "life"}])) "should accept homogenous array") (is (not (validate s1 ["a" "b" 3])) "should not accept heterogenous array") (is (not (validate s2 [{:name "quake"} {:id 1}])) "should not accept if inner item does not follow item schema"))) (deftest validate-items-with-schema-array (let [s {:type "array" :items [{:type "string" :required true} {:type "string" :required true}]}] (is (and (validate s ["a" "b"]) (not (validate s ["a"])) (not (validate s ["a" 1]))) "should enforce tuple typing") (is (and (validate s ["a" "b" "c"]) (validate s ["a" "b" 1 2 3 {}])) "should allow additional properties to be defined by default"))) (deftest validate-items-with-additional-properties (let [s {:type "array" :items [{:type "number"}] :additionalProperties {:type "string"}}] (is (and (validate s [1 "a" "b" "c"]) (not (validate s [1 2 "a"]))) "should ensure type schema for additional properties") (is (not (validate s ["a" 1])) "should still enforce tuple typing"))) (deftest validate-items-with-additional-properties-disabled (let [s {:type "array" :items [{:type "number"}] :additionalProperties false}] (is (validate s [1]) "should be strict about tuple typing") (is (not (validate s [1 "a"])) "should be strict about tuple typing"))) (deftest validate-items-with-unique-items-set (let [s {:type "array" :uniqueItems true}] (is (validate s [1 2 3]) "of type numbers") (is (validate s ["a" "b"]) "of type strings") (is (validate s [{:a 1} {:b 1} {:a 2}]) "of type objects") (is (not (validate s [1 1])) "of type numbers") (is (not (validate s ["a" "b" "c" "b"])) "of type strings") (is (not (validate s [{:a 1} {:a 2} {:a 1}])) "of type objects"))) (deftest validate-items-with-bounds (let [s1 {:type "array" :minItems 2 :items {:type "number"}} s2 {:type "array" :maxItems 4 :items {:type "number"}} s11 {:type "array" :minItems 2 :maxItems 2 :items {:type "string"}} s12 (merge s1 s2)] (is (validate s1 [1 2]) "minimum length") (is (validate s12 [1 2]) "minimum length") (is (validate s11 ["1" "2"]) "minimum length") (is (validate s2 []) "minimum length") (is (not (validate s1 [1])) "minimum length") (is (not (validate s12 [1])) "minimum length") (is (not (validate s11 ["3"])) "minimum length") (is (validate s1 [1 2 3 4 5]) "maximum length") (is (validate s12 [1 2 3]) "maximum length") (is (validate s11 ["1" "2"]) "maximum length") (is (validate s2 []) "maximum length") (is (not (validate s2 [1 3 4 5 6 7])) "maximum length") (is (not (validate s12 [1 2 3 4 5])) "maximum length") (is (not (validate s11 ["1" "2" "3"])) "maximum length"))) (deftest validate-common-string (let [s {:type "string"}] (is (validate s "foobar") "should validate with string"))) (deftest validate-minimum-string (let [s {:type "string" :minLength 3}] (is (validate s "foobar") "validate if within the lengths") (is (not (validate s "fo")) "not validate if not within the lengths"))) (deftest validate-maximum-string (let [s {:type "string" :maxLength 5}] (is (validate s "fooba") "validate if within the lengths") (is (not (validate s "foobar")) "not validate if not within the lengths"))) (deftest validate-min-max-string (let [s {:type "string" :maxLength 5 :minLength 3}] (is (and (validate s "foo") (validate s "fooba")) "validate if within the lengths" ) (is (and (not (validate s "fo")) (not (validate s "foobar"))) "not validate if not within the lengths"))) (deftest validate-string-pattern (let [s {:type "string" :pattern "^[a-zA-Z0-9]+$"}] (is (and (validate s "fooBar") (validate s "fooBar123") (validate s "123fooBar")) "pattern matches") (is (and (not (validate s "foo-Bar")) (not (validate s "foo_bar"))) "pattern doesn't match")) (is (validate {:type "string" :pattern "es"} "expression"))) (deftest validate-common-numbers (let [s {:type "number"}] (is (and (validate s 1) (validate s -2) (validate s 3.5)) "is a number") (is (not (validate s "2")) "not a number"))) (deftest validate-max-number (let [s {:type '"number" :maximum 5 :exclusiveMaximum true} t {:type '"integer" :maximum 5}] (is (validate s 4) "lower than maximum") (is (and (not (validate s 6)) (not (validate s 5))) "greater or equal than maximum") (is (validate t 4) "lower than maximum") (is (and (not (validate t 6)) (validate t 5)) "greater or equal than maximum"))) (deftest validate-min-number (let [s {:type '"number" :minimum 2 :exclusiveMinimum true} t {:type '"integer" :minimum 2}] (is (validate s 3) "above minimum") (is (and (not (validate s 1)) (not (validate s 2))) "less or equal than minimum") (is (validate t 3) "above minimum") (is (and (not (validate t 1)) (validate t 2)) "less or equal than minimum"))) (deftest validate-max-number (let [s {:type '"number" :maximum 5} t {:type '"integer" :maximum 5}] (is (and (validate s 5) (validate s 4)) "should validate if is lower or equal maximum") (is (not (validate s 6)) "should not validate if not lower nor equal maximum") (is (and (validate t 5) (validate t 4)) "should validate if is lower or equal maximum") (is (not (validate t 6)) "should not validate if not lower nor equal maximum"))) (deftest validate-min-number (let [s {:type '"number" :minimum 2} t {:type '"integer" :minimum 2}] (is (and (validate s 3) (validate s 2)) "should validate if is above or equal minimum") (is (not (validate s 1)) "should not validate if not above nor equal minimum") (is (and (validate t 3) (validate t 2)) "should validate if is above or equal minimum") (is (not (validate t 1)) "should not validate if not above nor equal minimum"))) (deftest validate-divisible-number (let [s {:type "number" :divisibleBy 2} t {:type "integer" :divisibleBy 2}] (is (validate s 4) "number is divisible by 2") (is (not (validate s 5)) "if number it not divisible by 2") (is (validate t 4) "number is divisible by 2") (is (not (validate t 5)) "if number it not divisible by 2"))) (deftest validate-booleans (let [s {:type "boolean"}] (is (validate s false)) (is (validate s true)) (is (not (validate s "2")))) (let [s {:type "object" :properties {:header {:type "boolean"}}}] (is (validate s {:header true})) (is (validate s {:header false})) (is (not (validate s {:header 42}))))) (deftest reference (let [schema {:$ref "test1.json"}] (is (validate schema {:name "<NAME>" :info {:odor "roses" :human? true}})) (is (validate schema {:name "<NAME>" :info {:odor "wet dog" :human? false}})) (is (not (validate schema {:name "<NAME>" :info {:odor 4 :human? false}}))) (is (not (validate schema {:name "J<NAME>" :info {:odor "roses" :hu? true}}))) (is (not (validate schema {:info {:odor "roses" :human? true}})))) (is (validate read-schema {:person json1-item :dog-name "wrinkles"})) (is (not (validate read-schema {:person 5 :dog-name "wrinkles"}))) (is (not (validate read-schema {:person json1-item})))) (deftest union (is (validate union-schema 5)) (is (validate union-schema 123124)) (is (not (validate union-schema 123.124))) (is (not (validate union-schema [1 2 3]))) (is (validate union-schema {:first-name "<NAME>" :last-name "<NAME>"})) (is (not (validate union-schema {:first-name "<NAME>" :last "<NAME>"}))) (is (not (validate union-schema {:first-name "<NAME>" :last-name 4}))) (is (not (validate union-schema {:first-name true :last-name "<NAME>"})))) (deftest array-union (is (validate union-array [1 2 3])) (is (validate union-array [1 2232 314567])) (is (validate union-array [10])) (is (validate union-array [10 json1-item 1423])) (is (validate union-array [json1-item json1-item])) (is (not (validate union-array [json1-item 23.5 json1-item]))) (is (not (validate union-array [1 (assoc json1-item :name false) 2]))) (is (not (validate union-array [1 "yes" 2 3])))) (deftest array-self-ref (is (validate self-ref {:id 1})) (is (validate self-ref {:id 1 :children [{:id 5}]})) (is (validate self-ref {:id 1 :children [{:id 5} {:id 4}]})) (is (validate self-ref {:id 1 :children [{:id 5} {:id 4 :children [{:id 6}]}]})) (is (not (validate self-ref {:id 1 :children [3 4 5]}))) (is (not (validate self-ref {:id 1.5 :children [{:id 5} {:id 4}]}))) (is (not (validate self-ref {:id 1 :children [{:id 5} {:id "a"}]}))) (is (not (validate self-ref {:id 1 :children [{:id 5} {:id 4 :children [{:i 6}]}]}))) (is (not (validate self-ref {:id 1 :children [{:id 5} {:id "a" :children [{:id 6}]}]})))) (deftest null-in-objects (is (validate {:type "object" :properties {:id {:type "null"}}} {:id nil})) (is (not (validate {:type "object" :properties {:id {:type "null"}}} {:id 4}))) (is (not (validate {:type "object" :properties {:id {:type "null"}}} {:id "a"}))) (is (validate {:type "array" :items [{:type "null"} {:type "integer"}]} [nil 1])) (is (not (validate {:type "array" :items [{:type "null"} {:type "integer"}]} [1 nil]))) (is (validate {:type "array" :items [{:type "null"} {:type ["integer" "null"]}]} [nil nil]))) (deftest extends (is (validate extends-schema {:id 1 :human? false :odor "wet dog"})) (is (validate extends-schema {:id -1 :human? true :odor "roses"})) (is (not (validate extends-schema {:id 1 :humn? false :odor "wet-dog"}))) (is (not (validate extends-schema {:id 1 :human? false :odor "rozes"}))) (is (not (validate extends-schema {:id 1.1 :human? false :odor "roses"})))) (deftest multiple-inheritance (is (validate extends-mult {:name "a" :human? false :odor "wet dog"})) (is (validate extends-mult {:name "b" :human? true :odor "roses"})) (is (not (validate extends-mult {:name "a" :odor "wet-dog"}))) (is (not (validate extends-mult {:name 1 :human? false :odor "rozes"}))) (is (not (validate extends-mult {:human? false :odor "roses"})))) (deftest validate-any-type (is (validate {:type "any"} 1)) (is (validate {:type "any"} [1 2 3])) (is (validate {:type "any"} {:a 3}))) (deftest validate-type-string-with-length-limits (is (not (validate {:type "string" :minLength 3} 1))) (is (not (validate {:type "string" :minLength 3} "ab"))) (is (not (validate {:type "string" :maxLength 3} "abcd"))) (is (not (validate {:type "string" :minLength 5 :maxLength 4} "abcde"))) (is (validate {:type "string" :minLength 3 :maxLength 8} "abc")) (is (validate {:type "string" :minLength 3 :maxLength 8} "abcdef"))) (deftest validate-type-integer-with-vector-input (is (not (validate {:type "integer" :minimum 0} [1 2 3])))) (deftest validate-type-array-with-number-input (is (not (validate {:type "array" :items {:type "integer"}} 1)))) ;; Test all combinations of :required array (deftest validate-with-new-required-keys ;; With no :required params, the key is not required (let [schema {:type "object" :properties {:id {:type "integer"}}}] (is (validate schema {}))) ;; With an empty :required param, the key is not required (let [schema {:type "object" :required [] :properties {:id {:type "integer"}}}] (is (validate schema {}))) ;; With a :required param, the key is required (let [schema {:type "object" :required ["id"] :properties {:id {:type "integer"}}}] (is (not (validate schema {})))) ;; With a :required param, a keyword key is accepted (let [schema {:type "object" :required ["id"] :properties {:id {:type "integer"}}}] (is (validate schema {:id 12345}))) ;; With a :required param, a string key is accepted (let [schema {:type "object" :required ["id"] :properties {:id {:type "integer"}}}] (is (validate schema {"id" 12345})))) ;; Test all combinations of :optional and :required (deftest validate-with-required-or-optional-keys ;; With no :required or :optional params, the key is not required (let [schema {:type "object" :properties {:id {:type "integer"}}}] (is (validate schema {}))) ;; With a ":required true" param, the key is required (let [schema {:type "object" :properties {:id {:type "integer" :required true}}}] (is (not (validate schema {})))) ;; With a ":required false" param, the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :required false}}}] (is (validate schema {}))) ;; With an ":optional true" param, the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :optional true}}}] (is (validate schema {}))) ;; With an ":optional false" param, the key is required (let [schema {:type "object" :properties {:id {:type "integer" :optional false}}}] (is (not (validate schema {})))) ;; With ":required false" and ":optional true", the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :required false :optional true}}}] (is (validate schema {}))) ;; With ":required true" and ":optional false", the key is required (let [schema {:type "object" :properties {:id {:type "integer" :required true :optional false}}}] (is (not (validate schema {})))) ;; :required has precedence over :optional ;; With a ":required false" ":optional false" param, the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :required false :optional false}}}] (is (validate schema {}))) ;; :required has precedence over :optional ;; With a ":required true" ":optional true" param, the key is required (let [schema {:type "object" :properties {:id {:type "integer" :required true :optional true}}}] (is (not (validate schema {}))))) (deftest validate-extra-validators (let [schema {:type "object" :properties {:id {:type "integer" :required true}}}] (is (not (validate schema {:id "banana"}))) (is (validate schema {:id "banana"} :extra-validators {"integer" (fn [_] true)})) (is (not (validate schema {:id 10M}))) (is (validate schema {:id 10M} :extra-validators {"integer" (fn [x] (instance? BigDecimal x))}))))
true
(ns closchema.test.core (:require (cheshire [core :as cheshire]) (closchema [core :as closchema :refer [validate]]) (clojure.java [io :as io])) (:use clojure.test)) (def base-schema {:type "object" :required true :properties {:id {:type "number" :required true} :name {:type "string" :required true} :description {:type "string"}}}) ;; Union type containing either an ID number or a first and last name (def union-schema {:type ["integer" {:type "object" :required true :properties {:first-name {:type "string" :required true} :last-name {:type "string" :required true}}}] :required true}) (def read-schema {:type "object" :required true :properties {:person {:$ref "test1.json" :required true} :dog-name {:type "string" :required true}}}) (def union-array {:type "array" :required true :items {:type ["integer" {:$ref "test1.json"}]}}) (def self-ref (cheshire/decode (slurp (io/resource "self-ref.json")) true)) (def extends-schema {:type "object" :required true :extends {:$ref "test2.json"} :properties {:id {:type "integer" :required true}}}) (def extends-mult {:type "object" :required true :extends [{:$ref "test2.json"} {:type "object" :required true :properties {:name {:type "string" :required true}}}]}) (def json1-item {:name "PI:NAME:<NAME>END_PI" :info {:odor "wet dog" :human? true}}) (deftest validate-properties (let [s base-schema] (is (validate s {:id 1 :name "shoe"}) "should accept object with only required properties") (is (validate s {:id 1 :name "shoe" :description "style"}) "should accept object with optional properties") (is (not (validate s {:id 1})) "should not accept when required property is not present") (is (not (validate s {:id "1" :name "bag"})) "should not accept when property type is incorrect") (is (validate s {:id 1 :name "test" :description nil}) "should accept an optional property with value null"))) (deftest validate-false-additional-properties (let [s (merge base-schema {:additionalProperties false})] (is (not (validate s {:id 1 :name "wine" :age "13 years"})) "should not allow any properties that are not defined in schema") (is (validate s {:id 1 :name "wine" :description "good"}) "should allow any properties that are defined in schema as optional"))) (deftest validate-additional-properties-schema (let [s (merge base-schema {:additionalProperties {:type "string"}})] (is (and (validate s {:id 1 :name "wine" :age "13 years" :country "france"}) (not (validate s {:id 1 :name "wine" :age 13}))) "should enforce that all extra properties conform to the schema"))) (deftest validate-additional-properties-fields (let [s (assoc base-schema :properties (merge (base-schema :properties) {:address {:type "string" :required false} :address2 {:type "string" :requires "address" :required false}}))] (is (validate s {:id 1 :name "PI:NAME:<NAME>END_PI" :address "street"}) "should validate with non-required") (is (validate s {:id 1 :name "PI:NAME:<NAME>END_PI" :address "street" :address2 "country"}) "should validate when both are present" ) (is (not (validate s {:id 1 :name "PI:NAME:<NAME>END_PI" :address2 "country"})) "should not validate nem required is not present"))) (deftest validate-pattern-properties (let [s (merge base-schema {:additionalProperties false :patternProperties {"^tes(t)+$" {:type "string"}}})] (is (not (validate s {:id 1 :name "wine" :age "13 years"})) "should not allow any properties that are not defined in schema") (is (validate s {:id 1 :name "wine" :test "good"}) "should allow any properties that are defined in pattern"))) (deftest validate-items-any (is (and (validate {:type "array"} [ 1 2 3]) (validate {:type "array" :items []} [1 "2" 3]) (validate {:type "array"} (map identity [1 2 3])) (validate {:type "array"} #{1 2 3})) "should allow any items")) (deftest validate-items-with-object-schema (let [s1 {:type "array" :items {:type "string"}} s2 {:type "array" :items {:type "object" :required true :properties {:name {:type "string" :required true}}}}] (is (validate s1 []) "should accept empty array") (is (and (validate s1 ["a" "b" "c"]) (validate s2 [{:name "half"} {:name "life"}])) "should accept homogenous array") (is (not (validate s1 ["a" "b" 3])) "should not accept heterogenous array") (is (not (validate s2 [{:name "quake"} {:id 1}])) "should not accept if inner item does not follow item schema"))) (deftest validate-items-with-schema-array (let [s {:type "array" :items [{:type "string" :required true} {:type "string" :required true}]}] (is (and (validate s ["a" "b"]) (not (validate s ["a"])) (not (validate s ["a" 1]))) "should enforce tuple typing") (is (and (validate s ["a" "b" "c"]) (validate s ["a" "b" 1 2 3 {}])) "should allow additional properties to be defined by default"))) (deftest validate-items-with-additional-properties (let [s {:type "array" :items [{:type "number"}] :additionalProperties {:type "string"}}] (is (and (validate s [1 "a" "b" "c"]) (not (validate s [1 2 "a"]))) "should ensure type schema for additional properties") (is (not (validate s ["a" 1])) "should still enforce tuple typing"))) (deftest validate-items-with-additional-properties-disabled (let [s {:type "array" :items [{:type "number"}] :additionalProperties false}] (is (validate s [1]) "should be strict about tuple typing") (is (not (validate s [1 "a"])) "should be strict about tuple typing"))) (deftest validate-items-with-unique-items-set (let [s {:type "array" :uniqueItems true}] (is (validate s [1 2 3]) "of type numbers") (is (validate s ["a" "b"]) "of type strings") (is (validate s [{:a 1} {:b 1} {:a 2}]) "of type objects") (is (not (validate s [1 1])) "of type numbers") (is (not (validate s ["a" "b" "c" "b"])) "of type strings") (is (not (validate s [{:a 1} {:a 2} {:a 1}])) "of type objects"))) (deftest validate-items-with-bounds (let [s1 {:type "array" :minItems 2 :items {:type "number"}} s2 {:type "array" :maxItems 4 :items {:type "number"}} s11 {:type "array" :minItems 2 :maxItems 2 :items {:type "string"}} s12 (merge s1 s2)] (is (validate s1 [1 2]) "minimum length") (is (validate s12 [1 2]) "minimum length") (is (validate s11 ["1" "2"]) "minimum length") (is (validate s2 []) "minimum length") (is (not (validate s1 [1])) "minimum length") (is (not (validate s12 [1])) "minimum length") (is (not (validate s11 ["3"])) "minimum length") (is (validate s1 [1 2 3 4 5]) "maximum length") (is (validate s12 [1 2 3]) "maximum length") (is (validate s11 ["1" "2"]) "maximum length") (is (validate s2 []) "maximum length") (is (not (validate s2 [1 3 4 5 6 7])) "maximum length") (is (not (validate s12 [1 2 3 4 5])) "maximum length") (is (not (validate s11 ["1" "2" "3"])) "maximum length"))) (deftest validate-common-string (let [s {:type "string"}] (is (validate s "foobar") "should validate with string"))) (deftest validate-minimum-string (let [s {:type "string" :minLength 3}] (is (validate s "foobar") "validate if within the lengths") (is (not (validate s "fo")) "not validate if not within the lengths"))) (deftest validate-maximum-string (let [s {:type "string" :maxLength 5}] (is (validate s "fooba") "validate if within the lengths") (is (not (validate s "foobar")) "not validate if not within the lengths"))) (deftest validate-min-max-string (let [s {:type "string" :maxLength 5 :minLength 3}] (is (and (validate s "foo") (validate s "fooba")) "validate if within the lengths" ) (is (and (not (validate s "fo")) (not (validate s "foobar"))) "not validate if not within the lengths"))) (deftest validate-string-pattern (let [s {:type "string" :pattern "^[a-zA-Z0-9]+$"}] (is (and (validate s "fooBar") (validate s "fooBar123") (validate s "123fooBar")) "pattern matches") (is (and (not (validate s "foo-Bar")) (not (validate s "foo_bar"))) "pattern doesn't match")) (is (validate {:type "string" :pattern "es"} "expression"))) (deftest validate-common-numbers (let [s {:type "number"}] (is (and (validate s 1) (validate s -2) (validate s 3.5)) "is a number") (is (not (validate s "2")) "not a number"))) (deftest validate-max-number (let [s {:type '"number" :maximum 5 :exclusiveMaximum true} t {:type '"integer" :maximum 5}] (is (validate s 4) "lower than maximum") (is (and (not (validate s 6)) (not (validate s 5))) "greater or equal than maximum") (is (validate t 4) "lower than maximum") (is (and (not (validate t 6)) (validate t 5)) "greater or equal than maximum"))) (deftest validate-min-number (let [s {:type '"number" :minimum 2 :exclusiveMinimum true} t {:type '"integer" :minimum 2}] (is (validate s 3) "above minimum") (is (and (not (validate s 1)) (not (validate s 2))) "less or equal than minimum") (is (validate t 3) "above minimum") (is (and (not (validate t 1)) (validate t 2)) "less or equal than minimum"))) (deftest validate-max-number (let [s {:type '"number" :maximum 5} t {:type '"integer" :maximum 5}] (is (and (validate s 5) (validate s 4)) "should validate if is lower or equal maximum") (is (not (validate s 6)) "should not validate if not lower nor equal maximum") (is (and (validate t 5) (validate t 4)) "should validate if is lower or equal maximum") (is (not (validate t 6)) "should not validate if not lower nor equal maximum"))) (deftest validate-min-number (let [s {:type '"number" :minimum 2} t {:type '"integer" :minimum 2}] (is (and (validate s 3) (validate s 2)) "should validate if is above or equal minimum") (is (not (validate s 1)) "should not validate if not above nor equal minimum") (is (and (validate t 3) (validate t 2)) "should validate if is above or equal minimum") (is (not (validate t 1)) "should not validate if not above nor equal minimum"))) (deftest validate-divisible-number (let [s {:type "number" :divisibleBy 2} t {:type "integer" :divisibleBy 2}] (is (validate s 4) "number is divisible by 2") (is (not (validate s 5)) "if number it not divisible by 2") (is (validate t 4) "number is divisible by 2") (is (not (validate t 5)) "if number it not divisible by 2"))) (deftest validate-booleans (let [s {:type "boolean"}] (is (validate s false)) (is (validate s true)) (is (not (validate s "2")))) (let [s {:type "object" :properties {:header {:type "boolean"}}}] (is (validate s {:header true})) (is (validate s {:header false})) (is (not (validate s {:header 42}))))) (deftest reference (let [schema {:$ref "test1.json"}] (is (validate schema {:name "PI:NAME:<NAME>END_PI" :info {:odor "roses" :human? true}})) (is (validate schema {:name "PI:NAME:<NAME>END_PI" :info {:odor "wet dog" :human? false}})) (is (not (validate schema {:name "PI:NAME:<NAME>END_PI" :info {:odor 4 :human? false}}))) (is (not (validate schema {:name "JPI:NAME:<NAME>END_PI" :info {:odor "roses" :hu? true}}))) (is (not (validate schema {:info {:odor "roses" :human? true}})))) (is (validate read-schema {:person json1-item :dog-name "wrinkles"})) (is (not (validate read-schema {:person 5 :dog-name "wrinkles"}))) (is (not (validate read-schema {:person json1-item})))) (deftest union (is (validate union-schema 5)) (is (validate union-schema 123124)) (is (not (validate union-schema 123.124))) (is (not (validate union-schema [1 2 3]))) (is (validate union-schema {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"})) (is (not (validate union-schema {:first-name "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"}))) (is (not (validate union-schema {:first-name "PI:NAME:<NAME>END_PI" :last-name 4}))) (is (not (validate union-schema {:first-name true :last-name "PI:NAME:<NAME>END_PI"})))) (deftest array-union (is (validate union-array [1 2 3])) (is (validate union-array [1 2232 314567])) (is (validate union-array [10])) (is (validate union-array [10 json1-item 1423])) (is (validate union-array [json1-item json1-item])) (is (not (validate union-array [json1-item 23.5 json1-item]))) (is (not (validate union-array [1 (assoc json1-item :name false) 2]))) (is (not (validate union-array [1 "yes" 2 3])))) (deftest array-self-ref (is (validate self-ref {:id 1})) (is (validate self-ref {:id 1 :children [{:id 5}]})) (is (validate self-ref {:id 1 :children [{:id 5} {:id 4}]})) (is (validate self-ref {:id 1 :children [{:id 5} {:id 4 :children [{:id 6}]}]})) (is (not (validate self-ref {:id 1 :children [3 4 5]}))) (is (not (validate self-ref {:id 1.5 :children [{:id 5} {:id 4}]}))) (is (not (validate self-ref {:id 1 :children [{:id 5} {:id "a"}]}))) (is (not (validate self-ref {:id 1 :children [{:id 5} {:id 4 :children [{:i 6}]}]}))) (is (not (validate self-ref {:id 1 :children [{:id 5} {:id "a" :children [{:id 6}]}]})))) (deftest null-in-objects (is (validate {:type "object" :properties {:id {:type "null"}}} {:id nil})) (is (not (validate {:type "object" :properties {:id {:type "null"}}} {:id 4}))) (is (not (validate {:type "object" :properties {:id {:type "null"}}} {:id "a"}))) (is (validate {:type "array" :items [{:type "null"} {:type "integer"}]} [nil 1])) (is (not (validate {:type "array" :items [{:type "null"} {:type "integer"}]} [1 nil]))) (is (validate {:type "array" :items [{:type "null"} {:type ["integer" "null"]}]} [nil nil]))) (deftest extends (is (validate extends-schema {:id 1 :human? false :odor "wet dog"})) (is (validate extends-schema {:id -1 :human? true :odor "roses"})) (is (not (validate extends-schema {:id 1 :humn? false :odor "wet-dog"}))) (is (not (validate extends-schema {:id 1 :human? false :odor "rozes"}))) (is (not (validate extends-schema {:id 1.1 :human? false :odor "roses"})))) (deftest multiple-inheritance (is (validate extends-mult {:name "a" :human? false :odor "wet dog"})) (is (validate extends-mult {:name "b" :human? true :odor "roses"})) (is (not (validate extends-mult {:name "a" :odor "wet-dog"}))) (is (not (validate extends-mult {:name 1 :human? false :odor "rozes"}))) (is (not (validate extends-mult {:human? false :odor "roses"})))) (deftest validate-any-type (is (validate {:type "any"} 1)) (is (validate {:type "any"} [1 2 3])) (is (validate {:type "any"} {:a 3}))) (deftest validate-type-string-with-length-limits (is (not (validate {:type "string" :minLength 3} 1))) (is (not (validate {:type "string" :minLength 3} "ab"))) (is (not (validate {:type "string" :maxLength 3} "abcd"))) (is (not (validate {:type "string" :minLength 5 :maxLength 4} "abcde"))) (is (validate {:type "string" :minLength 3 :maxLength 8} "abc")) (is (validate {:type "string" :minLength 3 :maxLength 8} "abcdef"))) (deftest validate-type-integer-with-vector-input (is (not (validate {:type "integer" :minimum 0} [1 2 3])))) (deftest validate-type-array-with-number-input (is (not (validate {:type "array" :items {:type "integer"}} 1)))) ;; Test all combinations of :required array (deftest validate-with-new-required-keys ;; With no :required params, the key is not required (let [schema {:type "object" :properties {:id {:type "integer"}}}] (is (validate schema {}))) ;; With an empty :required param, the key is not required (let [schema {:type "object" :required [] :properties {:id {:type "integer"}}}] (is (validate schema {}))) ;; With a :required param, the key is required (let [schema {:type "object" :required ["id"] :properties {:id {:type "integer"}}}] (is (not (validate schema {})))) ;; With a :required param, a keyword key is accepted (let [schema {:type "object" :required ["id"] :properties {:id {:type "integer"}}}] (is (validate schema {:id 12345}))) ;; With a :required param, a string key is accepted (let [schema {:type "object" :required ["id"] :properties {:id {:type "integer"}}}] (is (validate schema {"id" 12345})))) ;; Test all combinations of :optional and :required (deftest validate-with-required-or-optional-keys ;; With no :required or :optional params, the key is not required (let [schema {:type "object" :properties {:id {:type "integer"}}}] (is (validate schema {}))) ;; With a ":required true" param, the key is required (let [schema {:type "object" :properties {:id {:type "integer" :required true}}}] (is (not (validate schema {})))) ;; With a ":required false" param, the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :required false}}}] (is (validate schema {}))) ;; With an ":optional true" param, the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :optional true}}}] (is (validate schema {}))) ;; With an ":optional false" param, the key is required (let [schema {:type "object" :properties {:id {:type "integer" :optional false}}}] (is (not (validate schema {})))) ;; With ":required false" and ":optional true", the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :required false :optional true}}}] (is (validate schema {}))) ;; With ":required true" and ":optional false", the key is required (let [schema {:type "object" :properties {:id {:type "integer" :required true :optional false}}}] (is (not (validate schema {})))) ;; :required has precedence over :optional ;; With a ":required false" ":optional false" param, the key is not required (let [schema {:type "object" :properties {:id {:type "integer" :required false :optional false}}}] (is (validate schema {}))) ;; :required has precedence over :optional ;; With a ":required true" ":optional true" param, the key is required (let [schema {:type "object" :properties {:id {:type "integer" :required true :optional true}}}] (is (not (validate schema {}))))) (deftest validate-extra-validators (let [schema {:type "object" :properties {:id {:type "integer" :required true}}}] (is (not (validate schema {:id "banana"}))) (is (validate schema {:id "banana"} :extra-validators {"integer" (fn [_] true)})) (is (not (validate schema {:id 10M}))) (is (validate schema {:id 10M} :extra-validators {"integer" (fn [x] (instance? BigDecimal x))}))))
[ { "context": " ;; Can handle gh:atom/atom, https://github.com/atom/atom.git or git@github.com:atom/atom.git\n ", "end": 1769, "score": 0.9993150234222412, "start": 1765, "tag": "USERNAME", "value": "atom" }, { "context": " gh:atom/atom, https://github.com/atom/atom.git or git@github.com:atom/atom.git\n (if-let [user-repo (second ", "end": 1796, "score": 0.9987896680831909, "start": 1782, "tag": "EMAIL", "value": "git@github.com" }, { "context": "ttps://github.com/atom/atom.git or git@github.com:atom/atom.git\n (if-let [user-repo (second (re-f", "end": 1801, "score": 0.9993219375610352, "start": 1797, "tag": "USERNAME", "value": "atom" }, { "context": "nd\"\n []\n ;; Sleep needed per https://github.com/babashka/babashka/issues/324#issuecomment-639810098\n (Thr", "end": 2529, "score": 0.9991958737373352, "start": 2521, "tag": "USERNAME", "value": "babashka" } ]
src/cldwalker/bb_clis/cli/misc.clj
cldwalker/bb-clis
31
(ns cldwalker.bb-clis.cli.misc "Misc fns that are useful to bb/clojure clis" (:require [cldwalker.bb-clis.cli :as cli] [clojure.edn :as edn] [clojure.string :as str] [clojure.java.shell :as shell])) ;; Misc ;; ==== (defn open-url "Osx specific way to open url in browser" [url] ;; -n needed to open in big sur. ;; See https://apple.stackexchange.com/questions/406556/macos-big-sur-terminal-command-open-behaviour-changed-and-i-dont-know-how-to (shell/sh "open" "-n" url)) (defn sh "Wrapper around a shell command which fails fast like bash's -e flag. Takes following options: * :dry-run: Prints command instead of executing it" [& args*] (let [default-opts {:is-error-fn #(-> % :exit (not= 0))} [options args] (if (map? (last args*)) [(merge default-opts (last args*)) (drop-last args*)] [default-opts args*])] (if (:dry-run options) (apply println "Command: " args) (let [{:keys [out err] :as res} (apply shell/sh (concat args [:dir (:dir options)]))] (if ((:is-error-fn options) res) (cli/error (format "Command '%s' failed with:\n%s" (str/join " " args) (str out "\n" err))) out))))) ;; Github ;; ====== (defn find-current-user-repo "Returns github user/repository of current directory" [opts] ;; Don't like this knowing about help but don't want error scenarios occurring ;; when running --help (if (:help opts) opts (let [{:keys [out exit err]} (shell/sh "git" "config" "remote.origin.url")] (if (zero? exit) ;; Can handle gh:atom/atom, https://github.com/atom/atom.git or git@github.com:atom/atom.git (if-let [user-repo (second (re-find #"(?:gh|github.com)(?::|/)([^/]+/[^/.\s]+)" out))] user-repo (cli/error "Failed to determine current directory's repository" (pr-str {:out out}))) (cli/error "Failed to determine current directory's repository" (pr-str {:error err :out out})))))) ;; I/O ;; === (defn read-stdin-edn "Read edn on *in* into a coll. Useful to convert a `bb -I --stream` cmd to a script that doesn't require that invocation." [] (take-while #(not (identical? ::EOF %)) (repeatedly #(edn/read {:eof ::EOF} *in*)))) (defn stdin-active? "Detect if stdin is active. Waits for a split second" [] ;; Sleep needed per https://github.com/babashka/babashka/issues/324#issuecomment-639810098 (Thread/sleep 100) (pos? (.available System/in)))
99763
(ns cldwalker.bb-clis.cli.misc "Misc fns that are useful to bb/clojure clis" (:require [cldwalker.bb-clis.cli :as cli] [clojure.edn :as edn] [clojure.string :as str] [clojure.java.shell :as shell])) ;; Misc ;; ==== (defn open-url "Osx specific way to open url in browser" [url] ;; -n needed to open in big sur. ;; See https://apple.stackexchange.com/questions/406556/macos-big-sur-terminal-command-open-behaviour-changed-and-i-dont-know-how-to (shell/sh "open" "-n" url)) (defn sh "Wrapper around a shell command which fails fast like bash's -e flag. Takes following options: * :dry-run: Prints command instead of executing it" [& args*] (let [default-opts {:is-error-fn #(-> % :exit (not= 0))} [options args] (if (map? (last args*)) [(merge default-opts (last args*)) (drop-last args*)] [default-opts args*])] (if (:dry-run options) (apply println "Command: " args) (let [{:keys [out err] :as res} (apply shell/sh (concat args [:dir (:dir options)]))] (if ((:is-error-fn options) res) (cli/error (format "Command '%s' failed with:\n%s" (str/join " " args) (str out "\n" err))) out))))) ;; Github ;; ====== (defn find-current-user-repo "Returns github user/repository of current directory" [opts] ;; Don't like this knowing about help but don't want error scenarios occurring ;; when running --help (if (:help opts) opts (let [{:keys [out exit err]} (shell/sh "git" "config" "remote.origin.url")] (if (zero? exit) ;; Can handle gh:atom/atom, https://github.com/atom/atom.git or <EMAIL>:atom/atom.git (if-let [user-repo (second (re-find #"(?:gh|github.com)(?::|/)([^/]+/[^/.\s]+)" out))] user-repo (cli/error "Failed to determine current directory's repository" (pr-str {:out out}))) (cli/error "Failed to determine current directory's repository" (pr-str {:error err :out out})))))) ;; I/O ;; === (defn read-stdin-edn "Read edn on *in* into a coll. Useful to convert a `bb -I --stream` cmd to a script that doesn't require that invocation." [] (take-while #(not (identical? ::EOF %)) (repeatedly #(edn/read {:eof ::EOF} *in*)))) (defn stdin-active? "Detect if stdin is active. Waits for a split second" [] ;; Sleep needed per https://github.com/babashka/babashka/issues/324#issuecomment-639810098 (Thread/sleep 100) (pos? (.available System/in)))
true
(ns cldwalker.bb-clis.cli.misc "Misc fns that are useful to bb/clojure clis" (:require [cldwalker.bb-clis.cli :as cli] [clojure.edn :as edn] [clojure.string :as str] [clojure.java.shell :as shell])) ;; Misc ;; ==== (defn open-url "Osx specific way to open url in browser" [url] ;; -n needed to open in big sur. ;; See https://apple.stackexchange.com/questions/406556/macos-big-sur-terminal-command-open-behaviour-changed-and-i-dont-know-how-to (shell/sh "open" "-n" url)) (defn sh "Wrapper around a shell command which fails fast like bash's -e flag. Takes following options: * :dry-run: Prints command instead of executing it" [& args*] (let [default-opts {:is-error-fn #(-> % :exit (not= 0))} [options args] (if (map? (last args*)) [(merge default-opts (last args*)) (drop-last args*)] [default-opts args*])] (if (:dry-run options) (apply println "Command: " args) (let [{:keys [out err] :as res} (apply shell/sh (concat args [:dir (:dir options)]))] (if ((:is-error-fn options) res) (cli/error (format "Command '%s' failed with:\n%s" (str/join " " args) (str out "\n" err))) out))))) ;; Github ;; ====== (defn find-current-user-repo "Returns github user/repository of current directory" [opts] ;; Don't like this knowing about help but don't want error scenarios occurring ;; when running --help (if (:help opts) opts (let [{:keys [out exit err]} (shell/sh "git" "config" "remote.origin.url")] (if (zero? exit) ;; Can handle gh:atom/atom, https://github.com/atom/atom.git or PI:EMAIL:<EMAIL>END_PI:atom/atom.git (if-let [user-repo (second (re-find #"(?:gh|github.com)(?::|/)([^/]+/[^/.\s]+)" out))] user-repo (cli/error "Failed to determine current directory's repository" (pr-str {:out out}))) (cli/error "Failed to determine current directory's repository" (pr-str {:error err :out out})))))) ;; I/O ;; === (defn read-stdin-edn "Read edn on *in* into a coll. Useful to convert a `bb -I --stream` cmd to a script that doesn't require that invocation." [] (take-while #(not (identical? ::EOF %)) (repeatedly #(edn/read {:eof ::EOF} *in*)))) (defn stdin-active? "Detect if stdin is active. Waits for a split second" [] ;; Sleep needed per https://github.com/babashka/babashka/issues/324#issuecomment-639810098 (Thread/sleep 100) (pos? (.available System/in)))
[ { "context": "tests for database functions\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under t", "end": 91, "score": 0.9998603463172913, "start": 78, "tag": "NAME", "value": "F.M. de Waard" }, { "context": "s\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under the Apache License, Versio", "end": 116, "score": 0.9999344348907471, "start": 104, "tag": "EMAIL", "value": "fmw@vixu.com" } ]
test/alida/test/db.clj
fmw/alida
6
;; test/alida/test/db.clj: tests for database functions ;; ;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns alida.test.db (:use [clojure.test] [clj-http.fake] [alida.test.helpers :only [with-test-db +test-db+ +test-server+ dummy-routes]] [alida.db] :reload) (:require [clojure.data.json :as json] [clj-http.client :as http-client] [com.ashafa.clutch :as clutch] [alida.util :as util] [alida.crawl :as crawl])) (defn couchdb-id? [s] (re-matches #"^[a-z0-9]{32}$" s)) (defn couchdb-rev? ([s] (couchdb-rev? 1 s)) ([rev-num s] (re-matches (re-pattern (str "^" rev-num "-[a-z0-9]{32}$")) s))) (defn iso-date? [s] (re-matches #"^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{1,4}Z" s)) (defn database-fixture [f] (with-test-db (f))) (use-fixtures :each database-fixture) (deftest test-create-views (is (= (create-views +test-db+) (json/read-json (:body (http-client/get (str +test-server+ +test-db+ "/_design/views"))))))) (def dummy-crawled-pages (with-fake-routes dummy-routes (with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")] @(crawl/directed-crawl "fake-routes" "2012-05-13T21:52:58.114Z" 0 "http://www.dummyhealthfoodstore.com/index.html" [{:selector [:ul#menu :a] :path-filter #"^/products.+" :next [{:selector [[:div#content] [:a]]}]}])))) (deftest test-add-batched-documents (is (= (:doc_count (clutch/database-info +test-db+)) 0)) (do (add-batched-documents +test-db+ dummy-crawled-pages)) (is (= (:doc_count (clutch/database-info +test-db+)) 13))) (deftest test-store-page (let [{:keys [_id _rev score crawled-at uri type crawl-tag crawl-timestamp headers body]} (store-page +test-db+ "store-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/" {:headers {:foo "bar"} :body "..."} 1.0)] (is (couchdb-id? _id)) (is (couchdb-rev? _rev)) (is (= score 1.0)) (is (iso-date? crawled-at)) (is (= uri "http://www.vixu.com/")) (is (= type "crawled-page")) (is (= crawl-tag "store-page-test")) (is (= crawl-timestamp "2012-05-13T21:52:58.114Z")) (is (= headers {:foo "bar"})) (is (= body "...")))) (deftest test-get-page (do (create-views +test-db+)) (let [p1 (store-page +test-db+ "get-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/" {:headers {:foo "bar"} :body "p1"} 1) p2 (store-page +test-db+ "get-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/" {:headers {:foo "bar"} :body "p2"} 1) p3 (store-page +test-db+ "get-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/en/pricing.html" {:headers {:foo "bar"} :body "p3"} 1)] (is (= (get-page +test-db+ "get-page-test" "http://www.vixu.com/") p2)) (is (= (vec (get-page-history +test-db+ "get-page-test" "http://www.vixu.com/" 10)) [p2 p1])))) (deftest test-get-pages-for-crawl-tag-and-timestamp (create-views +test-db+) (let [[p1a p2a p3a p4a p5a p6a p7a p8a p9a p10a] (map #(store-page +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" (str "http://www.vixu.com/p" (inc %)) {:headers {:foo "bar"} :body (str "p" (inc %))} 1) (range 10)) [p1b p2b p3b p4b p5b p6b p7b p8b p9b p10b] (map #(store-page +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-19T04:18:50.678Z" (str "http://www.vixu.com/p" (inc %)) {:headers {:foo "bar"} :body (str "p" (inc %))} 1) (range 10))] (is (= (count (:documents (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" 100))) 10)) (is (= (count (:documents (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-19T04:18:50.678Z" 100))) 10)) (let [pages-a-result-1 (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" 5)] (is (= (count (:documents pages-a-result-1)) 5)) (is (= (sort-by :uri (:documents pages-a-result-1)) [p5a p6a p7a p8a p9a])) (is (= (:next pages-a-result-1) {:uri (:uri p4a) :timestamp (:crawled-at p4a) :id (:_id p4a)})) (let [pages-a-result-2 (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" 5 (:uri (:next pages-a-result-1)) (:timestamp (:next pages-a-result-1)) (:id (:next pages-a-result-1)))] (is (= (count (:documents pages-a-result-2)) 5)) (is (= (sort-by :uri (:documents pages-a-result-2)) [p1a p10a p2a p3a p4a])) (is (= (:next pages-a-result-2) nil)))))) (deftest test-get-scrape-results (create-views +test-db+) (let [dummy-scrape (map (fn [n] {:type "scrape-result" :uri (str "http://www.vixu.com/" n) :crawled-at "2012-05-19T23:30:09.021Z" :crawl-tag "get-scrape-results-test" :crawl-timestamp "2012-05-19T04:18:50.678Z" :title (str "Page " (inc n)) :fulltext (str n " is an interesting number!")}) (range 10)) old-dummy-scrape (map (fn [n] {:type "scrape-result" :uri (str "http://www.vixu.com/" n) :crawled-at "2012-05-19T23:30:09.021Z" :crawl-tag "get-scrape-results-test" :crawl-timestamp "2012-05-18T04:18:50.678Z" :title (str "Page " (inc n)) :fulltext (str n " is an interesting number!")}) (range 10)) dummy-docs (map (fn [x {:keys [id rev]}] (merge x {:_id id :_rev rev})) dummy-scrape (add-batched-documents +test-db+ dummy-scrape))] (do (add-batched-documents +test-db+ old-dummy-scrape)) (is (= (count (:documents (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-19T04:18:50.678Z" 100))) 10)) (is (= (count (:documents (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-18T04:18:50.678Z" 100))) 10)) (let [scrape-results-a (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-19T04:18:50.678Z" 5)] (is (= (count (:documents scrape-results-a)) 5)) (is (= (:documents scrape-results-a) (take 5 (reverse dummy-docs)))) (is (= (:next scrape-results-a) {:uri (:uri (nth dummy-docs 4)) :id (:_id (nth dummy-docs 4))})) (let [scrape-results-b (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-19T04:18:50.678Z" 5 (:uri (:next scrape-results-a)) (:id (:next scrape-results-a)))] (is (= (count (:documents scrape-results-b)) 5)) (is (= (:documents scrape-results-b) (take-last 5 (reverse dummy-docs)))) (is (= (:next scrape-results-b) nil))))))
16753
;; test/alida/test/db.clj: tests for database functions ;; ;; Copyright 2012, <NAME> & Vixu.com <<EMAIL>>. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns alida.test.db (:use [clojure.test] [clj-http.fake] [alida.test.helpers :only [with-test-db +test-db+ +test-server+ dummy-routes]] [alida.db] :reload) (:require [clojure.data.json :as json] [clj-http.client :as http-client] [com.ashafa.clutch :as clutch] [alida.util :as util] [alida.crawl :as crawl])) (defn couchdb-id? [s] (re-matches #"^[a-z0-9]{32}$" s)) (defn couchdb-rev? ([s] (couchdb-rev? 1 s)) ([rev-num s] (re-matches (re-pattern (str "^" rev-num "-[a-z0-9]{32}$")) s))) (defn iso-date? [s] (re-matches #"^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{1,4}Z" s)) (defn database-fixture [f] (with-test-db (f))) (use-fixtures :each database-fixture) (deftest test-create-views (is (= (create-views +test-db+) (json/read-json (:body (http-client/get (str +test-server+ +test-db+ "/_design/views"))))))) (def dummy-crawled-pages (with-fake-routes dummy-routes (with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")] @(crawl/directed-crawl "fake-routes" "2012-05-13T21:52:58.114Z" 0 "http://www.dummyhealthfoodstore.com/index.html" [{:selector [:ul#menu :a] :path-filter #"^/products.+" :next [{:selector [[:div#content] [:a]]}]}])))) (deftest test-add-batched-documents (is (= (:doc_count (clutch/database-info +test-db+)) 0)) (do (add-batched-documents +test-db+ dummy-crawled-pages)) (is (= (:doc_count (clutch/database-info +test-db+)) 13))) (deftest test-store-page (let [{:keys [_id _rev score crawled-at uri type crawl-tag crawl-timestamp headers body]} (store-page +test-db+ "store-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/" {:headers {:foo "bar"} :body "..."} 1.0)] (is (couchdb-id? _id)) (is (couchdb-rev? _rev)) (is (= score 1.0)) (is (iso-date? crawled-at)) (is (= uri "http://www.vixu.com/")) (is (= type "crawled-page")) (is (= crawl-tag "store-page-test")) (is (= crawl-timestamp "2012-05-13T21:52:58.114Z")) (is (= headers {:foo "bar"})) (is (= body "...")))) (deftest test-get-page (do (create-views +test-db+)) (let [p1 (store-page +test-db+ "get-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/" {:headers {:foo "bar"} :body "p1"} 1) p2 (store-page +test-db+ "get-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/" {:headers {:foo "bar"} :body "p2"} 1) p3 (store-page +test-db+ "get-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/en/pricing.html" {:headers {:foo "bar"} :body "p3"} 1)] (is (= (get-page +test-db+ "get-page-test" "http://www.vixu.com/") p2)) (is (= (vec (get-page-history +test-db+ "get-page-test" "http://www.vixu.com/" 10)) [p2 p1])))) (deftest test-get-pages-for-crawl-tag-and-timestamp (create-views +test-db+) (let [[p1a p2a p3a p4a p5a p6a p7a p8a p9a p10a] (map #(store-page +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" (str "http://www.vixu.com/p" (inc %)) {:headers {:foo "bar"} :body (str "p" (inc %))} 1) (range 10)) [p1b p2b p3b p4b p5b p6b p7b p8b p9b p10b] (map #(store-page +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-19T04:18:50.678Z" (str "http://www.vixu.com/p" (inc %)) {:headers {:foo "bar"} :body (str "p" (inc %))} 1) (range 10))] (is (= (count (:documents (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" 100))) 10)) (is (= (count (:documents (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-19T04:18:50.678Z" 100))) 10)) (let [pages-a-result-1 (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" 5)] (is (= (count (:documents pages-a-result-1)) 5)) (is (= (sort-by :uri (:documents pages-a-result-1)) [p5a p6a p7a p8a p9a])) (is (= (:next pages-a-result-1) {:uri (:uri p4a) :timestamp (:crawled-at p4a) :id (:_id p4a)})) (let [pages-a-result-2 (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" 5 (:uri (:next pages-a-result-1)) (:timestamp (:next pages-a-result-1)) (:id (:next pages-a-result-1)))] (is (= (count (:documents pages-a-result-2)) 5)) (is (= (sort-by :uri (:documents pages-a-result-2)) [p1a p10a p2a p3a p4a])) (is (= (:next pages-a-result-2) nil)))))) (deftest test-get-scrape-results (create-views +test-db+) (let [dummy-scrape (map (fn [n] {:type "scrape-result" :uri (str "http://www.vixu.com/" n) :crawled-at "2012-05-19T23:30:09.021Z" :crawl-tag "get-scrape-results-test" :crawl-timestamp "2012-05-19T04:18:50.678Z" :title (str "Page " (inc n)) :fulltext (str n " is an interesting number!")}) (range 10)) old-dummy-scrape (map (fn [n] {:type "scrape-result" :uri (str "http://www.vixu.com/" n) :crawled-at "2012-05-19T23:30:09.021Z" :crawl-tag "get-scrape-results-test" :crawl-timestamp "2012-05-18T04:18:50.678Z" :title (str "Page " (inc n)) :fulltext (str n " is an interesting number!")}) (range 10)) dummy-docs (map (fn [x {:keys [id rev]}] (merge x {:_id id :_rev rev})) dummy-scrape (add-batched-documents +test-db+ dummy-scrape))] (do (add-batched-documents +test-db+ old-dummy-scrape)) (is (= (count (:documents (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-19T04:18:50.678Z" 100))) 10)) (is (= (count (:documents (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-18T04:18:50.678Z" 100))) 10)) (let [scrape-results-a (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-19T04:18:50.678Z" 5)] (is (= (count (:documents scrape-results-a)) 5)) (is (= (:documents scrape-results-a) (take 5 (reverse dummy-docs)))) (is (= (:next scrape-results-a) {:uri (:uri (nth dummy-docs 4)) :id (:_id (nth dummy-docs 4))})) (let [scrape-results-b (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-19T04:18:50.678Z" 5 (:uri (:next scrape-results-a)) (:id (:next scrape-results-a)))] (is (= (count (:documents scrape-results-b)) 5)) (is (= (:documents scrape-results-b) (take-last 5 (reverse dummy-docs)))) (is (= (:next scrape-results-b) nil))))))
true
;; test/alida/test/db.clj: tests for database functions ;; ;; Copyright 2012, PI:NAME:<NAME>END_PI & Vixu.com <PI:EMAIL:<EMAIL>END_PI>. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns alida.test.db (:use [clojure.test] [clj-http.fake] [alida.test.helpers :only [with-test-db +test-db+ +test-server+ dummy-routes]] [alida.db] :reload) (:require [clojure.data.json :as json] [clj-http.client :as http-client] [com.ashafa.clutch :as clutch] [alida.util :as util] [alida.crawl :as crawl])) (defn couchdb-id? [s] (re-matches #"^[a-z0-9]{32}$" s)) (defn couchdb-rev? ([s] (couchdb-rev? 1 s)) ([rev-num s] (re-matches (re-pattern (str "^" rev-num "-[a-z0-9]{32}$")) s))) (defn iso-date? [s] (re-matches #"^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{1,4}Z" s)) (defn database-fixture [f] (with-test-db (f))) (use-fixtures :each database-fixture) (deftest test-create-views (is (= (create-views +test-db+) (json/read-json (:body (http-client/get (str +test-server+ +test-db+ "/_design/views"))))))) (def dummy-crawled-pages (with-fake-routes dummy-routes (with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")] @(crawl/directed-crawl "fake-routes" "2012-05-13T21:52:58.114Z" 0 "http://www.dummyhealthfoodstore.com/index.html" [{:selector [:ul#menu :a] :path-filter #"^/products.+" :next [{:selector [[:div#content] [:a]]}]}])))) (deftest test-add-batched-documents (is (= (:doc_count (clutch/database-info +test-db+)) 0)) (do (add-batched-documents +test-db+ dummy-crawled-pages)) (is (= (:doc_count (clutch/database-info +test-db+)) 13))) (deftest test-store-page (let [{:keys [_id _rev score crawled-at uri type crawl-tag crawl-timestamp headers body]} (store-page +test-db+ "store-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/" {:headers {:foo "bar"} :body "..."} 1.0)] (is (couchdb-id? _id)) (is (couchdb-rev? _rev)) (is (= score 1.0)) (is (iso-date? crawled-at)) (is (= uri "http://www.vixu.com/")) (is (= type "crawled-page")) (is (= crawl-tag "store-page-test")) (is (= crawl-timestamp "2012-05-13T21:52:58.114Z")) (is (= headers {:foo "bar"})) (is (= body "...")))) (deftest test-get-page (do (create-views +test-db+)) (let [p1 (store-page +test-db+ "get-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/" {:headers {:foo "bar"} :body "p1"} 1) p2 (store-page +test-db+ "get-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/" {:headers {:foo "bar"} :body "p2"} 1) p3 (store-page +test-db+ "get-page-test" "2012-05-13T21:52:58.114Z" "http://www.vixu.com/en/pricing.html" {:headers {:foo "bar"} :body "p3"} 1)] (is (= (get-page +test-db+ "get-page-test" "http://www.vixu.com/") p2)) (is (= (vec (get-page-history +test-db+ "get-page-test" "http://www.vixu.com/" 10)) [p2 p1])))) (deftest test-get-pages-for-crawl-tag-and-timestamp (create-views +test-db+) (let [[p1a p2a p3a p4a p5a p6a p7a p8a p9a p10a] (map #(store-page +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" (str "http://www.vixu.com/p" (inc %)) {:headers {:foo "bar"} :body (str "p" (inc %))} 1) (range 10)) [p1b p2b p3b p4b p5b p6b p7b p8b p9b p10b] (map #(store-page +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-19T04:18:50.678Z" (str "http://www.vixu.com/p" (inc %)) {:headers {:foo "bar"} :body (str "p" (inc %))} 1) (range 10))] (is (= (count (:documents (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" 100))) 10)) (is (= (count (:documents (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-19T04:18:50.678Z" 100))) 10)) (let [pages-a-result-1 (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" 5)] (is (= (count (:documents pages-a-result-1)) 5)) (is (= (sort-by :uri (:documents pages-a-result-1)) [p5a p6a p7a p8a p9a])) (is (= (:next pages-a-result-1) {:uri (:uri p4a) :timestamp (:crawled-at p4a) :id (:_id p4a)})) (let [pages-a-result-2 (get-pages-for-crawl-tag-and-timestamp +test-db+ "get-pages-for-crawl-tag-and-timestamp-test" "2012-05-13T21:52:58.114Z" 5 (:uri (:next pages-a-result-1)) (:timestamp (:next pages-a-result-1)) (:id (:next pages-a-result-1)))] (is (= (count (:documents pages-a-result-2)) 5)) (is (= (sort-by :uri (:documents pages-a-result-2)) [p1a p10a p2a p3a p4a])) (is (= (:next pages-a-result-2) nil)))))) (deftest test-get-scrape-results (create-views +test-db+) (let [dummy-scrape (map (fn [n] {:type "scrape-result" :uri (str "http://www.vixu.com/" n) :crawled-at "2012-05-19T23:30:09.021Z" :crawl-tag "get-scrape-results-test" :crawl-timestamp "2012-05-19T04:18:50.678Z" :title (str "Page " (inc n)) :fulltext (str n " is an interesting number!")}) (range 10)) old-dummy-scrape (map (fn [n] {:type "scrape-result" :uri (str "http://www.vixu.com/" n) :crawled-at "2012-05-19T23:30:09.021Z" :crawl-tag "get-scrape-results-test" :crawl-timestamp "2012-05-18T04:18:50.678Z" :title (str "Page " (inc n)) :fulltext (str n " is an interesting number!")}) (range 10)) dummy-docs (map (fn [x {:keys [id rev]}] (merge x {:_id id :_rev rev})) dummy-scrape (add-batched-documents +test-db+ dummy-scrape))] (do (add-batched-documents +test-db+ old-dummy-scrape)) (is (= (count (:documents (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-19T04:18:50.678Z" 100))) 10)) (is (= (count (:documents (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-18T04:18:50.678Z" 100))) 10)) (let [scrape-results-a (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-19T04:18:50.678Z" 5)] (is (= (count (:documents scrape-results-a)) 5)) (is (= (:documents scrape-results-a) (take 5 (reverse dummy-docs)))) (is (= (:next scrape-results-a) {:uri (:uri (nth dummy-docs 4)) :id (:_id (nth dummy-docs 4))})) (let [scrape-results-b (get-scrape-results +test-db+ "get-scrape-results-test" "2012-05-19T04:18:50.678Z" 5 (:uri (:next scrape-results-a)) (:id (:next scrape-results-a)))] (is (= (count (:documents scrape-results-b)) 5)) (is (= (:documents scrape-results-b) (take-last 5 (reverse dummy-docs)))) (is (= (:next scrape-results-b) nil))))))
[ { "context": "he same as R's quantile type=7.\n Transcribed from Jason Davies; https://github.com/jasondavies/science.js/blob/m", "end": 2757, "score": 0.9998769760131836, "start": 2745, "tag": "NAME", "value": "Jason Davies" }, { "context": "Transcribed from Jason Davies; https://github.com/jasondavies/science.js/blob/master/src/stats/quantiles.js\"\n ", "end": 2789, "score": 0.9930272698402405, "start": 2778, "tag": "USERNAME", "value": "jasondavies" } ]
src/cljx/c2/maths.cljx
jlin/c2
172
^:clj (ns c2.maths (:use [c2.util :only [combine-with]])) ^:cljs (ns c2.maths (:use-macros [c2.util :only [combine-with]])) (def Pi Math/PI) (def Tau (* 2 Pi)) (def e Math/E) (def radians-per-degree (/ Pi 180)) (defn rad [x] (* radians-per-degree x)) (defn deg [x] (/ x radians-per-degree)) (defn sin [x] (Math/sin x)) (defn asin [x] (Math/asin x)) (defn cos [x] (Math/cos x)) (defn acos [x] (Math/acos x)) (defn tan [x] (Math/tan x)) (defn atan [x] (Math/atan x)) (defn expt ([x] (Math/exp x)) ([x y] (Math/pow x y))) (defn sq [x] (expt x 2)) (defn sqrt [x] (Math/sqrt x)) (defn floor [x] (Math/floor x)) (defn ceil [x] (Math/ceil x)) (defn abs [x] (Math/abs x)) (defn log ([x] (Math/log x)) ([base x] (/ (Math/log x) (Math/log base)))) (defn ^:clj log10 [x] (Math/log10 x)) (defn ^:cljs log10 [x] (/ (.log js/Math x) (.-LN10 js/Math))) (defn extent "Returns 2-vector of min and max elements in xs." [xs] [(apply min xs) (apply max xs)]) ;;TODO: replace mean and median with smarter algorithms for better performance. (defn mean "Arithemetic mean of collection" [xs] (/ (reduce + xs) (count xs))) (defn median "Median of a collection." [xs] (let [sorted (sort xs) n (count xs)] (cond (= n 1) (first sorted) (odd? n) (nth sorted (/ (inc n) 2)) :else (let [mid (/ n 2)] (mean [(nth sorted (floor mid)) (nth sorted (ceil mid))]))))) (defn irange "Inclusive range; same as core/range, but includes the end." ([start] (range start)) ([start end] (concat (range start end) [end])) ([start end step] (let [r (range start end step)] (if (== (mod (first r) step) (mod end step)) (concat r [end]) r)))) (defn within? "Checks if bottom <= x <= top." [x [bottom top]] (<= bottom x top)) ;;element-by-element arithmetic ;;Code modified from Incanter (defn add ([& args] (reduce (fn [A B] (combine-with A B clojure.core/+ add)) args))) (defn sub ([& args] (if (= (count args) 1) (combine-with 0 (first args) clojure.core/- sub) (reduce (fn [A B] (combine-with A B clojure.core/- sub)) args)))) (defn mul ([& args] (reduce (fn [A B] (combine-with A B clojure.core/* mul)) args))) (defn div ([& args] (if (= (count args) 1) (combine-with 1 (first args) clojure.core// div) (reduce (fn [A B] (combine-with A B clojure.core// div)) args)))) (defn quantile "Returns the quantiles of a dataset. Kwargs: > *:probs*: ntiles of the data to return, defaults to `[0 0.25 0.5 0.75 1]` Algorithm is the same as R's quantile type=7. Transcribed from Jason Davies; https://github.com/jasondavies/science.js/blob/master/src/stats/quantiles.js" [data & {:keys [probs] :or {probs [0 0.25 0.5 0.75 1]}}] (let [xs (into [] (sort data)) n-1 (dec (count xs))] (for [q probs] (let [index (inc (* q n-1)) lo (int (floor index)) h (- index lo) a (xs (dec lo))] (if (= h 0) a (+ a (* h (- (xs lo) a))))))))
64448
^:clj (ns c2.maths (:use [c2.util :only [combine-with]])) ^:cljs (ns c2.maths (:use-macros [c2.util :only [combine-with]])) (def Pi Math/PI) (def Tau (* 2 Pi)) (def e Math/E) (def radians-per-degree (/ Pi 180)) (defn rad [x] (* radians-per-degree x)) (defn deg [x] (/ x radians-per-degree)) (defn sin [x] (Math/sin x)) (defn asin [x] (Math/asin x)) (defn cos [x] (Math/cos x)) (defn acos [x] (Math/acos x)) (defn tan [x] (Math/tan x)) (defn atan [x] (Math/atan x)) (defn expt ([x] (Math/exp x)) ([x y] (Math/pow x y))) (defn sq [x] (expt x 2)) (defn sqrt [x] (Math/sqrt x)) (defn floor [x] (Math/floor x)) (defn ceil [x] (Math/ceil x)) (defn abs [x] (Math/abs x)) (defn log ([x] (Math/log x)) ([base x] (/ (Math/log x) (Math/log base)))) (defn ^:clj log10 [x] (Math/log10 x)) (defn ^:cljs log10 [x] (/ (.log js/Math x) (.-LN10 js/Math))) (defn extent "Returns 2-vector of min and max elements in xs." [xs] [(apply min xs) (apply max xs)]) ;;TODO: replace mean and median with smarter algorithms for better performance. (defn mean "Arithemetic mean of collection" [xs] (/ (reduce + xs) (count xs))) (defn median "Median of a collection." [xs] (let [sorted (sort xs) n (count xs)] (cond (= n 1) (first sorted) (odd? n) (nth sorted (/ (inc n) 2)) :else (let [mid (/ n 2)] (mean [(nth sorted (floor mid)) (nth sorted (ceil mid))]))))) (defn irange "Inclusive range; same as core/range, but includes the end." ([start] (range start)) ([start end] (concat (range start end) [end])) ([start end step] (let [r (range start end step)] (if (== (mod (first r) step) (mod end step)) (concat r [end]) r)))) (defn within? "Checks if bottom <= x <= top." [x [bottom top]] (<= bottom x top)) ;;element-by-element arithmetic ;;Code modified from Incanter (defn add ([& args] (reduce (fn [A B] (combine-with A B clojure.core/+ add)) args))) (defn sub ([& args] (if (= (count args) 1) (combine-with 0 (first args) clojure.core/- sub) (reduce (fn [A B] (combine-with A B clojure.core/- sub)) args)))) (defn mul ([& args] (reduce (fn [A B] (combine-with A B clojure.core/* mul)) args))) (defn div ([& args] (if (= (count args) 1) (combine-with 1 (first args) clojure.core// div) (reduce (fn [A B] (combine-with A B clojure.core// div)) args)))) (defn quantile "Returns the quantiles of a dataset. Kwargs: > *:probs*: ntiles of the data to return, defaults to `[0 0.25 0.5 0.75 1]` Algorithm is the same as R's quantile type=7. Transcribed from <NAME>; https://github.com/jasondavies/science.js/blob/master/src/stats/quantiles.js" [data & {:keys [probs] :or {probs [0 0.25 0.5 0.75 1]}}] (let [xs (into [] (sort data)) n-1 (dec (count xs))] (for [q probs] (let [index (inc (* q n-1)) lo (int (floor index)) h (- index lo) a (xs (dec lo))] (if (= h 0) a (+ a (* h (- (xs lo) a))))))))
true
^:clj (ns c2.maths (:use [c2.util :only [combine-with]])) ^:cljs (ns c2.maths (:use-macros [c2.util :only [combine-with]])) (def Pi Math/PI) (def Tau (* 2 Pi)) (def e Math/E) (def radians-per-degree (/ Pi 180)) (defn rad [x] (* radians-per-degree x)) (defn deg [x] (/ x radians-per-degree)) (defn sin [x] (Math/sin x)) (defn asin [x] (Math/asin x)) (defn cos [x] (Math/cos x)) (defn acos [x] (Math/acos x)) (defn tan [x] (Math/tan x)) (defn atan [x] (Math/atan x)) (defn expt ([x] (Math/exp x)) ([x y] (Math/pow x y))) (defn sq [x] (expt x 2)) (defn sqrt [x] (Math/sqrt x)) (defn floor [x] (Math/floor x)) (defn ceil [x] (Math/ceil x)) (defn abs [x] (Math/abs x)) (defn log ([x] (Math/log x)) ([base x] (/ (Math/log x) (Math/log base)))) (defn ^:clj log10 [x] (Math/log10 x)) (defn ^:cljs log10 [x] (/ (.log js/Math x) (.-LN10 js/Math))) (defn extent "Returns 2-vector of min and max elements in xs." [xs] [(apply min xs) (apply max xs)]) ;;TODO: replace mean and median with smarter algorithms for better performance. (defn mean "Arithemetic mean of collection" [xs] (/ (reduce + xs) (count xs))) (defn median "Median of a collection." [xs] (let [sorted (sort xs) n (count xs)] (cond (= n 1) (first sorted) (odd? n) (nth sorted (/ (inc n) 2)) :else (let [mid (/ n 2)] (mean [(nth sorted (floor mid)) (nth sorted (ceil mid))]))))) (defn irange "Inclusive range; same as core/range, but includes the end." ([start] (range start)) ([start end] (concat (range start end) [end])) ([start end step] (let [r (range start end step)] (if (== (mod (first r) step) (mod end step)) (concat r [end]) r)))) (defn within? "Checks if bottom <= x <= top." [x [bottom top]] (<= bottom x top)) ;;element-by-element arithmetic ;;Code modified from Incanter (defn add ([& args] (reduce (fn [A B] (combine-with A B clojure.core/+ add)) args))) (defn sub ([& args] (if (= (count args) 1) (combine-with 0 (first args) clojure.core/- sub) (reduce (fn [A B] (combine-with A B clojure.core/- sub)) args)))) (defn mul ([& args] (reduce (fn [A B] (combine-with A B clojure.core/* mul)) args))) (defn div ([& args] (if (= (count args) 1) (combine-with 1 (first args) clojure.core// div) (reduce (fn [A B] (combine-with A B clojure.core// div)) args)))) (defn quantile "Returns the quantiles of a dataset. Kwargs: > *:probs*: ntiles of the data to return, defaults to `[0 0.25 0.5 0.75 1]` Algorithm is the same as R's quantile type=7. Transcribed from PI:NAME:<NAME>END_PI; https://github.com/jasondavies/science.js/blob/master/src/stats/quantiles.js" [data & {:keys [probs] :or {probs [0 0.25 0.5 0.75 1]}}] (let [xs (into [] (sort data)) n-1 (dec (count xs))] (for [q probs] (let [index (inc (* q n-1)) lo (int (floor index)) h (- index lo) a (xs (dec lo))] (if (= h 0) a (+ a (* h (- (xs lo) a))))))))
[ { "context": "exploration-results-original-text\n (str \"N - Yes: Ann, Brenda / No: Charles\\n\"\n \"NE - Yes: Deborah / No: ", "end": 3832, "score": 0.9994386434555054, "start": 3821, "tag": "NAME", "value": "Ann, Brenda" }, { "context": "s-original-text\n (str \"N - Yes: Ann, Brenda / No: Charles\\n\"\n \"NE - Yes: Deborah / No: Edward, Frank\\", "end": 3846, "score": 0.9983078837394714, "start": 3839, "tag": "NAME", "value": "Charles" }, { "context": "es: Ann, Brenda / No: Charles\\n\"\n \"NE - Yes: Deborah / No: Edward, Frank\\n\"\n \"SE - Yes: Gary, Ha", "end": 3875, "score": 0.9978551268577576, "start": 3868, "tag": "NAME", "value": "Deborah" }, { "context": "a / No: Charles\\n\"\n \"NE - Yes: Deborah / No: Edward, Frank\\n\"\n \"SE - Yes: Gary, Harold / No: Irene\\n\"\n", "end": 3895, "score": 0.8875594735145569, "start": 3882, "tag": "NAME", "value": "Edward, Frank" }, { "context": ": Deborah / No: Edward, Frank\\n\"\n \"SE - Yes: Gary, Harold / No: Irene\\n\"\n \"S - Yes: James / No: Karen", "end": 3929, "score": 0.9997611045837402, "start": 3917, "tag": "NAME", "value": "Gary, Harold" }, { "context": "ard, Frank\\n\"\n \"SE - Yes: Gary, Harold / No: Irene\\n\"\n \"S - Yes: James / No: Karen, Linda\\n\"\n ", "end": 3941, "score": 0.9981819987297058, "start": 3936, "tag": "NAME", "value": "Irene" }, { "context": " Yes: Gary, Harold / No: Irene\\n\"\n \"S - Yes: James / No: Karen, Linda\\n\"\n \"SW - No: Ann, Brend", "end": 3967, "score": 0.9996113181114197, "start": 3962, "tag": "NAME", "value": "James" }, { "context": "Harold / No: Irene\\n\"\n \"S - Yes: James / No: Karen, Linda\\n\"\n \"SW - No: Ann, Brenda, Charles, Deborah", "end": 3986, "score": 0.9634357690811157, "start": 3974, "tag": "NAME", "value": "Karen, Linda" }, { "context": " Yes: James / No: Karen, Linda\\n\"\n \"SW - No: Ann, Brenda, Charles, Deborah\\n\"\n \"NW - Yes: Ed", "end": 4010, "score": 0.9995453953742981, "start": 4007, "tag": "NAME", "value": "Ann" }, { "context": " James / No: Karen, Linda\\n\"\n \"SW - No: Ann, Brenda, Charles, Deborah\\n\"\n \"NW - Yes: Edward, Fr", "end": 4018, "score": 0.9137906432151794, "start": 4012, "tag": "NAME", "value": "Brenda" }, { "context": " No: Karen, Linda\\n\"\n \"SW - No: Ann, Brenda, Charles, Deborah\\n\"\n \"NW - Yes: Edward, Frank, Gary", "end": 4027, "score": 0.9956129193305969, "start": 4020, "tag": "NAME", "value": "Charles" }, { "context": "n, Linda\\n\"\n \"SW - No: Ann, Brenda, Charles, Deborah\\n\"\n \"NW - Yes: Edward, Frank, Gary Harold\\n", "end": 4036, "score": 0.8518123626708984, "start": 4029, "tag": "NAME", "value": "Deborah" }, { "context": "Ann, Brenda, Charles, Deborah\\n\"\n \"NW - Yes: Edward, Frank, Gary Harold\\n\"))\n\n(defn create-exploratio", "end": 4064, "score": 0.9989235401153564, "start": 4058, "tag": "NAME", "value": "Edward" }, { "context": "nda, Charles, Deborah\\n\"\n \"NW - Yes: Edward, Frank, Gary Harold\\n\"))\n\n(defn create-exploration-resul", "end": 4071, "score": 0.9249113202095032, "start": 4066, "tag": "NAME", "value": "Frank" }, { "context": "arles, Deborah\\n\"\n \"NW - Yes: Edward, Frank, Gary Harold\\n\"))\n\n(defn create-exploration-results-text [syst", "end": 4084, "score": 0.9992929697036743, "start": 4073, "tag": "NAME", "value": "Gary Harold" } ]
src/fossa/dungeon.cljs
foobardog/fossa
1
(ns fossa.dungeon (:require [cljs.pprint :as c.pprint] [brute.entity :as b.entity] [phzr.button :as p.button] [phzr.core :as p.core] [phzr.game-object-factory :as p.factory] [phzr.loader :as p.loader] [phzr.point :as p.point] [phzr.signal :as p.signal] [phzr.sprite :as p.sprite] [phzr.world :as p.world] [fossa.component :as f.component] [fossa.dialogue :as f.dialogue] [fossa.exploration-path :as f.exploration-path] [fossa.group :as f.group] [fossa.input :as f.input] [fossa.party-member :as f.party-member] [fossa.rendering :as f.rendering])) (def initial-dungeon [{:paths #{ :north :south :southwest :northeast } :safe-path :southwest :liars 2} {:paths #{ :north :northeast :southeast } :safe-path :north :liars 1} {:paths #{ :south :northwest :southwest } :safe-path :northwest :liars 4}]) (defn preload-assets [loader] (doto loader (p.loader/spritesheet "button" "assets/images/button.png" 190 49 2) (p.loader/image "paper" "assets/images/paper.png") (p.loader/spritesheet "square-button" "assets/images/square_button.png" 49 49 2) (p.loader/spritesheet "direction-arrows" "assets/images/direction_arrows.png" 50 50 6) (p.loader/image "dungeon-status" "assets/images/panel.png"))) (defn update-dungeon-status [system] (let [{:keys [text]} (f.component/get-singleton-component system f.component/DungeonStatus) {:keys [rooms current-room]} (f.component/get-singleton-component system f.component/Dungeon) rooms-left (- (count rooms) current-room) liar-count (f.party-member/get-liar-count system)] (p.core/pset! text :text (c.pprint/cl-format nil "Subject #2 Rank:~%TERRIBLE~%Room(s) left: ~D~%Exp. Subjects: ~D" rooms-left liar-count)) system)) (defn initialize-dungeon [system] (let [dungeon-entity (first (b.entity/get-all-entities-with-component system f.component/Dungeon)) dungeon (b.entity/get-component system dungeon-entity f.component/Dungeon) current-room ((:rooms dungeon) (:current-room dungeon))] (-> system (f.exploration-path/update-exploration-paths (:paths current-room)) (f.group/move-all-members-back-to-unassigned) (f.party-member/set-liars (:liars current-room)) (update-dungeon-status)))) (defn create-explore-button [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-button (p.factory/button factory 0 0 "button" nil nil 0 0 1 0) phzr-text (p.factory/text factory 0 0 "Explore")] (f.input/set-event-callback! phzr-button :on-input-up :pressed-explore-button) (p.button/add-child phzr-button phzr-text) (doto phzr-text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :fill "#000000") (p.core/pset! :align "center") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :x 95) (p.core/pset! :y 25)) phzr-button)) (defn create-exploration-results-sprite [system] (let [phzr-game (:phzr-game system)] (doto (f.rendering/create-phzr-sprite phzr-game "exploration-results" "paper" 500 600) (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :angle -15) (p.core/pset! :input-enabled true) (-> :input (p.core/pset! :priority-id 0)) (-> :events :on-input-down (p.signal/add (fn [sprite _] (p.core/pset! sprite :visible false)))) (p.core/pset! :visible false) (p.core/pset! :z 16r40)))) (def exploration-results-original-text (str "N - Yes: Ann, Brenda / No: Charles\n" "NE - Yes: Deborah / No: Edward, Frank\n" "SE - Yes: Gary, Harold / No: Irene\n" "S - Yes: James / No: Karen, Linda\n" "SW - No: Ann, Brenda, Charles, Deborah\n" "NW - Yes: Edward, Frank, Gary Harold\n")) (defn create-exploration-results-text [system sprite] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-text (p.factory/text factory 0 0 exploration-results-original-text)] (p.sprite/add-child sprite phzr-text) (doto phzr-text (p.core/pset! :font "Just Me Again Down Here, MV Boli, Apple Chancery, Zapfino, cursive") (p.core/pset! :font-size 40) (p.core/pset! :fill "#000000") (p.core/pset! :align "left") (p.core/pset! :word-wrap true) (p.core/pset! :word-wrap-width (- (:width sprite) 150)) (p.core/pset! :x -270) (p.core/pset! :y -460)))) (def movement-results-original-text "We moved SW. It was UNSAFE!!!") (defn create-movement-results-text [system sprite] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-text (p.factory/text factory 0 0 movement-results-original-text)] (p.sprite/add-child sprite phzr-text) (doto phzr-text (p.core/pset! :visible false) (p.core/pset! :font "Just Me Again Down Here, MV Boli, Apple Chancery, Zapfino, cursive") (p.core/pset! :font-size 40) (p.core/pset! :fill "#ff0000") (p.core/pset! :align "center") (p.core/pset! :word-wrap true) (p.core/pset! :word-wrap-width (- (:width sprite) 150)) (p.core/pset! :x -210) (p.core/pset! :y -160)))) (defn create-exploration-results-navigation [system sprite] (let [phzr-game (:phzr-game system) factory (:add phzr-game) previous-text (p.factory/text factory 0 0 "<Previous") next-text (p.factory/text factory 0 0 "Next>")] (doseq [text [previous-text next-text]] (p.sprite/add-child sprite text) (doto text (p.core/pset! :font "Just Me Again Down Here, MV Boli, Apple Chancery, Zapfino, cursive") (p.core/pset! :font-size 60) (p.core/pset! :fill "#0000ff") (-> :events :on-input-over (p.signal/add (fn [sprite _] (p.core/pset! sprite :fill "#ff0000")))) (-> :events :on-input-out (p.signal/add (fn [sprite _] (p.core/pset! sprite :fill "#0000ff")))) (p.core/pset! :input-enabled true) (-> :input (p.core/pset! :priority-id 1)) (p.core/pset! :y -525))) (doto previous-text (f.input/set-event-callback! :on-input-up :pressed-previous-results) (p.core/pset! :align "left") (p.core/pset! :x -270)) (doto next-text (f.input/set-event-callback! :on-input-up :pressed-next-results) (p.core/pset! :align "right") (p.core/pset! :x 145)) (f.component/->ResultsNavigation 0 previous-text next-text))) (defn create-results-button [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-button (p.factory/button factory 0 526 "button" nil nil 0 0 1 0) phzr-text (p.factory/text factory 0 0 "Results")] (f.input/set-event-callback! phzr-button :on-input-up :pressed-results-button) (p.button/add-child phzr-button phzr-text) (doto phzr-text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :fill "#000000") (p.core/pset! :align "center") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :x 95) (p.core/pset! :y 25)) phzr-button)) (defn create-movement-button-icon [factory button i] (let [button-icon (p.factory/sprite factory 0 0 "direction-arrows" i)] (p.button/add-child button button-icon))) (declare direction-abbreviation) (defn create-movement-button-text [factory button i] (let [direction (f.exploration-path/directions i) direction-text (direction-abbreviation direction) button-text (p.factory/text factory 0 0 direction-text)] (p.button/add-child button button-text) (doto button-text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :font-size 15) (p.core/pset! :fill "#ffffff") (p.core/pset! :align "center") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :x 25) (p.core/pset! :y 25)))) (def movement-buttons-coordinates [[50 0] [100 25] [100 75] [50 100] [0 75] [0 25]]) (defn create-movement-button [button-map i factory group] (let [direction (f.exploration-path/directions i) tint (f.exploration-path/hex-tints i) coordinates (movement-buttons-coordinates i) button (p.factory/button factory 0 0 "square-button" nil nil 0 0 1 0 group)] (create-movement-button-icon factory button i) (create-movement-button-text factory button i) (p.core/pset! button :tint tint) (p.core/pset! button :x (coordinates 0)) (p.core/pset! button :y (coordinates 1)) (assoc button-map direction button))) (defn create-movement-buttons [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) group (f.group/create-phzr-group phzr-game "movement buttons" 600 415) button-map (reduce #(create-movement-button %1 %2 factory group) {} (range 6)) entity (b.entity/create-entity)] (p.core/pset! group :z 16r30) (-> system (b.entity/add-entity entity) (b.entity/add-component entity (f.component/->MovementButtons button-map group))))) (def dungeon-status-original-text "Subject #2 Rank:\nTERRIBLE\nRoom(s) left: 10\nExp. Subjects: 10") (defn create-dungeon-status [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) sprite (f.rendering/create-phzr-sprite phzr-game "dungeon-status" "dungeon-status" 890 80) text (p.factory/text factory 0 0 dungeon-status-original-text) dungeon-status (b.entity/create-entity)] (doto sprite (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :visible true) (p.core/pset! :z 16r30) (p.sprite/add-child text)) (doto text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :font-size 20) (p.core/pset! :fill "#000000") (p.core/pset! :align "left") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :word-wrap true) (p.core/pset! :word-wrap-width 250) (p.core/pset! :x -230) (p.core/pset! :y -10)) (-> system (b.entity/add-entity dungeon-status) (b.entity/add-component dungeon-status (f.component/->DungeonStatus sprite text))))) (defn create-entities [system] (let [dungeon (b.entity/create-entity) explore-button (b.entity/create-entity) explore-phzr-button (create-explore-button system) exploration-results (b.entity/create-entity) exploration-results-sprite (create-exploration-results-sprite system) exploration-results-text (create-exploration-results-text system exploration-results-sprite) movement-results (b.entity/create-entity) movement-results-text (create-movement-results-text system exploration-results-sprite) results-navigation (create-exploration-results-navigation system exploration-results-sprite) results-button-entity (b.entity/create-entity) results-button (create-results-button system)] (-> system (b.entity/add-entity dungeon) (b.entity/add-component dungeon (f.component/->Dungeon initial-dungeon 0)) (b.entity/add-entity explore-button) (b.entity/add-component explore-button (f.component/->ExploreButton explore-phzr-button)) (b.entity/add-entity exploration-results) (b.entity/add-component exploration-results (f.component/->Sprite exploration-results-sprite)) (b.entity/add-component exploration-results (f.component/->Text exploration-results-text)) (b.entity/add-component exploration-results results-navigation) (b.entity/add-component exploration-results (f.component/->ExplorationResults [])) (b.entity/add-entity movement-results) (b.entity/add-component movement-results (f.component/->MovementResults {} movement-results-text)) (b.entity/add-entity results-button-entity) (b.entity/add-component results-button-entity (f.component/->ResultsButton results-button)) (create-movement-buttons) (create-dungeon-status) (initialize-dungeon)))) (def liar-truth-percentage 0.25) (defn get-answer [party-member is-it-safe?] (cond (not (:is-liar party-member)) is-it-safe? is-it-safe? false ; Always lie if it's safe :else (> (rand) liar-truth-percentage))) ; Otherwise, small chance of telling the truth (false) (defn explore-path [system result-map direction explorers safe-path] (let [explorers-components (map #(b.entity/get-component system % f.component/PartyMember) explorers) is-it-safe? (= direction safe-path) grouped-members (group-by #(get-answer % is-it-safe?) explorers-components)] (assoc result-map direction grouped-members))) (defn explore-paths [system paths safe-path] (let [exploration-paths (map #(f.exploration-path/get-exploration-path-by-direction system %) paths)] (->> (zipmap paths (map #(f.component/get-group-members-from-entity system %) exploration-paths)) (reduce #(explore-path system %1 (get %2 0) (get %2 1) safe-path) {})))) (def direction-abbreviation {:north "N" :northeast "NE" :southeast "SE" :south "S" :southwest "SW" :northwest "NW"}) (defn get-direction-result [[direction answers]] (let [yes-answers (map :member-name (get answers true)) no-answers (map :member-name (get answers false))] (c.pprint/cl-format nil "~A- Yes:~[ no one~*~:;~{ ~A~}~]/ No:~[ no one~*~:;~{ ~A~}~]~%" (get direction-abbreviation direction) (count yes-answers) yes-answers (count no-answers) no-answers))) (defn get-exploration-text [results-map] (let [lines (map get-direction-result results-map)] (apply str lines))) (defn update-movement-text [system] (let [{:keys [current-result]} (f.component/get-singleton-component system f.component/ResultsNavigation) {:keys [previous-results movement-results-text]} (f.component/get-singleton-component system f.component/MovementResults)] (if-let [{:keys [direction was-safe?]} (get previous-results current-result)] (doto movement-results-text (p.core/pset! :fill (if was-safe? "#009900" "#ff0000")) (p.core/pset! :text (c.pprint/cl-format nil "- We moved ~A. It was ~:[UNSAFE!!!~;safe.~] -" (get direction-abbreviation direction) was-safe?)) (p.core/pset! :visible true)) (p.core/pset! movement-results-text :visible false)) system)) (defn update-results-navigation [system] (let [results-navigation (first (b.entity/get-all-entities-with-component system f.component/ResultsNavigation)) {:keys [current-result previous-text next-text]} (b.entity/get-component system results-navigation f.component/ResultsNavigation) exploration-results-entity (first (b.entity/get-all-entities-with-component system f.component/ExplorationResults)) exploration-results (:previous-results (b.entity/get-component system exploration-results-entity f.component/ExplorationResults)) exploration-results-text (f.component/get-phzr-text-from-entity system exploration-results-entity) new-exploration-text (get-exploration-text (get exploration-results current-result))] (p.core/pset! previous-text :visible (not= current-result 0)) (p.core/pset! next-text :visible (not= current-result (dec (count exploration-results)))) (p.core/pset! exploration-results-text :text new-exploration-text) (update-movement-text system))) (defn get-current-dungeon-room [system] (let [{:keys [rooms current-room]} (f.component/get-singleton-component system f.component/Dungeon)] (rooms current-room))) (defn do-exploration [system] (let [current-room (get-current-dungeon-room system) exploration-results-map (explore-paths system (:paths current-room) (:safe-path current-room)) exploration-results-string (get-exploration-text exploration-results-map) exploration-results-entity (first (b.entity/get-all-entities-with-component system f.component/ExplorationResults)) exploration-results-component (b.entity/get-component system exploration-results-entity f.component/ExplorationResults) previous-results (:previous-results exploration-results-component) exploration-results-sprite (f.component/get-phzr-sprite-from-entity system exploration-results-entity) exploration-results-text (f.component/get-phzr-text-from-entity system exploration-results-entity) results-navigation-entity (first (b.entity/get-all-entities-with-component system f.component/ResultsNavigation)) {:keys [previous-text next-text]} (b.entity/get-component system results-navigation-entity f.component/ResultsNavigation)] (p.core/pset! exploration-results-text :text exploration-results-string) (p.core/pset! exploration-results-sprite :visible true) (-> system :phzr-game :world (p.world/bring-to-top exploration-results-sprite)) (-> system (assoc :explored-this-turn true) (b.entity/add-component exploration-results-entity (f.component/->ExplorationResults (conj previous-results exploration-results-map))) (b.entity/add-component results-navigation-entity (f.component/->ResultsNavigation (count previous-results) previous-text next-text)) (update-results-navigation)))) (defn handle-explore-button [system] (let [explore-button (:phzr-button (f.component/get-singleton-component system f.component/ExploreButton)) unassigned-members (:members (f.component/get-singleton-component system f.component/UnassignedMembers f.component/Group)) exploration-results-sprite (:phzr-sprite (f.component/get-singleton-component system f.component/ExplorationResults f.component/Sprite))] (p.core/pset! explore-button :visible (and (empty? unassigned-members) (not (:visible exploration-results-sprite)))) (if (f.input/event-happened-in-system? system :pressed-explore-button) (-> system (f.input/consume-event-from-system :pressed-explore-button) (do-exploration)) system))) (defn handle-results-navigation [system] (let [results-navigation-entity (f.component/get-singleton-entity system f.component/ResultsNavigation) {:keys [current-result] :as result-navigation-component} (f.component/get-singleton-component system f.component/ResultsNavigation) previous-pressed? (f.input/event-happened-in-system? system :pressed-previous-results) next-pressed? (f.input/event-happened-in-system? system :pressed-next-results) exploration-results-count (-> (f.component/get-singleton-component system f.component/ExplorationResults) :previous-results count)] (if (or previous-pressed? next-pressed?) (let [updated-result (if previous-pressed? (max (dec current-result) 0) (min (inc current-result) (dec exploration-results-count)))] (-> system (as-> sys (if previous-pressed? (f.input/consume-event-from-system sys :pressed-previous-results) (f.input/consume-event-from-system sys :pressed-next-results))) (b.entity/add-component results-navigation-entity (assoc result-navigation-component :current-result updated-result)) (update-results-navigation))) system))) (defn handle-results-button [system] (let [{:keys [phzr-button]} (f.component/get-singleton-component system f.component/ResultsButton) exploration-results-count (-> (f.component/get-singleton-component system f.component/ExplorationResults) :previous-results count) exploration-results-sprite (:phzr-sprite (f.component/get-singleton-component system f.component/ExplorationResults f.component/Sprite)) results-navigation-entity (f.component/get-singleton-entity system f.component/ResultsNavigation) results-navigation-component (f.component/get-singleton-component system f.component/ResultsNavigation)] (p.core/pset! phzr-button :visible (and (not (:visible exploration-results-sprite)) (> exploration-results-count 0))) (if (f.input/event-happened-in-system? system :pressed-results-button) (-> system (f.input/consume-event-from-system :pressed-results-button) (b.entity/add-component results-navigation-entity (assoc results-navigation-component :current-result (dec exploration-results-count))) (update-results-navigation) (as-> sys (do (p.core/pset! exploration-results-sprite :visible true) (-> sys :phzr-game :world (p.world/bring-to-top exploration-results-sprite)) sys))) system))) (defn move-to-next-room [system direction] (let [dungeon (f.component/get-singleton-component system f.component/Dungeon) dungeon-entity (f.component/get-singleton-entity system f.component/Dungeon) {:keys [safe-path]} (get-current-dungeon-room system) movement-results-entity (f.component/get-singleton-entity system f.component/MovementResults) movement-results-component (f.component/get-singleton-component system f.component/MovementResults) previous-results (:previous-results movement-results-component) current-exploration (dec (count (:previous-results (f.component/get-singleton-component system f.component/ExplorationResults)))) move-is-safe? (= direction safe-path) new-previous-results (assoc previous-results current-exploration {:direction direction :was-safe? move-is-safe?})] (-> system (b.entity/add-component movement-results-entity (assoc movement-results-component :previous-results new-previous-results)) (assoc :explored-this-turn false) (b.entity/add-component dungeon-entity (f.component/->Dungeon (:rooms dungeon) (inc (:current-room dungeon)))) (initialize-dungeon) (f.dialogue/start-dialogue (if move-is-safe? :right-path :wrong-path))))) (defn handle-movement-buttons [system] (let [exploration-results-sprite (:phzr-sprite (f.component/get-singleton-component system f.component/ExplorationResults f.component/Sprite)) {:keys [movement-buttons group]} (f.component/get-singleton-component system f.component/MovementButtons) direction-pressed (get (first (filter #(f.input/just-pressed (get % 1)) movement-buttons)) 0) {:keys [paths]} (get-current-dungeon-room system)] (p.core/pset! group :visible (and (not (:visible exploration-results-sprite)) (:explored-this-turn system))) (doseq [[direction button] movement-buttons] (p.core/pset! button :visible (paths direction))) (if (and (f.input/blackout-expired? system :just-pressed-movement-button) direction-pressed) (-> system (f.input/update-blackout-property :just-pressed-movement-button) (move-to-next-room direction-pressed)) system))) (defn process-one-game-tick [system] (-> system (handle-results-button) (handle-explore-button) (handle-results-navigation) (handle-movement-buttons)))
30709
(ns fossa.dungeon (:require [cljs.pprint :as c.pprint] [brute.entity :as b.entity] [phzr.button :as p.button] [phzr.core :as p.core] [phzr.game-object-factory :as p.factory] [phzr.loader :as p.loader] [phzr.point :as p.point] [phzr.signal :as p.signal] [phzr.sprite :as p.sprite] [phzr.world :as p.world] [fossa.component :as f.component] [fossa.dialogue :as f.dialogue] [fossa.exploration-path :as f.exploration-path] [fossa.group :as f.group] [fossa.input :as f.input] [fossa.party-member :as f.party-member] [fossa.rendering :as f.rendering])) (def initial-dungeon [{:paths #{ :north :south :southwest :northeast } :safe-path :southwest :liars 2} {:paths #{ :north :northeast :southeast } :safe-path :north :liars 1} {:paths #{ :south :northwest :southwest } :safe-path :northwest :liars 4}]) (defn preload-assets [loader] (doto loader (p.loader/spritesheet "button" "assets/images/button.png" 190 49 2) (p.loader/image "paper" "assets/images/paper.png") (p.loader/spritesheet "square-button" "assets/images/square_button.png" 49 49 2) (p.loader/spritesheet "direction-arrows" "assets/images/direction_arrows.png" 50 50 6) (p.loader/image "dungeon-status" "assets/images/panel.png"))) (defn update-dungeon-status [system] (let [{:keys [text]} (f.component/get-singleton-component system f.component/DungeonStatus) {:keys [rooms current-room]} (f.component/get-singleton-component system f.component/Dungeon) rooms-left (- (count rooms) current-room) liar-count (f.party-member/get-liar-count system)] (p.core/pset! text :text (c.pprint/cl-format nil "Subject #2 Rank:~%TERRIBLE~%Room(s) left: ~D~%Exp. Subjects: ~D" rooms-left liar-count)) system)) (defn initialize-dungeon [system] (let [dungeon-entity (first (b.entity/get-all-entities-with-component system f.component/Dungeon)) dungeon (b.entity/get-component system dungeon-entity f.component/Dungeon) current-room ((:rooms dungeon) (:current-room dungeon))] (-> system (f.exploration-path/update-exploration-paths (:paths current-room)) (f.group/move-all-members-back-to-unassigned) (f.party-member/set-liars (:liars current-room)) (update-dungeon-status)))) (defn create-explore-button [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-button (p.factory/button factory 0 0 "button" nil nil 0 0 1 0) phzr-text (p.factory/text factory 0 0 "Explore")] (f.input/set-event-callback! phzr-button :on-input-up :pressed-explore-button) (p.button/add-child phzr-button phzr-text) (doto phzr-text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :fill "#000000") (p.core/pset! :align "center") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :x 95) (p.core/pset! :y 25)) phzr-button)) (defn create-exploration-results-sprite [system] (let [phzr-game (:phzr-game system)] (doto (f.rendering/create-phzr-sprite phzr-game "exploration-results" "paper" 500 600) (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :angle -15) (p.core/pset! :input-enabled true) (-> :input (p.core/pset! :priority-id 0)) (-> :events :on-input-down (p.signal/add (fn [sprite _] (p.core/pset! sprite :visible false)))) (p.core/pset! :visible false) (p.core/pset! :z 16r40)))) (def exploration-results-original-text (str "N - Yes: <NAME> / No: <NAME>\n" "NE - Yes: <NAME> / No: <NAME>\n" "SE - Yes: <NAME> / No: <NAME>\n" "S - Yes: <NAME> / No: <NAME>\n" "SW - No: <NAME>, <NAME>, <NAME>, <NAME>\n" "NW - Yes: <NAME>, <NAME>, <NAME>\n")) (defn create-exploration-results-text [system sprite] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-text (p.factory/text factory 0 0 exploration-results-original-text)] (p.sprite/add-child sprite phzr-text) (doto phzr-text (p.core/pset! :font "Just Me Again Down Here, MV Boli, Apple Chancery, Zapfino, cursive") (p.core/pset! :font-size 40) (p.core/pset! :fill "#000000") (p.core/pset! :align "left") (p.core/pset! :word-wrap true) (p.core/pset! :word-wrap-width (- (:width sprite) 150)) (p.core/pset! :x -270) (p.core/pset! :y -460)))) (def movement-results-original-text "We moved SW. It was UNSAFE!!!") (defn create-movement-results-text [system sprite] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-text (p.factory/text factory 0 0 movement-results-original-text)] (p.sprite/add-child sprite phzr-text) (doto phzr-text (p.core/pset! :visible false) (p.core/pset! :font "Just Me Again Down Here, MV Boli, Apple Chancery, Zapfino, cursive") (p.core/pset! :font-size 40) (p.core/pset! :fill "#ff0000") (p.core/pset! :align "center") (p.core/pset! :word-wrap true) (p.core/pset! :word-wrap-width (- (:width sprite) 150)) (p.core/pset! :x -210) (p.core/pset! :y -160)))) (defn create-exploration-results-navigation [system sprite] (let [phzr-game (:phzr-game system) factory (:add phzr-game) previous-text (p.factory/text factory 0 0 "<Previous") next-text (p.factory/text factory 0 0 "Next>")] (doseq [text [previous-text next-text]] (p.sprite/add-child sprite text) (doto text (p.core/pset! :font "Just Me Again Down Here, MV Boli, Apple Chancery, Zapfino, cursive") (p.core/pset! :font-size 60) (p.core/pset! :fill "#0000ff") (-> :events :on-input-over (p.signal/add (fn [sprite _] (p.core/pset! sprite :fill "#ff0000")))) (-> :events :on-input-out (p.signal/add (fn [sprite _] (p.core/pset! sprite :fill "#0000ff")))) (p.core/pset! :input-enabled true) (-> :input (p.core/pset! :priority-id 1)) (p.core/pset! :y -525))) (doto previous-text (f.input/set-event-callback! :on-input-up :pressed-previous-results) (p.core/pset! :align "left") (p.core/pset! :x -270)) (doto next-text (f.input/set-event-callback! :on-input-up :pressed-next-results) (p.core/pset! :align "right") (p.core/pset! :x 145)) (f.component/->ResultsNavigation 0 previous-text next-text))) (defn create-results-button [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-button (p.factory/button factory 0 526 "button" nil nil 0 0 1 0) phzr-text (p.factory/text factory 0 0 "Results")] (f.input/set-event-callback! phzr-button :on-input-up :pressed-results-button) (p.button/add-child phzr-button phzr-text) (doto phzr-text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :fill "#000000") (p.core/pset! :align "center") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :x 95) (p.core/pset! :y 25)) phzr-button)) (defn create-movement-button-icon [factory button i] (let [button-icon (p.factory/sprite factory 0 0 "direction-arrows" i)] (p.button/add-child button button-icon))) (declare direction-abbreviation) (defn create-movement-button-text [factory button i] (let [direction (f.exploration-path/directions i) direction-text (direction-abbreviation direction) button-text (p.factory/text factory 0 0 direction-text)] (p.button/add-child button button-text) (doto button-text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :font-size 15) (p.core/pset! :fill "#ffffff") (p.core/pset! :align "center") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :x 25) (p.core/pset! :y 25)))) (def movement-buttons-coordinates [[50 0] [100 25] [100 75] [50 100] [0 75] [0 25]]) (defn create-movement-button [button-map i factory group] (let [direction (f.exploration-path/directions i) tint (f.exploration-path/hex-tints i) coordinates (movement-buttons-coordinates i) button (p.factory/button factory 0 0 "square-button" nil nil 0 0 1 0 group)] (create-movement-button-icon factory button i) (create-movement-button-text factory button i) (p.core/pset! button :tint tint) (p.core/pset! button :x (coordinates 0)) (p.core/pset! button :y (coordinates 1)) (assoc button-map direction button))) (defn create-movement-buttons [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) group (f.group/create-phzr-group phzr-game "movement buttons" 600 415) button-map (reduce #(create-movement-button %1 %2 factory group) {} (range 6)) entity (b.entity/create-entity)] (p.core/pset! group :z 16r30) (-> system (b.entity/add-entity entity) (b.entity/add-component entity (f.component/->MovementButtons button-map group))))) (def dungeon-status-original-text "Subject #2 Rank:\nTERRIBLE\nRoom(s) left: 10\nExp. Subjects: 10") (defn create-dungeon-status [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) sprite (f.rendering/create-phzr-sprite phzr-game "dungeon-status" "dungeon-status" 890 80) text (p.factory/text factory 0 0 dungeon-status-original-text) dungeon-status (b.entity/create-entity)] (doto sprite (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :visible true) (p.core/pset! :z 16r30) (p.sprite/add-child text)) (doto text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :font-size 20) (p.core/pset! :fill "#000000") (p.core/pset! :align "left") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :word-wrap true) (p.core/pset! :word-wrap-width 250) (p.core/pset! :x -230) (p.core/pset! :y -10)) (-> system (b.entity/add-entity dungeon-status) (b.entity/add-component dungeon-status (f.component/->DungeonStatus sprite text))))) (defn create-entities [system] (let [dungeon (b.entity/create-entity) explore-button (b.entity/create-entity) explore-phzr-button (create-explore-button system) exploration-results (b.entity/create-entity) exploration-results-sprite (create-exploration-results-sprite system) exploration-results-text (create-exploration-results-text system exploration-results-sprite) movement-results (b.entity/create-entity) movement-results-text (create-movement-results-text system exploration-results-sprite) results-navigation (create-exploration-results-navigation system exploration-results-sprite) results-button-entity (b.entity/create-entity) results-button (create-results-button system)] (-> system (b.entity/add-entity dungeon) (b.entity/add-component dungeon (f.component/->Dungeon initial-dungeon 0)) (b.entity/add-entity explore-button) (b.entity/add-component explore-button (f.component/->ExploreButton explore-phzr-button)) (b.entity/add-entity exploration-results) (b.entity/add-component exploration-results (f.component/->Sprite exploration-results-sprite)) (b.entity/add-component exploration-results (f.component/->Text exploration-results-text)) (b.entity/add-component exploration-results results-navigation) (b.entity/add-component exploration-results (f.component/->ExplorationResults [])) (b.entity/add-entity movement-results) (b.entity/add-component movement-results (f.component/->MovementResults {} movement-results-text)) (b.entity/add-entity results-button-entity) (b.entity/add-component results-button-entity (f.component/->ResultsButton results-button)) (create-movement-buttons) (create-dungeon-status) (initialize-dungeon)))) (def liar-truth-percentage 0.25) (defn get-answer [party-member is-it-safe?] (cond (not (:is-liar party-member)) is-it-safe? is-it-safe? false ; Always lie if it's safe :else (> (rand) liar-truth-percentage))) ; Otherwise, small chance of telling the truth (false) (defn explore-path [system result-map direction explorers safe-path] (let [explorers-components (map #(b.entity/get-component system % f.component/PartyMember) explorers) is-it-safe? (= direction safe-path) grouped-members (group-by #(get-answer % is-it-safe?) explorers-components)] (assoc result-map direction grouped-members))) (defn explore-paths [system paths safe-path] (let [exploration-paths (map #(f.exploration-path/get-exploration-path-by-direction system %) paths)] (->> (zipmap paths (map #(f.component/get-group-members-from-entity system %) exploration-paths)) (reduce #(explore-path system %1 (get %2 0) (get %2 1) safe-path) {})))) (def direction-abbreviation {:north "N" :northeast "NE" :southeast "SE" :south "S" :southwest "SW" :northwest "NW"}) (defn get-direction-result [[direction answers]] (let [yes-answers (map :member-name (get answers true)) no-answers (map :member-name (get answers false))] (c.pprint/cl-format nil "~A- Yes:~[ no one~*~:;~{ ~A~}~]/ No:~[ no one~*~:;~{ ~A~}~]~%" (get direction-abbreviation direction) (count yes-answers) yes-answers (count no-answers) no-answers))) (defn get-exploration-text [results-map] (let [lines (map get-direction-result results-map)] (apply str lines))) (defn update-movement-text [system] (let [{:keys [current-result]} (f.component/get-singleton-component system f.component/ResultsNavigation) {:keys [previous-results movement-results-text]} (f.component/get-singleton-component system f.component/MovementResults)] (if-let [{:keys [direction was-safe?]} (get previous-results current-result)] (doto movement-results-text (p.core/pset! :fill (if was-safe? "#009900" "#ff0000")) (p.core/pset! :text (c.pprint/cl-format nil "- We moved ~A. It was ~:[UNSAFE!!!~;safe.~] -" (get direction-abbreviation direction) was-safe?)) (p.core/pset! :visible true)) (p.core/pset! movement-results-text :visible false)) system)) (defn update-results-navigation [system] (let [results-navigation (first (b.entity/get-all-entities-with-component system f.component/ResultsNavigation)) {:keys [current-result previous-text next-text]} (b.entity/get-component system results-navigation f.component/ResultsNavigation) exploration-results-entity (first (b.entity/get-all-entities-with-component system f.component/ExplorationResults)) exploration-results (:previous-results (b.entity/get-component system exploration-results-entity f.component/ExplorationResults)) exploration-results-text (f.component/get-phzr-text-from-entity system exploration-results-entity) new-exploration-text (get-exploration-text (get exploration-results current-result))] (p.core/pset! previous-text :visible (not= current-result 0)) (p.core/pset! next-text :visible (not= current-result (dec (count exploration-results)))) (p.core/pset! exploration-results-text :text new-exploration-text) (update-movement-text system))) (defn get-current-dungeon-room [system] (let [{:keys [rooms current-room]} (f.component/get-singleton-component system f.component/Dungeon)] (rooms current-room))) (defn do-exploration [system] (let [current-room (get-current-dungeon-room system) exploration-results-map (explore-paths system (:paths current-room) (:safe-path current-room)) exploration-results-string (get-exploration-text exploration-results-map) exploration-results-entity (first (b.entity/get-all-entities-with-component system f.component/ExplorationResults)) exploration-results-component (b.entity/get-component system exploration-results-entity f.component/ExplorationResults) previous-results (:previous-results exploration-results-component) exploration-results-sprite (f.component/get-phzr-sprite-from-entity system exploration-results-entity) exploration-results-text (f.component/get-phzr-text-from-entity system exploration-results-entity) results-navigation-entity (first (b.entity/get-all-entities-with-component system f.component/ResultsNavigation)) {:keys [previous-text next-text]} (b.entity/get-component system results-navigation-entity f.component/ResultsNavigation)] (p.core/pset! exploration-results-text :text exploration-results-string) (p.core/pset! exploration-results-sprite :visible true) (-> system :phzr-game :world (p.world/bring-to-top exploration-results-sprite)) (-> system (assoc :explored-this-turn true) (b.entity/add-component exploration-results-entity (f.component/->ExplorationResults (conj previous-results exploration-results-map))) (b.entity/add-component results-navigation-entity (f.component/->ResultsNavigation (count previous-results) previous-text next-text)) (update-results-navigation)))) (defn handle-explore-button [system] (let [explore-button (:phzr-button (f.component/get-singleton-component system f.component/ExploreButton)) unassigned-members (:members (f.component/get-singleton-component system f.component/UnassignedMembers f.component/Group)) exploration-results-sprite (:phzr-sprite (f.component/get-singleton-component system f.component/ExplorationResults f.component/Sprite))] (p.core/pset! explore-button :visible (and (empty? unassigned-members) (not (:visible exploration-results-sprite)))) (if (f.input/event-happened-in-system? system :pressed-explore-button) (-> system (f.input/consume-event-from-system :pressed-explore-button) (do-exploration)) system))) (defn handle-results-navigation [system] (let [results-navigation-entity (f.component/get-singleton-entity system f.component/ResultsNavigation) {:keys [current-result] :as result-navigation-component} (f.component/get-singleton-component system f.component/ResultsNavigation) previous-pressed? (f.input/event-happened-in-system? system :pressed-previous-results) next-pressed? (f.input/event-happened-in-system? system :pressed-next-results) exploration-results-count (-> (f.component/get-singleton-component system f.component/ExplorationResults) :previous-results count)] (if (or previous-pressed? next-pressed?) (let [updated-result (if previous-pressed? (max (dec current-result) 0) (min (inc current-result) (dec exploration-results-count)))] (-> system (as-> sys (if previous-pressed? (f.input/consume-event-from-system sys :pressed-previous-results) (f.input/consume-event-from-system sys :pressed-next-results))) (b.entity/add-component results-navigation-entity (assoc result-navigation-component :current-result updated-result)) (update-results-navigation))) system))) (defn handle-results-button [system] (let [{:keys [phzr-button]} (f.component/get-singleton-component system f.component/ResultsButton) exploration-results-count (-> (f.component/get-singleton-component system f.component/ExplorationResults) :previous-results count) exploration-results-sprite (:phzr-sprite (f.component/get-singleton-component system f.component/ExplorationResults f.component/Sprite)) results-navigation-entity (f.component/get-singleton-entity system f.component/ResultsNavigation) results-navigation-component (f.component/get-singleton-component system f.component/ResultsNavigation)] (p.core/pset! phzr-button :visible (and (not (:visible exploration-results-sprite)) (> exploration-results-count 0))) (if (f.input/event-happened-in-system? system :pressed-results-button) (-> system (f.input/consume-event-from-system :pressed-results-button) (b.entity/add-component results-navigation-entity (assoc results-navigation-component :current-result (dec exploration-results-count))) (update-results-navigation) (as-> sys (do (p.core/pset! exploration-results-sprite :visible true) (-> sys :phzr-game :world (p.world/bring-to-top exploration-results-sprite)) sys))) system))) (defn move-to-next-room [system direction] (let [dungeon (f.component/get-singleton-component system f.component/Dungeon) dungeon-entity (f.component/get-singleton-entity system f.component/Dungeon) {:keys [safe-path]} (get-current-dungeon-room system) movement-results-entity (f.component/get-singleton-entity system f.component/MovementResults) movement-results-component (f.component/get-singleton-component system f.component/MovementResults) previous-results (:previous-results movement-results-component) current-exploration (dec (count (:previous-results (f.component/get-singleton-component system f.component/ExplorationResults)))) move-is-safe? (= direction safe-path) new-previous-results (assoc previous-results current-exploration {:direction direction :was-safe? move-is-safe?})] (-> system (b.entity/add-component movement-results-entity (assoc movement-results-component :previous-results new-previous-results)) (assoc :explored-this-turn false) (b.entity/add-component dungeon-entity (f.component/->Dungeon (:rooms dungeon) (inc (:current-room dungeon)))) (initialize-dungeon) (f.dialogue/start-dialogue (if move-is-safe? :right-path :wrong-path))))) (defn handle-movement-buttons [system] (let [exploration-results-sprite (:phzr-sprite (f.component/get-singleton-component system f.component/ExplorationResults f.component/Sprite)) {:keys [movement-buttons group]} (f.component/get-singleton-component system f.component/MovementButtons) direction-pressed (get (first (filter #(f.input/just-pressed (get % 1)) movement-buttons)) 0) {:keys [paths]} (get-current-dungeon-room system)] (p.core/pset! group :visible (and (not (:visible exploration-results-sprite)) (:explored-this-turn system))) (doseq [[direction button] movement-buttons] (p.core/pset! button :visible (paths direction))) (if (and (f.input/blackout-expired? system :just-pressed-movement-button) direction-pressed) (-> system (f.input/update-blackout-property :just-pressed-movement-button) (move-to-next-room direction-pressed)) system))) (defn process-one-game-tick [system] (-> system (handle-results-button) (handle-explore-button) (handle-results-navigation) (handle-movement-buttons)))
true
(ns fossa.dungeon (:require [cljs.pprint :as c.pprint] [brute.entity :as b.entity] [phzr.button :as p.button] [phzr.core :as p.core] [phzr.game-object-factory :as p.factory] [phzr.loader :as p.loader] [phzr.point :as p.point] [phzr.signal :as p.signal] [phzr.sprite :as p.sprite] [phzr.world :as p.world] [fossa.component :as f.component] [fossa.dialogue :as f.dialogue] [fossa.exploration-path :as f.exploration-path] [fossa.group :as f.group] [fossa.input :as f.input] [fossa.party-member :as f.party-member] [fossa.rendering :as f.rendering])) (def initial-dungeon [{:paths #{ :north :south :southwest :northeast } :safe-path :southwest :liars 2} {:paths #{ :north :northeast :southeast } :safe-path :north :liars 1} {:paths #{ :south :northwest :southwest } :safe-path :northwest :liars 4}]) (defn preload-assets [loader] (doto loader (p.loader/spritesheet "button" "assets/images/button.png" 190 49 2) (p.loader/image "paper" "assets/images/paper.png") (p.loader/spritesheet "square-button" "assets/images/square_button.png" 49 49 2) (p.loader/spritesheet "direction-arrows" "assets/images/direction_arrows.png" 50 50 6) (p.loader/image "dungeon-status" "assets/images/panel.png"))) (defn update-dungeon-status [system] (let [{:keys [text]} (f.component/get-singleton-component system f.component/DungeonStatus) {:keys [rooms current-room]} (f.component/get-singleton-component system f.component/Dungeon) rooms-left (- (count rooms) current-room) liar-count (f.party-member/get-liar-count system)] (p.core/pset! text :text (c.pprint/cl-format nil "Subject #2 Rank:~%TERRIBLE~%Room(s) left: ~D~%Exp. Subjects: ~D" rooms-left liar-count)) system)) (defn initialize-dungeon [system] (let [dungeon-entity (first (b.entity/get-all-entities-with-component system f.component/Dungeon)) dungeon (b.entity/get-component system dungeon-entity f.component/Dungeon) current-room ((:rooms dungeon) (:current-room dungeon))] (-> system (f.exploration-path/update-exploration-paths (:paths current-room)) (f.group/move-all-members-back-to-unassigned) (f.party-member/set-liars (:liars current-room)) (update-dungeon-status)))) (defn create-explore-button [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-button (p.factory/button factory 0 0 "button" nil nil 0 0 1 0) phzr-text (p.factory/text factory 0 0 "Explore")] (f.input/set-event-callback! phzr-button :on-input-up :pressed-explore-button) (p.button/add-child phzr-button phzr-text) (doto phzr-text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :fill "#000000") (p.core/pset! :align "center") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :x 95) (p.core/pset! :y 25)) phzr-button)) (defn create-exploration-results-sprite [system] (let [phzr-game (:phzr-game system)] (doto (f.rendering/create-phzr-sprite phzr-game "exploration-results" "paper" 500 600) (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :angle -15) (p.core/pset! :input-enabled true) (-> :input (p.core/pset! :priority-id 0)) (-> :events :on-input-down (p.signal/add (fn [sprite _] (p.core/pset! sprite :visible false)))) (p.core/pset! :visible false) (p.core/pset! :z 16r40)))) (def exploration-results-original-text (str "N - Yes: PI:NAME:<NAME>END_PI / No: PI:NAME:<NAME>END_PI\n" "NE - Yes: PI:NAME:<NAME>END_PI / No: PI:NAME:<NAME>END_PI\n" "SE - Yes: PI:NAME:<NAME>END_PI / No: PI:NAME:<NAME>END_PI\n" "S - Yes: PI:NAME:<NAME>END_PI / No: PI:NAME:<NAME>END_PI\n" "SW - No: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI\n" "NW - Yes: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI\n")) (defn create-exploration-results-text [system sprite] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-text (p.factory/text factory 0 0 exploration-results-original-text)] (p.sprite/add-child sprite phzr-text) (doto phzr-text (p.core/pset! :font "Just Me Again Down Here, MV Boli, Apple Chancery, Zapfino, cursive") (p.core/pset! :font-size 40) (p.core/pset! :fill "#000000") (p.core/pset! :align "left") (p.core/pset! :word-wrap true) (p.core/pset! :word-wrap-width (- (:width sprite) 150)) (p.core/pset! :x -270) (p.core/pset! :y -460)))) (def movement-results-original-text "We moved SW. It was UNSAFE!!!") (defn create-movement-results-text [system sprite] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-text (p.factory/text factory 0 0 movement-results-original-text)] (p.sprite/add-child sprite phzr-text) (doto phzr-text (p.core/pset! :visible false) (p.core/pset! :font "Just Me Again Down Here, MV Boli, Apple Chancery, Zapfino, cursive") (p.core/pset! :font-size 40) (p.core/pset! :fill "#ff0000") (p.core/pset! :align "center") (p.core/pset! :word-wrap true) (p.core/pset! :word-wrap-width (- (:width sprite) 150)) (p.core/pset! :x -210) (p.core/pset! :y -160)))) (defn create-exploration-results-navigation [system sprite] (let [phzr-game (:phzr-game system) factory (:add phzr-game) previous-text (p.factory/text factory 0 0 "<Previous") next-text (p.factory/text factory 0 0 "Next>")] (doseq [text [previous-text next-text]] (p.sprite/add-child sprite text) (doto text (p.core/pset! :font "Just Me Again Down Here, MV Boli, Apple Chancery, Zapfino, cursive") (p.core/pset! :font-size 60) (p.core/pset! :fill "#0000ff") (-> :events :on-input-over (p.signal/add (fn [sprite _] (p.core/pset! sprite :fill "#ff0000")))) (-> :events :on-input-out (p.signal/add (fn [sprite _] (p.core/pset! sprite :fill "#0000ff")))) (p.core/pset! :input-enabled true) (-> :input (p.core/pset! :priority-id 1)) (p.core/pset! :y -525))) (doto previous-text (f.input/set-event-callback! :on-input-up :pressed-previous-results) (p.core/pset! :align "left") (p.core/pset! :x -270)) (doto next-text (f.input/set-event-callback! :on-input-up :pressed-next-results) (p.core/pset! :align "right") (p.core/pset! :x 145)) (f.component/->ResultsNavigation 0 previous-text next-text))) (defn create-results-button [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) phzr-button (p.factory/button factory 0 526 "button" nil nil 0 0 1 0) phzr-text (p.factory/text factory 0 0 "Results")] (f.input/set-event-callback! phzr-button :on-input-up :pressed-results-button) (p.button/add-child phzr-button phzr-text) (doto phzr-text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :fill "#000000") (p.core/pset! :align "center") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :x 95) (p.core/pset! :y 25)) phzr-button)) (defn create-movement-button-icon [factory button i] (let [button-icon (p.factory/sprite factory 0 0 "direction-arrows" i)] (p.button/add-child button button-icon))) (declare direction-abbreviation) (defn create-movement-button-text [factory button i] (let [direction (f.exploration-path/directions i) direction-text (direction-abbreviation direction) button-text (p.factory/text factory 0 0 direction-text)] (p.button/add-child button button-text) (doto button-text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :font-size 15) (p.core/pset! :fill "#ffffff") (p.core/pset! :align "center") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :x 25) (p.core/pset! :y 25)))) (def movement-buttons-coordinates [[50 0] [100 25] [100 75] [50 100] [0 75] [0 25]]) (defn create-movement-button [button-map i factory group] (let [direction (f.exploration-path/directions i) tint (f.exploration-path/hex-tints i) coordinates (movement-buttons-coordinates i) button (p.factory/button factory 0 0 "square-button" nil nil 0 0 1 0 group)] (create-movement-button-icon factory button i) (create-movement-button-text factory button i) (p.core/pset! button :tint tint) (p.core/pset! button :x (coordinates 0)) (p.core/pset! button :y (coordinates 1)) (assoc button-map direction button))) (defn create-movement-buttons [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) group (f.group/create-phzr-group phzr-game "movement buttons" 600 415) button-map (reduce #(create-movement-button %1 %2 factory group) {} (range 6)) entity (b.entity/create-entity)] (p.core/pset! group :z 16r30) (-> system (b.entity/add-entity entity) (b.entity/add-component entity (f.component/->MovementButtons button-map group))))) (def dungeon-status-original-text "Subject #2 Rank:\nTERRIBLE\nRoom(s) left: 10\nExp. Subjects: 10") (defn create-dungeon-status [system] (let [phzr-game (:phzr-game system) factory (:add phzr-game) sprite (f.rendering/create-phzr-sprite phzr-game "dungeon-status" "dungeon-status" 890 80) text (p.factory/text factory 0 0 dungeon-status-original-text) dungeon-status (b.entity/create-entity)] (doto sprite (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :visible true) (p.core/pset! :z 16r30) (p.sprite/add-child text)) (doto text (p.core/pset! :font "Cutive, Courier, MS Courier New, monospace") (p.core/pset! :font-size 20) (p.core/pset! :fill "#000000") (p.core/pset! :align "left") (p.core/pset! :anchor (p.point/->Point 0.5 0.5)) (p.core/pset! :word-wrap true) (p.core/pset! :word-wrap-width 250) (p.core/pset! :x -230) (p.core/pset! :y -10)) (-> system (b.entity/add-entity dungeon-status) (b.entity/add-component dungeon-status (f.component/->DungeonStatus sprite text))))) (defn create-entities [system] (let [dungeon (b.entity/create-entity) explore-button (b.entity/create-entity) explore-phzr-button (create-explore-button system) exploration-results (b.entity/create-entity) exploration-results-sprite (create-exploration-results-sprite system) exploration-results-text (create-exploration-results-text system exploration-results-sprite) movement-results (b.entity/create-entity) movement-results-text (create-movement-results-text system exploration-results-sprite) results-navigation (create-exploration-results-navigation system exploration-results-sprite) results-button-entity (b.entity/create-entity) results-button (create-results-button system)] (-> system (b.entity/add-entity dungeon) (b.entity/add-component dungeon (f.component/->Dungeon initial-dungeon 0)) (b.entity/add-entity explore-button) (b.entity/add-component explore-button (f.component/->ExploreButton explore-phzr-button)) (b.entity/add-entity exploration-results) (b.entity/add-component exploration-results (f.component/->Sprite exploration-results-sprite)) (b.entity/add-component exploration-results (f.component/->Text exploration-results-text)) (b.entity/add-component exploration-results results-navigation) (b.entity/add-component exploration-results (f.component/->ExplorationResults [])) (b.entity/add-entity movement-results) (b.entity/add-component movement-results (f.component/->MovementResults {} movement-results-text)) (b.entity/add-entity results-button-entity) (b.entity/add-component results-button-entity (f.component/->ResultsButton results-button)) (create-movement-buttons) (create-dungeon-status) (initialize-dungeon)))) (def liar-truth-percentage 0.25) (defn get-answer [party-member is-it-safe?] (cond (not (:is-liar party-member)) is-it-safe? is-it-safe? false ; Always lie if it's safe :else (> (rand) liar-truth-percentage))) ; Otherwise, small chance of telling the truth (false) (defn explore-path [system result-map direction explorers safe-path] (let [explorers-components (map #(b.entity/get-component system % f.component/PartyMember) explorers) is-it-safe? (= direction safe-path) grouped-members (group-by #(get-answer % is-it-safe?) explorers-components)] (assoc result-map direction grouped-members))) (defn explore-paths [system paths safe-path] (let [exploration-paths (map #(f.exploration-path/get-exploration-path-by-direction system %) paths)] (->> (zipmap paths (map #(f.component/get-group-members-from-entity system %) exploration-paths)) (reduce #(explore-path system %1 (get %2 0) (get %2 1) safe-path) {})))) (def direction-abbreviation {:north "N" :northeast "NE" :southeast "SE" :south "S" :southwest "SW" :northwest "NW"}) (defn get-direction-result [[direction answers]] (let [yes-answers (map :member-name (get answers true)) no-answers (map :member-name (get answers false))] (c.pprint/cl-format nil "~A- Yes:~[ no one~*~:;~{ ~A~}~]/ No:~[ no one~*~:;~{ ~A~}~]~%" (get direction-abbreviation direction) (count yes-answers) yes-answers (count no-answers) no-answers))) (defn get-exploration-text [results-map] (let [lines (map get-direction-result results-map)] (apply str lines))) (defn update-movement-text [system] (let [{:keys [current-result]} (f.component/get-singleton-component system f.component/ResultsNavigation) {:keys [previous-results movement-results-text]} (f.component/get-singleton-component system f.component/MovementResults)] (if-let [{:keys [direction was-safe?]} (get previous-results current-result)] (doto movement-results-text (p.core/pset! :fill (if was-safe? "#009900" "#ff0000")) (p.core/pset! :text (c.pprint/cl-format nil "- We moved ~A. It was ~:[UNSAFE!!!~;safe.~] -" (get direction-abbreviation direction) was-safe?)) (p.core/pset! :visible true)) (p.core/pset! movement-results-text :visible false)) system)) (defn update-results-navigation [system] (let [results-navigation (first (b.entity/get-all-entities-with-component system f.component/ResultsNavigation)) {:keys [current-result previous-text next-text]} (b.entity/get-component system results-navigation f.component/ResultsNavigation) exploration-results-entity (first (b.entity/get-all-entities-with-component system f.component/ExplorationResults)) exploration-results (:previous-results (b.entity/get-component system exploration-results-entity f.component/ExplorationResults)) exploration-results-text (f.component/get-phzr-text-from-entity system exploration-results-entity) new-exploration-text (get-exploration-text (get exploration-results current-result))] (p.core/pset! previous-text :visible (not= current-result 0)) (p.core/pset! next-text :visible (not= current-result (dec (count exploration-results)))) (p.core/pset! exploration-results-text :text new-exploration-text) (update-movement-text system))) (defn get-current-dungeon-room [system] (let [{:keys [rooms current-room]} (f.component/get-singleton-component system f.component/Dungeon)] (rooms current-room))) (defn do-exploration [system] (let [current-room (get-current-dungeon-room system) exploration-results-map (explore-paths system (:paths current-room) (:safe-path current-room)) exploration-results-string (get-exploration-text exploration-results-map) exploration-results-entity (first (b.entity/get-all-entities-with-component system f.component/ExplorationResults)) exploration-results-component (b.entity/get-component system exploration-results-entity f.component/ExplorationResults) previous-results (:previous-results exploration-results-component) exploration-results-sprite (f.component/get-phzr-sprite-from-entity system exploration-results-entity) exploration-results-text (f.component/get-phzr-text-from-entity system exploration-results-entity) results-navigation-entity (first (b.entity/get-all-entities-with-component system f.component/ResultsNavigation)) {:keys [previous-text next-text]} (b.entity/get-component system results-navigation-entity f.component/ResultsNavigation)] (p.core/pset! exploration-results-text :text exploration-results-string) (p.core/pset! exploration-results-sprite :visible true) (-> system :phzr-game :world (p.world/bring-to-top exploration-results-sprite)) (-> system (assoc :explored-this-turn true) (b.entity/add-component exploration-results-entity (f.component/->ExplorationResults (conj previous-results exploration-results-map))) (b.entity/add-component results-navigation-entity (f.component/->ResultsNavigation (count previous-results) previous-text next-text)) (update-results-navigation)))) (defn handle-explore-button [system] (let [explore-button (:phzr-button (f.component/get-singleton-component system f.component/ExploreButton)) unassigned-members (:members (f.component/get-singleton-component system f.component/UnassignedMembers f.component/Group)) exploration-results-sprite (:phzr-sprite (f.component/get-singleton-component system f.component/ExplorationResults f.component/Sprite))] (p.core/pset! explore-button :visible (and (empty? unassigned-members) (not (:visible exploration-results-sprite)))) (if (f.input/event-happened-in-system? system :pressed-explore-button) (-> system (f.input/consume-event-from-system :pressed-explore-button) (do-exploration)) system))) (defn handle-results-navigation [system] (let [results-navigation-entity (f.component/get-singleton-entity system f.component/ResultsNavigation) {:keys [current-result] :as result-navigation-component} (f.component/get-singleton-component system f.component/ResultsNavigation) previous-pressed? (f.input/event-happened-in-system? system :pressed-previous-results) next-pressed? (f.input/event-happened-in-system? system :pressed-next-results) exploration-results-count (-> (f.component/get-singleton-component system f.component/ExplorationResults) :previous-results count)] (if (or previous-pressed? next-pressed?) (let [updated-result (if previous-pressed? (max (dec current-result) 0) (min (inc current-result) (dec exploration-results-count)))] (-> system (as-> sys (if previous-pressed? (f.input/consume-event-from-system sys :pressed-previous-results) (f.input/consume-event-from-system sys :pressed-next-results))) (b.entity/add-component results-navigation-entity (assoc result-navigation-component :current-result updated-result)) (update-results-navigation))) system))) (defn handle-results-button [system] (let [{:keys [phzr-button]} (f.component/get-singleton-component system f.component/ResultsButton) exploration-results-count (-> (f.component/get-singleton-component system f.component/ExplorationResults) :previous-results count) exploration-results-sprite (:phzr-sprite (f.component/get-singleton-component system f.component/ExplorationResults f.component/Sprite)) results-navigation-entity (f.component/get-singleton-entity system f.component/ResultsNavigation) results-navigation-component (f.component/get-singleton-component system f.component/ResultsNavigation)] (p.core/pset! phzr-button :visible (and (not (:visible exploration-results-sprite)) (> exploration-results-count 0))) (if (f.input/event-happened-in-system? system :pressed-results-button) (-> system (f.input/consume-event-from-system :pressed-results-button) (b.entity/add-component results-navigation-entity (assoc results-navigation-component :current-result (dec exploration-results-count))) (update-results-navigation) (as-> sys (do (p.core/pset! exploration-results-sprite :visible true) (-> sys :phzr-game :world (p.world/bring-to-top exploration-results-sprite)) sys))) system))) (defn move-to-next-room [system direction] (let [dungeon (f.component/get-singleton-component system f.component/Dungeon) dungeon-entity (f.component/get-singleton-entity system f.component/Dungeon) {:keys [safe-path]} (get-current-dungeon-room system) movement-results-entity (f.component/get-singleton-entity system f.component/MovementResults) movement-results-component (f.component/get-singleton-component system f.component/MovementResults) previous-results (:previous-results movement-results-component) current-exploration (dec (count (:previous-results (f.component/get-singleton-component system f.component/ExplorationResults)))) move-is-safe? (= direction safe-path) new-previous-results (assoc previous-results current-exploration {:direction direction :was-safe? move-is-safe?})] (-> system (b.entity/add-component movement-results-entity (assoc movement-results-component :previous-results new-previous-results)) (assoc :explored-this-turn false) (b.entity/add-component dungeon-entity (f.component/->Dungeon (:rooms dungeon) (inc (:current-room dungeon)))) (initialize-dungeon) (f.dialogue/start-dialogue (if move-is-safe? :right-path :wrong-path))))) (defn handle-movement-buttons [system] (let [exploration-results-sprite (:phzr-sprite (f.component/get-singleton-component system f.component/ExplorationResults f.component/Sprite)) {:keys [movement-buttons group]} (f.component/get-singleton-component system f.component/MovementButtons) direction-pressed (get (first (filter #(f.input/just-pressed (get % 1)) movement-buttons)) 0) {:keys [paths]} (get-current-dungeon-room system)] (p.core/pset! group :visible (and (not (:visible exploration-results-sprite)) (:explored-this-turn system))) (doseq [[direction button] movement-buttons] (p.core/pset! button :visible (paths direction))) (if (and (f.input/blackout-expired? system :just-pressed-movement-button) direction-pressed) (-> system (f.input/update-blackout-property :just-pressed-movement-button) (move-to-next-room direction-pressed)) system))) (defn process-one-game-tick [system] (-> system (handle-results-button) (handle-explore-button) (handle-results-navigation) (handle-movement-buttons)))
[ { "context": "equired\"]))\n(defn fake-db-lookup [email]\n (get {\"me@example.com\" {:first-name \"Me\"}} email))\n(defn email-uniquene", "end": 476, "score": 0.999893844127655, "start": 462, "tag": "EMAIL", "value": "me@example.com" }, { "context": "ormat-validation]\n {:email \"me@example.com\"}) => {}\n (validate [email-presence-v", "end": 1125, "score": 0.9997562170028687, "start": 1111, "tag": "EMAIL", "value": "me@example.com" }, { "context": "sence-validation]\n {:email \"me@example.com\" :password \"pass\"}) => {})\n (fact \"it retur", "end": 1285, "score": 0.9998822212219238, "start": 1271, "tag": "EMAIL", "value": "me@example.com" }, { "context": " {:email \"me@example.com\" :password \"pass\"}) => {})\n (fact \"it returns error messages", "end": 1302, "score": 0.9975548386573792, "start": 1298, "tag": "PASSWORD", "value": "pass" }, { "context": "lid\"}\n :password #{\"is required\"}}))\n\n(facts \"about 'group\"\n (fact \"it retu", "end": 1771, "score": 0.9923792481422424, "start": 1760, "tag": "PASSWORD", "value": "is required" }, { "context": "rmat-validation)]\n {:email \"me@example.com\"}) => {})\n (fact \"it skips the rest of the ", "end": 2020, "score": 0.999821662902832, "start": 2006, "tag": "EMAIL", "value": "me@example.com" }, { "context": "]\n {:email \"me@\" :password \"pass\"}) => {:email #{\"is invalid\"}}\n (vali", "end": 2901, "score": 0.9987722039222717, "start": 2897, "tag": "PASSWORD", "value": "pass" }, { "context": " {:email \"me@\" :password \"\"}) => {:password #{\"is required\"}}))\n\n(facts \"about 'make-claim\"\n (let [onl", "end": 3268, "score": 0.9955917000770569, "start": 3257, "tag": "PASSWORD", "value": "is required" } ]
test/heckle/core_test.clj
nwallace/heckle
0
(ns heckle.core-test (:require [midje.sweet :refer :all] [heckle.core :refer :all])) (defn email-presence-validation [data] (when (empty? (get data :email "")) [:email "is required"])) (defn email-format-validation [data] (when-not (re-find #".@." (get data :email "")) [:email "is invalid"])) (defn password-presence-validation [data] (when (empty? (get data :password "")) [:password "is required"])) (defn fake-db-lookup [email] (get {"me@example.com" {:first-name "Me"}} email)) (defn email-uniqueness-validation [data] (when (fake-db-lookup (:email data)) [:email "is already taken"])) (facts "about 'validate" (fact "it returns no errors when no validations are given" (validate [] {}) => {} (validate [] {:data "value"}) => {}) (fact "it returns no errors when the data passes all validations" (validate [email-presence-validation] {:email "any non-empty string"}) => {} (validate [email-presence-validation email-format-validation] {:email "me@example.com"}) => {} (validate [email-presence-validation password-presence-validation] {:email "me@example.com" :password "pass"}) => {}) (fact "it returns error messages grouped by error key when the data" (validate [email-presence-validation] {}) => {:email #{"is required"}} (validate [email-presence-validation email-format-validation password-presence-validation] {}) => {:email #{"is required" "is invalid"} :password #{"is required"}})) (facts "about 'group" (fact "it returns no errors the group is valid" (validate [] {}) => {} (validate [(group email-presence-validation email-format-validation)] {:email "me@example.com"}) => {}) (fact "it skips the rest of the group once one validation fails" (against-background (fake-db-lookup nil) =throws=> (RuntimeException. "Should be skipped!")) (validate [(group email-presence-validation email-format-validation email-uniqueness-validation)] {}) => {:email #{"is required"}}) (fact "groups can be nested indefinitely" (against-background (fake-db-lookup nil) =throws=> (RuntimeException. "Should be skipped!")) (validate [(group password-presence-validation (group email-presence-validation email-format-validation email-uniqueness-validation))] {:email "me@" :password "pass"}) => {:email #{"is invalid"}} (validate [(group password-presence-validation (group email-presence-validation email-format-validation email-uniqueness-validation))] {:email "me@" :password ""}) => {:password #{"is required"}})) (facts "about 'make-claim" (let [only-even (make-claim even? :number "must be even")] (fact "it returns a function that returns `nil` when called with data that passes the predicate" (only-even 2) => nil) (fact "it returns a function that returns an error tuple with the given key and message when called with data that fails the predicate" (only-even 1) => [:number "must be even"]))) (facts "about 'make-denial" (let [only-even (make-denial odd? :number "must be even")] (fact "it returns a function that returns `nil` when called with data that passes the predicate" (only-even 2) => nil) (fact "it returns a function that returns an error tuple with the given key and message when called with data that fails the predicate" (only-even 1) => [:number "must be even"])))
79794
(ns heckle.core-test (:require [midje.sweet :refer :all] [heckle.core :refer :all])) (defn email-presence-validation [data] (when (empty? (get data :email "")) [:email "is required"])) (defn email-format-validation [data] (when-not (re-find #".@." (get data :email "")) [:email "is invalid"])) (defn password-presence-validation [data] (when (empty? (get data :password "")) [:password "is required"])) (defn fake-db-lookup [email] (get {"<EMAIL>" {:first-name "Me"}} email)) (defn email-uniqueness-validation [data] (when (fake-db-lookup (:email data)) [:email "is already taken"])) (facts "about 'validate" (fact "it returns no errors when no validations are given" (validate [] {}) => {} (validate [] {:data "value"}) => {}) (fact "it returns no errors when the data passes all validations" (validate [email-presence-validation] {:email "any non-empty string"}) => {} (validate [email-presence-validation email-format-validation] {:email "<EMAIL>"}) => {} (validate [email-presence-validation password-presence-validation] {:email "<EMAIL>" :password "<PASSWORD>"}) => {}) (fact "it returns error messages grouped by error key when the data" (validate [email-presence-validation] {}) => {:email #{"is required"}} (validate [email-presence-validation email-format-validation password-presence-validation] {}) => {:email #{"is required" "is invalid"} :password #{"<PASSWORD>"}})) (facts "about 'group" (fact "it returns no errors the group is valid" (validate [] {}) => {} (validate [(group email-presence-validation email-format-validation)] {:email "<EMAIL>"}) => {}) (fact "it skips the rest of the group once one validation fails" (against-background (fake-db-lookup nil) =throws=> (RuntimeException. "Should be skipped!")) (validate [(group email-presence-validation email-format-validation email-uniqueness-validation)] {}) => {:email #{"is required"}}) (fact "groups can be nested indefinitely" (against-background (fake-db-lookup nil) =throws=> (RuntimeException. "Should be skipped!")) (validate [(group password-presence-validation (group email-presence-validation email-format-validation email-uniqueness-validation))] {:email "me@" :password "<PASSWORD>"}) => {:email #{"is invalid"}} (validate [(group password-presence-validation (group email-presence-validation email-format-validation email-uniqueness-validation))] {:email "me@" :password ""}) => {:password #{"<PASSWORD>"}})) (facts "about 'make-claim" (let [only-even (make-claim even? :number "must be even")] (fact "it returns a function that returns `nil` when called with data that passes the predicate" (only-even 2) => nil) (fact "it returns a function that returns an error tuple with the given key and message when called with data that fails the predicate" (only-even 1) => [:number "must be even"]))) (facts "about 'make-denial" (let [only-even (make-denial odd? :number "must be even")] (fact "it returns a function that returns `nil` when called with data that passes the predicate" (only-even 2) => nil) (fact "it returns a function that returns an error tuple with the given key and message when called with data that fails the predicate" (only-even 1) => [:number "must be even"])))
true
(ns heckle.core-test (:require [midje.sweet :refer :all] [heckle.core :refer :all])) (defn email-presence-validation [data] (when (empty? (get data :email "")) [:email "is required"])) (defn email-format-validation [data] (when-not (re-find #".@." (get data :email "")) [:email "is invalid"])) (defn password-presence-validation [data] (when (empty? (get data :password "")) [:password "is required"])) (defn fake-db-lookup [email] (get {"PI:EMAIL:<EMAIL>END_PI" {:first-name "Me"}} email)) (defn email-uniqueness-validation [data] (when (fake-db-lookup (:email data)) [:email "is already taken"])) (facts "about 'validate" (fact "it returns no errors when no validations are given" (validate [] {}) => {} (validate [] {:data "value"}) => {}) (fact "it returns no errors when the data passes all validations" (validate [email-presence-validation] {:email "any non-empty string"}) => {} (validate [email-presence-validation email-format-validation] {:email "PI:EMAIL:<EMAIL>END_PI"}) => {} (validate [email-presence-validation password-presence-validation] {:email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"}) => {}) (fact "it returns error messages grouped by error key when the data" (validate [email-presence-validation] {}) => {:email #{"is required"}} (validate [email-presence-validation email-format-validation password-presence-validation] {}) => {:email #{"is required" "is invalid"} :password #{"PI:PASSWORD:<PASSWORD>END_PI"}})) (facts "about 'group" (fact "it returns no errors the group is valid" (validate [] {}) => {} (validate [(group email-presence-validation email-format-validation)] {:email "PI:EMAIL:<EMAIL>END_PI"}) => {}) (fact "it skips the rest of the group once one validation fails" (against-background (fake-db-lookup nil) =throws=> (RuntimeException. "Should be skipped!")) (validate [(group email-presence-validation email-format-validation email-uniqueness-validation)] {}) => {:email #{"is required"}}) (fact "groups can be nested indefinitely" (against-background (fake-db-lookup nil) =throws=> (RuntimeException. "Should be skipped!")) (validate [(group password-presence-validation (group email-presence-validation email-format-validation email-uniqueness-validation))] {:email "me@" :password "PI:PASSWORD:<PASSWORD>END_PI"}) => {:email #{"is invalid"}} (validate [(group password-presence-validation (group email-presence-validation email-format-validation email-uniqueness-validation))] {:email "me@" :password ""}) => {:password #{"PI:PASSWORD:<PASSWORD>END_PI"}})) (facts "about 'make-claim" (let [only-even (make-claim even? :number "must be even")] (fact "it returns a function that returns `nil` when called with data that passes the predicate" (only-even 2) => nil) (fact "it returns a function that returns an error tuple with the given key and message when called with data that fails the predicate" (only-even 1) => [:number "must be even"]))) (facts "about 'make-denial" (let [only-even (make-denial odd? :number "must be even")] (fact "it returns a function that returns `nil` when called with data that passes the predicate" (only-even 2) => nil) (fact "it returns a function that returns an error tuple with the given key and message when called with data that fails the predicate" (only-even 1) => [:number "must be even"])))
[ { "context": " {:status 200 :body {:access_token \"foo\" :uid \"mjackson\" :scope [\"uid\"]}}\n {:status 401})))\n\n\n(defn ", "end": 995, "score": 0.9877919554710388, "start": 987, "tag": "USERNAME", "value": "mjackson" }, { "context": " {:as :json :oauth-token \"foo\"})))))\n (testing \"When an invalid token is giv", "end": 1643, "score": 0.6596829295158386, "start": 1640, "tag": "PASSWORD", "value": "foo" }, { "context": " {:as :json :oauth-token \"foo1\" :throw-exceptions? false})))))\n (m/stop)))\n{{", "end": 1868, "score": 0.9816370010375977, "start": 1864, "tag": "PASSWORD", "value": "foo1" } ]
resources/leiningen/new/cyrus/test/_namespace_/api_test.clj
dryewo/cyrus
9
(ns {{namespace}}.api-test (:require [clojure.test :refer :all] [mount.lite :as m] [clj-http.client :as http]{{#swagger1st-oauth2}} [aleph.http.server] [ring.middleware.json :refer [wrap-json-response]]{{/swagger1st-oauth2}} [{{namespace}}.api :refer :all] [{{namespace}}.http] [{{namespace}}.test-utils :as tu])) (deftest api (tu/start-with-env-override '{HTTP_PORT 8080} #'{{namespace}}.http/server) (is (= {:message "Hello Dude"} (:body (http/get "http://localhost:8080/api/hello/Dude" {:as :json})))) (is (= 200 (:status (http/get "http://localhost:8080/api/ui")))) (is (= 200 (:status (http/get "http://localhost:8080/api/swagger.json" {:as :json})))) (m/stop)) {{#swagger1st-oauth2}} (defn mock-tokeninfo-handler [request] (let [authorization (get-in request [:headers "authorization"])] (if (= "Bearer foo" authorization) {:status 200 :body {:access_token "foo" :uid "mjackson" :scope ["uid"]}} {:status 401}))) (defn start-mock-tokeninfo-server [] (aleph.http/start-server (wrap-json-response mock-tokeninfo-handler) {:port 7777})) (deftest api-protection (with-open [mock-tokeninfo-server (start-mock-tokeninfo-server)] (tu/start-with-env-override '{HTTP_PORT 8080 TOKENINFO_URL "http://localhost:7777/"} #'{{namespace}}.http/server) (testing "When a correct token is given, everything works" (is (= {:message "Hello Dude"} (:body (http/get "http://localhost:8080/api/hello/Dude" {:as :json :oauth-token "foo"}))))) (testing "When an invalid token is given, returns 401" (is (= 401 (:status (http/get "http://localhost:8080/api/hello/Dude" {:as :json :oauth-token "foo1" :throw-exceptions? false}))))) (m/stop))) {{/swagger1st-oauth2}}
42665
(ns {{namespace}}.api-test (:require [clojure.test :refer :all] [mount.lite :as m] [clj-http.client :as http]{{#swagger1st-oauth2}} [aleph.http.server] [ring.middleware.json :refer [wrap-json-response]]{{/swagger1st-oauth2}} [{{namespace}}.api :refer :all] [{{namespace}}.http] [{{namespace}}.test-utils :as tu])) (deftest api (tu/start-with-env-override '{HTTP_PORT 8080} #'{{namespace}}.http/server) (is (= {:message "Hello Dude"} (:body (http/get "http://localhost:8080/api/hello/Dude" {:as :json})))) (is (= 200 (:status (http/get "http://localhost:8080/api/ui")))) (is (= 200 (:status (http/get "http://localhost:8080/api/swagger.json" {:as :json})))) (m/stop)) {{#swagger1st-oauth2}} (defn mock-tokeninfo-handler [request] (let [authorization (get-in request [:headers "authorization"])] (if (= "Bearer foo" authorization) {:status 200 :body {:access_token "foo" :uid "mjackson" :scope ["uid"]}} {:status 401}))) (defn start-mock-tokeninfo-server [] (aleph.http/start-server (wrap-json-response mock-tokeninfo-handler) {:port 7777})) (deftest api-protection (with-open [mock-tokeninfo-server (start-mock-tokeninfo-server)] (tu/start-with-env-override '{HTTP_PORT 8080 TOKENINFO_URL "http://localhost:7777/"} #'{{namespace}}.http/server) (testing "When a correct token is given, everything works" (is (= {:message "Hello Dude"} (:body (http/get "http://localhost:8080/api/hello/Dude" {:as :json :oauth-token "<PASSWORD>"}))))) (testing "When an invalid token is given, returns 401" (is (= 401 (:status (http/get "http://localhost:8080/api/hello/Dude" {:as :json :oauth-token "<PASSWORD>" :throw-exceptions? false}))))) (m/stop))) {{/swagger1st-oauth2}}
true
(ns {{namespace}}.api-test (:require [clojure.test :refer :all] [mount.lite :as m] [clj-http.client :as http]{{#swagger1st-oauth2}} [aleph.http.server] [ring.middleware.json :refer [wrap-json-response]]{{/swagger1st-oauth2}} [{{namespace}}.api :refer :all] [{{namespace}}.http] [{{namespace}}.test-utils :as tu])) (deftest api (tu/start-with-env-override '{HTTP_PORT 8080} #'{{namespace}}.http/server) (is (= {:message "Hello Dude"} (:body (http/get "http://localhost:8080/api/hello/Dude" {:as :json})))) (is (= 200 (:status (http/get "http://localhost:8080/api/ui")))) (is (= 200 (:status (http/get "http://localhost:8080/api/swagger.json" {:as :json})))) (m/stop)) {{#swagger1st-oauth2}} (defn mock-tokeninfo-handler [request] (let [authorization (get-in request [:headers "authorization"])] (if (= "Bearer foo" authorization) {:status 200 :body {:access_token "foo" :uid "mjackson" :scope ["uid"]}} {:status 401}))) (defn start-mock-tokeninfo-server [] (aleph.http/start-server (wrap-json-response mock-tokeninfo-handler) {:port 7777})) (deftest api-protection (with-open [mock-tokeninfo-server (start-mock-tokeninfo-server)] (tu/start-with-env-override '{HTTP_PORT 8080 TOKENINFO_URL "http://localhost:7777/"} #'{{namespace}}.http/server) (testing "When a correct token is given, everything works" (is (= {:message "Hello Dude"} (:body (http/get "http://localhost:8080/api/hello/Dude" {:as :json :oauth-token "PI:PASSWORD:<PASSWORD>END_PI"}))))) (testing "When an invalid token is given, returns 401" (is (= 401 (:status (http/get "http://localhost:8080/api/hello/Dude" {:as :json :oauth-token "PI:PASSWORD:<PASSWORD>END_PI" :throw-exceptions? false}))))) (m/stop))) {{/swagger1st-oauth2}}
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.bixby.web.ftl\n\n ", "end": 597, "score": 0.9998483657836914, "start": 584, "tag": "NAME", "value": "Kenneth Leung" } ]
src/main/clojure/czlab/bixby/web/ftl.clj
llnek/skaro
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.bixby.web.ftl (:require [clojure.java.io :as io] [clojure.walk :as cw] [clojure.string :as cs] [czlab.basal.io :as i] [czlab.basal.core :as c] [czlab.basal.util :as u]) (:import [freemarker.template TemplateMethodModelEx TemplateBooleanModel TemplateCollectionModel TemplateDateModel TemplateHashModelEx TemplateNumberModel TemplateScalarModel TemplateSequenceModel TemplateMethodModel Configuration DefaultObjectWrapper] [java.util Date] [czlab.basal XData] [java.io File Writer StringWriter])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol CljApi (x->clj [_] "Turn something into clojure.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (extend-protocol CljApi TemplateCollectionModel (x->clj [_] (if-some [itr (.iterator _)] (loop [acc []] (if-not (.hasNext itr) acc (recur (conj acc (x->clj (.next itr)))))))) TemplateSequenceModel (x->clj [s] (for [n (range (.size s))] (x->clj (.get s n)))) TemplateHashModelEx (x->clj [m] (zipmap (x->clj (.keys m)) (x->clj (.values m)))) TemplateBooleanModel (x->clj [_] (.getAsBoolean _)) TemplateNumberModel (x->clj [_] (.getAsNumber _)) TemplateScalarModel (x->clj [_] (.getAsString _)) TemplateDateModel (x->clj [_] (.getAsDate _)) Object (x->clj [_] (u/throw-BadArg "Failed to convert %s" (class _)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- x->ftl-model<> "Sanitize the model to be ftl compliant." [m] (letfn [(skey [[k v]] [(cs/replace (c/kw->str k) #"[$!#*+\-]" "_") v]) (x->ftl [func] (reify TemplateMethodModelEx (exec [_ args] (apply func (map x->clj args)))))] (cw/postwalk #(cond (map? %) (c/map-> (map skey %)) (fn? %) (x->ftl %) :else %) m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ftl-config<> "Create a FTL config." {:tag Configuration} ([root] (ftl-config<> root nil)) ([root shared-vars] (c/do-with [cfg (Configuration.)] (let [dir (io/file root)] (assert (.exists dir) (c/fmt "Bad root dir %s." root)) (c/info "freemarker root: %s." root) (doto cfg (.setDirectoryForTemplateLoading dir) (.setObjectWrapper (DefaultObjectWrapper.))) (doseq [[^String k v] (x->ftl-model<> (or shared-vars {}))] (.setSharedVariable cfg k v)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn render->ftl "Render a FreeMarker template." {:arglists '([cfg path model] [cfg path model xref?])} ([cfg path model] (render->ftl cfg path model nil)) ([cfg path model xref?] {:pre [(c/is? Configuration cfg)]} (c/do-with-str [out (StringWriter.)] (c/debug "about to render tpl: %s." path) (if-some [t (.getTemplate ^Configuration cfg ^String path)] (.process t (if xref? (x->ftl-model<> model) model) out))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn load-template "Load and evaluate a FreeMarker template." {:arglists '([cfg tpath data])} [cfg tpath data] {:pre [(c/is? Configuration cfg)]} (let [ts (str "/" (c/triml tpath "/"))] {:data (XData. (render->ftl cfg ts data)) :ctype (condp #(cs/ends-with? %2 %1) ts ".json" "application/json" ".xml" "application/xml" ".html" "text/html" ;else "text/plain")})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
77100
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.bixby.web.ftl (:require [clojure.java.io :as io] [clojure.walk :as cw] [clojure.string :as cs] [czlab.basal.io :as i] [czlab.basal.core :as c] [czlab.basal.util :as u]) (:import [freemarker.template TemplateMethodModelEx TemplateBooleanModel TemplateCollectionModel TemplateDateModel TemplateHashModelEx TemplateNumberModel TemplateScalarModel TemplateSequenceModel TemplateMethodModel Configuration DefaultObjectWrapper] [java.util Date] [czlab.basal XData] [java.io File Writer StringWriter])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol CljApi (x->clj [_] "Turn something into clojure.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (extend-protocol CljApi TemplateCollectionModel (x->clj [_] (if-some [itr (.iterator _)] (loop [acc []] (if-not (.hasNext itr) acc (recur (conj acc (x->clj (.next itr)))))))) TemplateSequenceModel (x->clj [s] (for [n (range (.size s))] (x->clj (.get s n)))) TemplateHashModelEx (x->clj [m] (zipmap (x->clj (.keys m)) (x->clj (.values m)))) TemplateBooleanModel (x->clj [_] (.getAsBoolean _)) TemplateNumberModel (x->clj [_] (.getAsNumber _)) TemplateScalarModel (x->clj [_] (.getAsString _)) TemplateDateModel (x->clj [_] (.getAsDate _)) Object (x->clj [_] (u/throw-BadArg "Failed to convert %s" (class _)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- x->ftl-model<> "Sanitize the model to be ftl compliant." [m] (letfn [(skey [[k v]] [(cs/replace (c/kw->str k) #"[$!#*+\-]" "_") v]) (x->ftl [func] (reify TemplateMethodModelEx (exec [_ args] (apply func (map x->clj args)))))] (cw/postwalk #(cond (map? %) (c/map-> (map skey %)) (fn? %) (x->ftl %) :else %) m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ftl-config<> "Create a FTL config." {:tag Configuration} ([root] (ftl-config<> root nil)) ([root shared-vars] (c/do-with [cfg (Configuration.)] (let [dir (io/file root)] (assert (.exists dir) (c/fmt "Bad root dir %s." root)) (c/info "freemarker root: %s." root) (doto cfg (.setDirectoryForTemplateLoading dir) (.setObjectWrapper (DefaultObjectWrapper.))) (doseq [[^String k v] (x->ftl-model<> (or shared-vars {}))] (.setSharedVariable cfg k v)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn render->ftl "Render a FreeMarker template." {:arglists '([cfg path model] [cfg path model xref?])} ([cfg path model] (render->ftl cfg path model nil)) ([cfg path model xref?] {:pre [(c/is? Configuration cfg)]} (c/do-with-str [out (StringWriter.)] (c/debug "about to render tpl: %s." path) (if-some [t (.getTemplate ^Configuration cfg ^String path)] (.process t (if xref? (x->ftl-model<> model) model) out))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn load-template "Load and evaluate a FreeMarker template." {:arglists '([cfg tpath data])} [cfg tpath data] {:pre [(c/is? Configuration cfg)]} (let [ts (str "/" (c/triml tpath "/"))] {:data (XData. (render->ftl cfg ts data)) :ctype (condp #(cs/ends-with? %2 %1) ts ".json" "application/json" ".xml" "application/xml" ".html" "text/html" ;else "text/plain")})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.bixby.web.ftl (:require [clojure.java.io :as io] [clojure.walk :as cw] [clojure.string :as cs] [czlab.basal.io :as i] [czlab.basal.core :as c] [czlab.basal.util :as u]) (:import [freemarker.template TemplateMethodModelEx TemplateBooleanModel TemplateCollectionModel TemplateDateModel TemplateHashModelEx TemplateNumberModel TemplateScalarModel TemplateSequenceModel TemplateMethodModel Configuration DefaultObjectWrapper] [java.util Date] [czlab.basal XData] [java.io File Writer StringWriter])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol CljApi (x->clj [_] "Turn something into clojure.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (extend-protocol CljApi TemplateCollectionModel (x->clj [_] (if-some [itr (.iterator _)] (loop [acc []] (if-not (.hasNext itr) acc (recur (conj acc (x->clj (.next itr)))))))) TemplateSequenceModel (x->clj [s] (for [n (range (.size s))] (x->clj (.get s n)))) TemplateHashModelEx (x->clj [m] (zipmap (x->clj (.keys m)) (x->clj (.values m)))) TemplateBooleanModel (x->clj [_] (.getAsBoolean _)) TemplateNumberModel (x->clj [_] (.getAsNumber _)) TemplateScalarModel (x->clj [_] (.getAsString _)) TemplateDateModel (x->clj [_] (.getAsDate _)) Object (x->clj [_] (u/throw-BadArg "Failed to convert %s" (class _)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- x->ftl-model<> "Sanitize the model to be ftl compliant." [m] (letfn [(skey [[k v]] [(cs/replace (c/kw->str k) #"[$!#*+\-]" "_") v]) (x->ftl [func] (reify TemplateMethodModelEx (exec [_ args] (apply func (map x->clj args)))))] (cw/postwalk #(cond (map? %) (c/map-> (map skey %)) (fn? %) (x->ftl %) :else %) m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ftl-config<> "Create a FTL config." {:tag Configuration} ([root] (ftl-config<> root nil)) ([root shared-vars] (c/do-with [cfg (Configuration.)] (let [dir (io/file root)] (assert (.exists dir) (c/fmt "Bad root dir %s." root)) (c/info "freemarker root: %s." root) (doto cfg (.setDirectoryForTemplateLoading dir) (.setObjectWrapper (DefaultObjectWrapper.))) (doseq [[^String k v] (x->ftl-model<> (or shared-vars {}))] (.setSharedVariable cfg k v)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn render->ftl "Render a FreeMarker template." {:arglists '([cfg path model] [cfg path model xref?])} ([cfg path model] (render->ftl cfg path model nil)) ([cfg path model xref?] {:pre [(c/is? Configuration cfg)]} (c/do-with-str [out (StringWriter.)] (c/debug "about to render tpl: %s." path) (if-some [t (.getTemplate ^Configuration cfg ^String path)] (.process t (if xref? (x->ftl-model<> model) model) out))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn load-template "Load and evaluate a FreeMarker template." {:arglists '([cfg tpath data])} [cfg tpath data] {:pre [(c/is? Configuration cfg)]} (let [ts (str "/" (c/triml tpath "/"))] {:data (XData. (render->ftl cfg ts data)) :ctype (condp #(cs/ends-with? %2 %1) ts ".json" "application/json" ".xml" "application/xml" ".html" "text/html" ;else "text/plain")})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": "s.sqs :as sqs]))\n\n(def config\n {:access-key \"default\"\n :secret-key \"default\"\n :s3-endpoint ", "end": 278, "score": 0.9945747256278992, "start": 271, "tag": "KEY", "value": "default" }, { "context": "\n {:access-key \"default\"\n :secret-key \"default\"\n :s3-endpoint \"http://localhost:4566\"\n :s", "end": 307, "score": 0.9948481321334839, "start": 300, "tag": "KEY", "value": "default" } ]
src/clj_sqs_extended/core.clj
Motiva-AI/clj-sqs-extended
1
(ns clj-sqs-extended.core (:require [clojure.core.async :refer [chan <!! thread]] [clojure.tools.logging :as log] [clj-sqs-extended.internal.receive :as receive] [clj-sqs-extended.aws.sqs :as sqs])) (def config {:access-key "default" :secret-key "default" :s3-endpoint "http://localhost:4566" :s3-bucket-name "example-bucket" :sqs-endpoint "http://localhost:4566" :region "us-east-2"}) ;; Conveniance declarations (def sqs-ext-client sqs/sqs-ext-client) (def send-message sqs/send-message) (def send-fifo-message sqs/send-fifo-message) (defn- launch-handler-threads [number-of-handler-threads handler-chan auto-delete handler-fn] (dotimes [_ number-of-handler-threads] (thread (loop [] (when-let [{message-body :body done-fn :done-fn} (<!! handler-chan)] (try (if auto-delete (handler-fn message-body) (handler-fn message-body done-fn)) (catch Throwable error (log/error error (.getMessage error)))) (recur)))))) (defn handle-queue "Setup a loop that listens to a queue and processes all incoming messages. Arguments: sqs-ext-client - A client object from calling (sqs-ext-client config) handler-opts - A map for the queue handling settings: queue-url - A string containing the unique URL of the queue to handle (required) number-of-handler-threads - Number of how many threads to run for handling message receival (optional, default: 4) restart-limit - If a potentially non-fatal error occurs while handling the queue, it will try this many times to restart in order to hopefully recover from the occured error (optional, default: 6) restart-delay-seconds - If the loop restarts, restart will be delayed by this many seconds (optional, default: 10) auto-delete - A boolean where true: will immediately delete the message false: will provide a `done-fn` key inside the returned messages and the message will be left untouched by this API (optional, defaults: true) handler-fn - A function to which new incoming messages will be passed to (required) NOTE: If auto-delete above is set to false, a `done-fn` function will be passed as second argument which should be called to delete the message when processing has been finished. Returns: A stop function - Call this function to terminate the loop and receive a map of final information about the finished handling process (hopefully handy for debugging). That map includes: {:iteration The total count of iterations the loop was executed :restart-count 0 Number of times the loop was restarted :started-at (t/now) A tick instant timestamp when the loop was started :last-iteration-started-at A tick instant timestamp when the loop began last :stopped-at A tick instant timestamp when the loop was stopped :last-loop-duration-in-seconds} Last loop's running time in seconds" [sqs-ext-client {:keys [queue-url number-of-handler-threads restart-limit restart-delay-seconds auto-delete] :or {number-of-handler-threads 4 restart-limit 6 restart-delay-seconds 10 auto-delete true}} handler-fn] (let [handler-chan (chan) stop-fn (receive/receive-loop queue-url handler-chan (partial sqs/receive-messages sqs-ext-client queue-url) (partial sqs/delete-message! sqs-ext-client queue-url) {:auto-delete? auto-delete :restart-opts {:restart-limit restart-limit :restart-delay-seconds restart-delay-seconds}})] (log/infof (str "Handling queue '%s' with: " "number-of-handler-threads [%d], " "restart-limit [%d], " "restart-delay-seconds [%d], " "auto-delete [%s].") queue-url number-of-handler-threads restart-limit restart-delay-seconds auto-delete) (launch-handler-threads number-of-handler-threads handler-chan auto-delete handler-fn) stop-fn))
94454
(ns clj-sqs-extended.core (:require [clojure.core.async :refer [chan <!! thread]] [clojure.tools.logging :as log] [clj-sqs-extended.internal.receive :as receive] [clj-sqs-extended.aws.sqs :as sqs])) (def config {:access-key "<KEY>" :secret-key "<KEY>" :s3-endpoint "http://localhost:4566" :s3-bucket-name "example-bucket" :sqs-endpoint "http://localhost:4566" :region "us-east-2"}) ;; Conveniance declarations (def sqs-ext-client sqs/sqs-ext-client) (def send-message sqs/send-message) (def send-fifo-message sqs/send-fifo-message) (defn- launch-handler-threads [number-of-handler-threads handler-chan auto-delete handler-fn] (dotimes [_ number-of-handler-threads] (thread (loop [] (when-let [{message-body :body done-fn :done-fn} (<!! handler-chan)] (try (if auto-delete (handler-fn message-body) (handler-fn message-body done-fn)) (catch Throwable error (log/error error (.getMessage error)))) (recur)))))) (defn handle-queue "Setup a loop that listens to a queue and processes all incoming messages. Arguments: sqs-ext-client - A client object from calling (sqs-ext-client config) handler-opts - A map for the queue handling settings: queue-url - A string containing the unique URL of the queue to handle (required) number-of-handler-threads - Number of how many threads to run for handling message receival (optional, default: 4) restart-limit - If a potentially non-fatal error occurs while handling the queue, it will try this many times to restart in order to hopefully recover from the occured error (optional, default: 6) restart-delay-seconds - If the loop restarts, restart will be delayed by this many seconds (optional, default: 10) auto-delete - A boolean where true: will immediately delete the message false: will provide a `done-fn` key inside the returned messages and the message will be left untouched by this API (optional, defaults: true) handler-fn - A function to which new incoming messages will be passed to (required) NOTE: If auto-delete above is set to false, a `done-fn` function will be passed as second argument which should be called to delete the message when processing has been finished. Returns: A stop function - Call this function to terminate the loop and receive a map of final information about the finished handling process (hopefully handy for debugging). That map includes: {:iteration The total count of iterations the loop was executed :restart-count 0 Number of times the loop was restarted :started-at (t/now) A tick instant timestamp when the loop was started :last-iteration-started-at A tick instant timestamp when the loop began last :stopped-at A tick instant timestamp when the loop was stopped :last-loop-duration-in-seconds} Last loop's running time in seconds" [sqs-ext-client {:keys [queue-url number-of-handler-threads restart-limit restart-delay-seconds auto-delete] :or {number-of-handler-threads 4 restart-limit 6 restart-delay-seconds 10 auto-delete true}} handler-fn] (let [handler-chan (chan) stop-fn (receive/receive-loop queue-url handler-chan (partial sqs/receive-messages sqs-ext-client queue-url) (partial sqs/delete-message! sqs-ext-client queue-url) {:auto-delete? auto-delete :restart-opts {:restart-limit restart-limit :restart-delay-seconds restart-delay-seconds}})] (log/infof (str "Handling queue '%s' with: " "number-of-handler-threads [%d], " "restart-limit [%d], " "restart-delay-seconds [%d], " "auto-delete [%s].") queue-url number-of-handler-threads restart-limit restart-delay-seconds auto-delete) (launch-handler-threads number-of-handler-threads handler-chan auto-delete handler-fn) stop-fn))
true
(ns clj-sqs-extended.core (:require [clojure.core.async :refer [chan <!! thread]] [clojure.tools.logging :as log] [clj-sqs-extended.internal.receive :as receive] [clj-sqs-extended.aws.sqs :as sqs])) (def config {:access-key "PI:KEY:<KEY>END_PI" :secret-key "PI:KEY:<KEY>END_PI" :s3-endpoint "http://localhost:4566" :s3-bucket-name "example-bucket" :sqs-endpoint "http://localhost:4566" :region "us-east-2"}) ;; Conveniance declarations (def sqs-ext-client sqs/sqs-ext-client) (def send-message sqs/send-message) (def send-fifo-message sqs/send-fifo-message) (defn- launch-handler-threads [number-of-handler-threads handler-chan auto-delete handler-fn] (dotimes [_ number-of-handler-threads] (thread (loop [] (when-let [{message-body :body done-fn :done-fn} (<!! handler-chan)] (try (if auto-delete (handler-fn message-body) (handler-fn message-body done-fn)) (catch Throwable error (log/error error (.getMessage error)))) (recur)))))) (defn handle-queue "Setup a loop that listens to a queue and processes all incoming messages. Arguments: sqs-ext-client - A client object from calling (sqs-ext-client config) handler-opts - A map for the queue handling settings: queue-url - A string containing the unique URL of the queue to handle (required) number-of-handler-threads - Number of how many threads to run for handling message receival (optional, default: 4) restart-limit - If a potentially non-fatal error occurs while handling the queue, it will try this many times to restart in order to hopefully recover from the occured error (optional, default: 6) restart-delay-seconds - If the loop restarts, restart will be delayed by this many seconds (optional, default: 10) auto-delete - A boolean where true: will immediately delete the message false: will provide a `done-fn` key inside the returned messages and the message will be left untouched by this API (optional, defaults: true) handler-fn - A function to which new incoming messages will be passed to (required) NOTE: If auto-delete above is set to false, a `done-fn` function will be passed as second argument which should be called to delete the message when processing has been finished. Returns: A stop function - Call this function to terminate the loop and receive a map of final information about the finished handling process (hopefully handy for debugging). That map includes: {:iteration The total count of iterations the loop was executed :restart-count 0 Number of times the loop was restarted :started-at (t/now) A tick instant timestamp when the loop was started :last-iteration-started-at A tick instant timestamp when the loop began last :stopped-at A tick instant timestamp when the loop was stopped :last-loop-duration-in-seconds} Last loop's running time in seconds" [sqs-ext-client {:keys [queue-url number-of-handler-threads restart-limit restart-delay-seconds auto-delete] :or {number-of-handler-threads 4 restart-limit 6 restart-delay-seconds 10 auto-delete true}} handler-fn] (let [handler-chan (chan) stop-fn (receive/receive-loop queue-url handler-chan (partial sqs/receive-messages sqs-ext-client queue-url) (partial sqs/delete-message! sqs-ext-client queue-url) {:auto-delete? auto-delete :restart-opts {:restart-limit restart-limit :restart-delay-seconds restart-delay-seconds}})] (log/infof (str "Handling queue '%s' with: " "number-of-handler-threads [%d], " "restart-limit [%d], " "restart-delay-seconds [%d], " "auto-delete [%s].") queue-url number-of-handler-threads restart-limit restart-delay-seconds auto-delete) (launch-handler-threads number-of-handler-threads handler-chan auto-delete handler-fn) stop-fn))
[ { "context": "-2 1900)\n :max (time/t -2 2100)}\n\n \"sad\"\n \"sada\"\n \"upravo sad\"\n \"ovaj tren\"\n (datetim", "end": 203, "score": 0.5127118229866028, "start": 200, "tag": "NAME", "value": "sad" }, { "context": " (time/t -2 2100)}\n\n \"sad\"\n \"sada\"\n \"upravo sad\"\n \"ovaj tren\"\n (datetime 2013 2 12 4 30 00)\n\n ", "end": 227, "score": 0.6020736694335938, "start": 224, "tag": "NAME", "value": "sad" }, { "context": " 2100)}\n\n \"sad\"\n \"sada\"\n \"upravo sad\"\n \"ovaj tren\"\n (datetime 2013 2 12 4 30 00)\n\n \"danas\"\n (dat", "end": 241, "score": 0.6678920388221741, "start": 238, "tag": "NAME", "value": "ren" }, { "context": "\n \"ovaj tren\"\n (datetime 2013 2 12 4 30 00)\n\n \"danas\"\n (datetime 2013 2 12)\n\n \"jucer\"\n \"jučer\"\n (d", "end": 283, "score": 0.926077127456665, "start": 278, "tag": "NAME", "value": "danas" }, { "context": "12 4 30 00)\n\n \"danas\"\n (datetime 2013 2 12)\n\n \"jucer\"\n \"jučer\"\n (datetime 2013 2 11)\n\n \"sutra\"\n (d", "end": 317, "score": 0.9533518552780151, "start": 312, "tag": "NAME", "value": "jucer" }, { "context": ")\n\n \"danas\"\n (datetime 2013 2 12)\n\n \"jucer\"\n \"jučer\"\n (datetime 2013 2 11)\n\n \"sutra\"\n (datetime 20", "end": 327, "score": 0.9448477625846863, "start": 322, "tag": "NAME", "value": "jučer" }, { "context": ")\n\n \"jucer\"\n \"jučer\"\n (datetime 2013 2 11)\n\n \"sutra\"\n (datetime 2013 2 13)\n\n \"ponedjeljak\"\n \"pon.\"", "end": 361, "score": 0.9513325691223145, "start": 356, "tag": "NAME", "value": "sutra" }, { "context": " 2013 2 11)\n\n \"sutra\"\n (datetime 2013 2 13)\n\n \"ponedjeljak\"\n \"pon.\"\n \"ovaj ponedjeljak\"\n (datetime 2013 2", "end": 401, "score": 0.9732041954994202, "start": 390, "tag": "NAME", "value": "ponedjeljak" }, { "context": "atetime 2013 2 13)\n\n \"ponedjeljak\"\n \"pon.\"\n \"ovaj ponedjeljak\"\n (datetime 2013 2 18 :day-of-week 1", "end": 419, "score": 0.6476152539253235, "start": 417, "tag": "NAME", "value": "aj" }, { "context": "ime 2013 2 13)\n\n \"ponedjeljak\"\n \"pon.\"\n \"ovaj ponedjeljak\"\n (datetime 2013 2 18 :day-of-week 1)\n\n \"ponedj", "end": 431, "score": 0.8734654784202576, "start": 421, "tag": "NAME", "value": "onedjeljak" }, { "context": "jeljak\"\n (datetime 2013 2 18 :day-of-week 1)\n\n \"ponedjeljak, 18. veljace\"\n \"ponedjeljak, 18. veljače\"\n (dat", "end": 486, "score": 0.86676424741745, "start": 475, "tag": "NAME", "value": "ponedjeljak" }, { "context": "2013 2 18 :day-of-week 1)\n\n \"ponedjeljak, 18. veljace\"\n \"ponedjeljak, 18. veljače\"\n (datetime 2013 2 ", "end": 499, "score": 0.7314087152481079, "start": 495, "tag": "NAME", "value": "jace" }, { "context": "me 2013 2 18 :day-of-week 1 :day 18 :month 2)\n\n \"utorak\"\n \"utorak 19.\"\n (datetime 2013 2 19)\n\n \"cetvrt", "end": 595, "score": 0.9433957934379578, "start": 589, "tag": "NAME", "value": "utorak" }, { "context": "utorak\"\n \"utorak 19.\"\n (datetime 2013 2 19)\n\n \"cetvrtak\"\n \"četvrtak\"\n \"čet\"\n \"cet.\"\n (datetime 2013 2", "end": 647, "score": 0.8689643740653992, "start": 639, "tag": "NAME", "value": "cetvrtak" }, { "context": "orak 19.\"\n (datetime 2013 2 19)\n\n \"cetvrtak\"\n \"četvrtak\"\n \"čet\"\n \"cet.\"\n (datetime 2013 2 14)\n\n \"peta", "end": 660, "score": 0.7710846066474915, "start": 652, "tag": "NAME", "value": "četvrtak" }, { "context": "datetime 2013 2 19)\n\n \"cetvrtak\"\n \"četvrtak\"\n \"čet\"\n \"cet.\"\n (datetime 2013 2 14)\n\n \"petak\"\n \"pe", "end": 668, "score": 0.6551936864852905, "start": 665, "tag": "NAME", "value": "čet" }, { "context": "rtak\"\n \"čet\"\n \"cet.\"\n (datetime 2013 2 14)\n\n \"petak\"\n \"pet\"\n \"pet.\"\n (datetime 2013 2 15)\n\n \"subo", "end": 711, "score": 0.9568343162536621, "start": 706, "tag": "NAME", "value": "petak" }, { "context": "etak\"\n \"pet\"\n \"pet.\"\n (datetime 2013 2 15)\n\n \"subota\"\n \"sub\"\n \"sub.\"\n (datetime 2013 2 16)\n\n \"nedj", "end": 763, "score": 0.8072150945663452, "start": 757, "tag": "NAME", "value": "subota" }, { "context": "bota\"\n \"sub\"\n \"sub.\"\n (datetime 2013 2 16)\n\n \"nedjelja\"\n \"ned\"\n \"ned.\"\n (datetime 2013 2 17)\n\n \"1. o", "end": 817, "score": 0.9673251509666443, "start": 809, "tag": "NAME", "value": "nedjelja" }, { "context": "\n \"sub.\"\n (datetime 2013 2 16)\n\n \"nedjelja\"\n \"ned\"\n \"ned.\"\n (datetime 2013 2 17)\n\n \"1. ozujak\"\n ", "end": 825, "score": 0.5442020297050476, "start": 822, "tag": "NAME", "value": "ned" }, { "context": " (datetime 2013 3 3 :day 3 :month 3)\n\n ; \"martovske ide\"\n ; (datetime 2013 3 15 :month 3)\n\n \"3. oz", "end": 1031, "score": 0.5181745290756226, "start": 1027, "tag": "NAME", "value": "vske" }, { "context": "2)\n\n \"sljedeci utorak\" ; when today is Tuesday, \"mardi prochain\" is a week from now\n (datetime 2013 2 19 :day-of", "end": 3183, "score": 0.7673319578170776, "start": 3169, "tag": "NAME", "value": "mardi prochain" }, { "context": "(datetime 2013 2 19 :day-of-week 2)\n\n \"sljedecu srijedu\" ; when today is Tuesday, \"mercredi prochain\" is ", "end": 3262, "score": 0.642520546913147, "start": 3256, "tag": "NAME", "value": "rijedu" }, { "context": "me 2013 2 13 :day-of-week 3)\n\n \"sljedeci tjedan u srijedu\"\n \"srijeda sljedeci tjedan\"\n (datetime 2013 ", "end": 3385, "score": 0.5452932715415955, "start": 3381, "tag": "NAME", "value": "srij" }, { "context": "tjedan\"\n (datetime 2013 2 20 :day-of-week 3)\n\n \"sljedeci petak\"\n (datetime 2013 2 15 :day-of-week 5)\n\n ", "end": 3466, "score": 0.6394298076629639, "start": 3460, "tag": "NAME", "value": "sljede" }, { "context": " (datetime 2013 2 20 :day-of-week 3)\n\n \"sljedeci petak\"\n (datetime 2013 2 15 :day-of-week 5)\n\n \"ovaj t", "end": 3474, "score": 0.7207874059677124, "start": 3469, "tag": "NAME", "value": "petak" }, { "context": "rak\"\n (datetime 2013 2 19 :day-of-week 2)\n\n \"ova srijeda\"\n \"ovaj tjedan u srijedu\"\n (datetime 2013 2 13 ", "end": 3653, "score": 0.6565327048301697, "start": 3646, "tag": "NAME", "value": "srijeda" }, { "context": " \"za 2.5 sata\"\n (datetime 2013 2 12 7 0 0)\n\n \"za jedan sat\"\n \"za 1h\"\n (datetime 2013 2 12 5 30)\n\n \"za par", "end": 7086, "score": 0.9968333840370178, "start": 7077, "tag": "NAME", "value": "jedan sat" }, { "context": " sat\"\n \"za 1h\"\n (datetime 2013 2 12 5 30)\n\n \"za par sati\"\n (datetime 2013 2 12 6 30)\n\n \"za nekoliko s", "end": 7138, "score": 0.5480791926383972, "start": 7133, "tag": "NAME", "value": "par s" }, { "context": "h\"\n (datetime 2013 2 13 4 30)\n\n \"za 1 dan\"\n \"za jedan dan\"\n (datetime 2013 2 13 4)\n\n \"3 godine od danasnj", "end": 7305, "score": 0.998737633228302, "start": 7296, "tag": "NAME", "value": "jedan dan" }, { "context": ")\n\n \"za 7 dana\"\n (datetime 2013 2 19 4)\n\n \"za 1 tjedan\"\n (datetime 2013 2 19)\n\n \"za oko pola sata\" ;; ", "end": 7439, "score": 0.8822860717773438, "start": 7433, "tag": "NAME", "value": "tjedan" }, { "context": "\"prije 14 dana\"\n (datetime 2013 1 29 4)\n\n \"prije jedan tjedan\"\n \"prije jednog tjedna\"\n (datetime 2013 ", "end": 7671, "score": 0.8647684454917908, "start": 7666, "tag": "NAME", "value": "jedan" }, { "context": " 14 dana\"\n (datetime 2013 1 29 4)\n\n \"prije jedan tjedan\"\n \"prije jednog tjedna\"\n (datetime 2013 2 5)\n\n ", "end": 7678, "score": 0.8586723208427429, "start": 7672, "tag": "NAME", "value": "tjedan" }, { "context": "4)\n\n \"za 14 dana\"\n (datetime 2013 2 26 4)\n\n \"za jedan tjedan\"\n (datetime 2013 2 19)\n\n \"za tri tjedna\"", "end": 7983, "score": 0.8663430213928223, "start": 7978, "tag": "NAME", "value": "jedan" }, { "context": "\"za 14 dana\"\n (datetime 2013 2 26 4)\n\n \"za jedan tjedan\"\n (datetime 2013 2 19)\n\n \"za tri tjedna\"\n (dat", "end": 7990, "score": 0.8045718669891357, "start": 7984, "tag": "NAME", "value": "tjedan" }, { "context": " 1 1)\n\n \"valentinovo\"\n (datetime 2013 2 14)\n\n \"majcin dan\"\n (datetime 2013 5 12)\n\n \"dan oceva\"\n (datetim", "end": 8637, "score": 0.9995750784873962, "start": 8627, "tag": "NAME", "value": "majcin dan" }, { "context": " 2 14)\n\n \"majcin dan\"\n (datetime 2013 5 12)\n\n \"dan oceva\"\n (datetime 2013 6 16)\n\n \"noc vjestica\"\n (date", "end": 8675, "score": 0.7805256247520447, "start": 8666, "tag": "NAME", "value": "dan oceva" }, { "context": " 31)\n\n ; Part of day (morning, afternoon...)\n\n \"veceras\"\n \"ove veceri\"\n \"danas navecer\"\n (datetime-int", "end": 8794, "score": 0.8935031890869141, "start": 8787, "tag": "NAME", "value": "veceras" }, { "context": "ing, afternoon...)\n\n \"veceras\"\n \"ove veceri\"\n \"danas navecer\"\n (datetime-interval [2013 2 12 18] [2013 2 13 0", "end": 8827, "score": 0.998045802116394, "start": 8814, "tag": "NAME", "value": "danas navecer" }, { "context": "tetime-interval [2013 2 8 18] [2013 2 11 00])\n\n \"sutra navecer\"\n ;\"Wednesday evening\"\n (datetime-interval [201", "end": 8968, "score": 0.9975132942199707, "start": 8955, "tag": "NAME", "value": "sutra navecer" }, { "context": "etime-interval [2013 2 13 18] [2013 2 14 00])\n\n \"sutra rucak\"\n (datetime-interval [2013 2 13 12] [2013 2 13 1", "end": 9060, "score": 0.9922499656677246, "start": 9049, "tag": "NAME", "value": "sutra rucak" }, { "context": "etime-interval [2013 2 13 12] [2013 2 13 14])\n\n \"jucer navecer\"\n \"prethodne veceri\"\n (datetime-interval [2013 ", "end": 9131, "score": 0.9954856038093567, "start": 9118, "tag": "NAME", "value": "jucer navecer" }, { "context": "13 2 13 12] [2013 2 13 14])\n\n \"jucer navecer\"\n \"prethodne veceri\"\n (datetime-interval [2013 2 11 18]", "end": 9139, "score": 0.6271098852157593, "start": 9136, "tag": "NAME", "value": "pre" }, { "context": "a 15 minuta\"\n (datetime 2013 2 12 4 45 0)\n\n \"poslije rucka\"\n (datetime-interval [2013 2 12 13] [2013 2 12 1", "end": 13630, "score": 0.648158848285675, "start": 13620, "tag": "NAME", "value": "lije rucka" }, { "context": "17])\n\n \"10:30\"\n (datetime 2013 2 12 10 30)\n\n \"jutro\" ;; how should we deal with fb mornings?\n (datet", "end": 13733, "score": 0.5026648640632629, "start": 13729, "tag": "NAME", "value": "utro" }, { "context": "tetime-interval [2013 2 12 4] [2013 2 12 12])\n\n \"sljedeci ponedjeljak\"\n (datetime 2013 2 18 :day-of-week 1)\n\n \"u 12\"\n", "end": 13850, "score": 0.969018816947937, "start": 13830, "tag": "NAME", "value": "sljedeci ponedjeljak" }, { "context": "noci\"\n \"u ponoc\"\n (datetime 2013 2 13 0)\n\n \"ozujak\"\n \"u ozujku\"\n (datetime 2013 3))\n", "end": 14002, "score": 0.5634973645210266, "start": 13999, "tag": "NAME", "value": "jak" } ]
resources/languages/hr/corpus/time.clj
ksseono/duckling
922
(; Context map ; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests {:reference-time (time/t -2 2013 2 12 4 30 0) :min (time/t -2 1900) :max (time/t -2 2100)} "sad" "sada" "upravo sad" "ovaj tren" (datetime 2013 2 12 4 30 00) "danas" (datetime 2013 2 12) "jucer" "jučer" (datetime 2013 2 11) "sutra" (datetime 2013 2 13) "ponedjeljak" "pon." "ovaj ponedjeljak" (datetime 2013 2 18 :day-of-week 1) "ponedjeljak, 18. veljace" "ponedjeljak, 18. veljače" (datetime 2013 2 18 :day-of-week 1 :day 18 :month 2) "utorak" "utorak 19." (datetime 2013 2 19) "cetvrtak" "četvrtak" "čet" "cet." (datetime 2013 2 14) "petak" "pet" "pet." (datetime 2013 2 15) "subota" "sub" "sub." (datetime 2013 2 16) "nedjelja" "ned" "ned." (datetime 2013 2 17) "1. ozujak" "1. ožujak" "prvi ozujka" (datetime 2013 3 1 :day 1 :month 3) "treci ozujka" "treci ožujka" (datetime 2013 3 3 :day 3 :month 3) ; "martovske ide" ; (datetime 2013 3 15 :month 3) "3. ozujka 2015" "treci ozujka 2015" "3/3/2015" "3/3/15" "2015-3-3" "2015-03-03" (datetime 2015 3 3 :day 3 :month 3 :year 2015) "15ti drugi" (datetime 2013 2 15 :day 15) "15. veljace" "15. veljače" "15/02" (datetime 2013 2 15 :day 15 :month 2) "8. kolovoza" "8. kolovoz" (datetime 2013 8 8 :day 8 :month 8) "listopad 2014" (datetime 2014 10 :year 2014 :month 10) "31/10/1974" "31/10/74" "74-10-31" (datetime 1974 10 31 :day 31 :month 10 :year 1974) "14travanj 2015" "14. travnja, 2015" "14. travanj 15" (datetime 2015 4 14 :day 14 :month 4 :years 2015) "sljedeci utorak" "sljedeceg utorka" (datetime 2013 2 19 :day-of-week 2) "petak nakon sljedeceg" (datetime 2013 2 22 :day-of-week 2) "sljedeci ozujak" (datetime 2013 3) "ozujak nakon sljedeceg" (datetime 2014 3) "nedjelja, 10. veljace" "nedjelja, 10. veljače" (datetime 2013 2 10 :day-of-week 7 :day 10 :month 2) "Sri, 13. velj" (datetime 2013 2 13 :day-of-week 3 :day 13 :month 2) "ponedjeljak, veljaca 18." "Pon, 18. veljace" (datetime 2013 2 18 :day-of-week 1 :day 18 :month 2) ; ;; Cycles "ovaj tjedan" (datetime 2013 2 11 :grain :week) "prosli tjedan" "prošli tjedan" "prethodni tjedan" (datetime 2013 2 4 :grain :week) "sljedeci tjedan" (datetime 2013 2 18 :grain :week) "prethodni mjesec" (datetime 2013 1) "sljedeci mjesec" (datetime 2013 3) "ovaj kvartal" "ovo tromjesecje" (datetime 2013 1 1 :grain :quarter) "sljedeci kvartal" (datetime 2013 4 1 :grain :quarter) "treci kvartal" "3. kvartal" "trece tromjesecje" "3. tromjesečje" (datetime 2013 7 1 :grain :quarter) "4. kvartal 2018" "četvrto tromjesečje 2018" (datetime 2018 10 1 :grain :quarter) "prošla godina" "prethodna godina" (datetime 2012) "ova godina" (datetime 2013) "sljedece godina" (datetime 2014) "prosle nedjelje" "prosli tjedan u nedjelju" (datetime 2013 2 10 :day-of-week 7) "prosli utorak" (datetime 2013 2 5 :day-of-week 2) "sljedeci utorak" ; when today is Tuesday, "mardi prochain" is a week from now (datetime 2013 2 19 :day-of-week 2) "sljedecu srijedu" ; when today is Tuesday, "mercredi prochain" is tomorrow (datetime 2013 2 13 :day-of-week 3) "sljedeci tjedan u srijedu" "srijeda sljedeci tjedan" (datetime 2013 2 20 :day-of-week 3) "sljedeci petak" (datetime 2013 2 15 :day-of-week 5) "ovaj tjedan u ponedjeljak" (datetime 2013 2 11 :day-of-week 1) "ovaj utorak" (datetime 2013 2 19 :day-of-week 2) "ova srijeda" "ovaj tjedan u srijedu" (datetime 2013 2 13 :day-of-week 3) "prekosutra" (datetime 2013 2 14) "prekosutra u 5 popodne" "prekosutra u 17" (datetime 2013 2 14 17) "prekjucer" "prekjučer" (datetime 2013 2 10) "prekjučer u 8" "prekjučer u 8 sati" (datetime 2013 2 10 8) "zadnji ponedjeljak u ozujku" (datetime 2013 3 25 :day-of-week 1) "zadnja nedjelja u ozujku 2014" (datetime 2014 3 30 :day-of-week 7) "treci dan u listopadu" (datetime 2013 10 3) "prvi tjedan u listopadu 2014" (datetime 2014 10 6 :grain :week) "zadnji dan u listopadu 2015" (datetime 2015 10 31) "zadnji tjedan u rujnu 2014" (datetime 2014 9 22 :grain :week) ;; nth of "prvi utorak u listopadu" (datetime 2013 10 1) "treci utorak u rujnu 2014" (datetime 2014 9 16) "prva srijeda u listopadu 2014" (datetime 2014 10 1) "druga srijeda u listopadu 2014" (datetime 2014 10 8) ;; nth after "treci utorak poslije Bozica 2014" (datetime 2015 1 13) ;; Hours "3 u noci" "u 3 ujutro" "u tri sata u noci" (datetime 2013 2 13 3) "3:18 rano" (datetime 2013 2 12 3 18) "u 3 poslijepodne" "@ 15" "15" "15 sati poslijepodne" (datetime 2013 2 12 15 :hour 3 :meridiem :pm) "oko 3 poslijepodne" ;; FIXME pm overrides precision "otprilike u 3 poslijepodne" "cca 3 poslijepodne" "cca 15" (datetime 2013 2 12 15 :hour 3 :meridiem :pm) ;; :precision "approximate" "15 i 15" "3:15 poslijepodne" "15:15" (datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm) "cetvrt nakon 3 poslijepodne" (datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm :grain :second) "3 i 20 popodne" "3:20 poslijepodne" "3:20 popodne" "dvadeset nakon 3 popodne" "15:20" (datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm) "tri i po popodne" "pola 4 popodne" "15:30" "pola cetiri popodne" (datetime 2013 2 12 15 30 :hour 3 :minute 30) "15:23:24" (datetime 2013 2 12 15 23 24 :hour 15 :minute 23 :second 24) "petnaest do podne" "11:45" "četvrt do podneva" ; Ambiguous with interval (datetime 2013 2 12 11 45 :hour 11 :minute 45) "8 navecer" "osam sati navecer" "danas 8 navecer" (datetime 2013 2 12 20) ;; Mixing date and time "u 7:30 popodne u pet, 20. rujna" (datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm) "9 ujutro u subotu" "u subotu u 9 sati ujutro" (datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am) "pet, srp 18., 2014, 19:00" "pet, srp 18., 2014 u 19:00" (datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm) ; TODO reported as not found even tough it passes ; "pet, srp 18., 2014, 19 sati 10 minuta" ; (datetime 2014 7 18 19 10 :day-of-week 5 :hour 7 :meridiem :pm) ; ;; Involving periods "za jednu sekundu" (datetime 2013 2 12 4 30 1) "za jednu minutu" (datetime 2013 2 12 4 31 0) "za 2 minute" "za jos 2 minute" "2 minute od sad" (datetime 2013 2 12 4 32 0) "za 60 minuta" (datetime 2013 2 12 5 30 0) "oko cetvrt sata" "oko 1/4h" "oko 1/4 h" "oko 1/4 sata" (datetime 2013 2 12 4 45 0) "za pola sata" "za pol sata" "za 1/2h" "za 1/2 h" "za 1/2 sata" (datetime 2013 2 12 5 0 0) "za tri-cetvrt sata" "za 3/4h" "za 3/4 h" "za 3/4 sata" (datetime 2013 2 12 5 15 0) ; TODO reported as not found, ; "za dva i pol sata" "za 2.5 sata" (datetime 2013 2 12 7 0 0) "za jedan sat" "za 1h" (datetime 2013 2 12 5 30) "za par sati" (datetime 2013 2 12 6 30) "za nekoliko sati" (datetime 2013 2 12 7 30) "za 24 sata" "za 24h" (datetime 2013 2 13 4 30) "za 1 dan" "za jedan dan" (datetime 2013 2 13 4) "3 godine od danasnjeg dana" (datetime 2016 2) "za 7 dana" (datetime 2013 2 19 4) "za 1 tjedan" (datetime 2013 2 19) "za oko pola sata" ;; FIXME precision is lost (datetime 2013 2 12 5 0 0) ;; :precision "approximate" "prije 7 dana" (datetime 2013 2 5 4) "prije 14 dana" (datetime 2013 1 29 4) "prije jedan tjedan" "prije jednog tjedna" (datetime 2013 2 5) "prije tri tjedna" (datetime 2013 1 22) "prije tri mjeseca" (datetime 2012 11 12) "prije dvije godine" (datetime 2011 2) "1954" (datetime 1954) "za 7 dana" (datetime 2013 2 19 4) "za 14 dana" (datetime 2013 2 26 4) "za jedan tjedan" (datetime 2013 2 19) "za tri tjedna" (datetime 2013 3 5) "za tri mjeseca" (datetime 2013 5 12) "za dvije godine" (datetime 2015 2) "jednu godinu poslije Bozica" (datetime 2013 12) ; resolves as after last Xmas... ; Seasons "ovog ljeta" "ovo ljeto" "ljetos" (datetime-interval [2013 6 21] [2013 9 24]) "ove zime" "zimus" (datetime-interval [2012 12 21] [2013 3 21]) ; US holidays (http://www.timeanddate.com/holidays/us/) "Bozic" "zicbo" (datetime 2013 12 25) "stara godina" (datetime 2013 12 31) "nova godina" (datetime 2014 1 1) "valentinovo" (datetime 2013 2 14) "majcin dan" (datetime 2013 5 12) "dan oceva" (datetime 2013 6 16) "noc vjestica" (datetime 2013 10 31) ; Part of day (morning, afternoon...) "veceras" "ove veceri" "danas navecer" (datetime-interval [2013 2 12 18] [2013 2 13 00]) "prosli vikend" (datetime-interval [2013 2 8 18] [2013 2 11 00]) "sutra navecer" ;"Wednesday evening" (datetime-interval [2013 2 13 18] [2013 2 14 00]) "sutra rucak" (datetime-interval [2013 2 13 12] [2013 2 13 14]) "jucer navecer" "prethodne veceri" (datetime-interval [2013 2 11 18] [2013 2 12 00]) "ovaj vikend" "ovog vikenda" (datetime-interval [2013 2 15 18] [2013 2 18 00]) "ponedjeljak ujutro" (datetime-interval [2013 2 18 4] [2013 2 18 12]) "ponedjeljak rano ujutro" "ponedjeljak rano" "ponedjeljak u rane jutarnje sate" (datetime-interval [2013 2 18 3] [2013 2 18 9]) "15. veljace ujutro" (datetime-interval [2013 2 15 4] [2013 2 15 12]) ; Intervals involving cycles "prosle 2 sekunde" "prethodne dvije sekunde" (datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00]) "sljedece 3 sekunde" "sljedece tri sekunde" (datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04]) "prosle 2 minute" "prethodne dvije minute" (datetime-interval [2013 2 12 4 28] [2013 2 12 4 30]) "sljedece 3 minute" "sljedece tri minute" (datetime-interval [2013 2 12 4 31] [2013 2 12 4 34]) "prethodni jedan sat" (datetime-interval [2013 2 12 3] [2013 2 12 4]) "prethodna 24 sata" "prethodna dvadeset i cetiri sata" "prethodna dvadeset i cetiri sata" "prethodna 24h" (datetime-interval [2013 2 11 4] [2013 2 12 4]) "sljedeca 3 sata" "sljedeca tri sata" (datetime-interval [2013 2 12 5] [2013 2 12 8]) "prethodna dva dana" "prethodna 2 dana" "prosla 2 dana" (datetime-interval [2013 2 10] [2013 2 12]) "sljedeca 3 dana" "sljedeca tri dana" (datetime-interval [2013 2 13] [2013 2 16]) "sljedecih nekoliko dana" (datetime-interval [2013 2 13] [2013 2 16]) "prethodna 2 tjedna" "prethodna dva tjedna" "prosla 2 tjedna" (datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week]) "sljedeca 3 tjedna" "sljedeca tri tjedna" (datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week]) "prethodna 2 mjeseca" "prethodna dva mjeseca" (datetime-interval [2012 12] [2013 02]) "sljedeca 3 mjeseca" "sljedeca tri mjeseca" (datetime-interval [2013 3] [2013 6]) "prethodne 2 godine" "prethodne dvije godine" (datetime-interval [2011] [2013]) "sljedece 3 godine" "sljedece tri godine" (datetime-interval [2014] [2017]) ; Explicit intervals "srpanj 13-15" "srpanj 13 do 15" "srpanj 13 - srpanj 15" (datetime-interval [2013 7 13] [2013 7 16]) "kol 8 - kol 12" (datetime-interval [2013 8 8] [2013 8 13]) "9:30 - 11:00" (datetime-interval [2013 2 12 9 30] [2013 2 12 11 1]) "od 9:30 - 11:00 u cetvrtak" "između 9:30 i 11:00 u cetvrtak" "9:30 - 11:00 u cetvrtak" "izmedju 9:30 i 11:00 u cetvrtak" "cetvrtak od 9:30 do 11:00" "od 9:30 do 11:00 u cetvrtak" "cetvrtak od 9:30 do 11:00" (datetime-interval [2013 2 14 9 30] [2013 2 14 11 1]) "cetvrtak od 9 do 11 ujutro" (datetime-interval [2013 2 14 9] [2013 2 14 12]) "11:30-1:30" ; go train this rule! "11:30-1:30" "11:30-1:30" "11:30-1:30" "11:30-1:30" "11:30-1:30" "11:30-1:30" (datetime-interval [2013 2 12 11 30] [2013 2 12 13 31]) "1:30 poslijepodne u sub, ruj 21." (datetime 2013 9 21 13 30) "sljedeca 2 tjedna" (datetime-interval [2013 2 18 :grain :week] [2013 3 4 :grain :week]) "do 2 poslijepodne" (datetime 2013 2 12 14 :direction :before) "do kraja ovog dana" (datetime-interval [2013 2 12 4 30 0] [2013 2 13 0]) "do kraja dana" (datetime 2013 2 13 0) "do kraja ovog mjeseca" (datetime-interval [2013 2 12 4 30 0] [2013 3 1 0]) "do kraja sljedeceg mjeseca" (datetime-interval [2013 2 12 4 30 0] [2013 4 1 0]) ; Timezones "4 poslijepodne CET" (datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET") "cetvrtak 8:00 GMT" (datetime 2013 2 14 8 00 :timezone "GMT") ;; Bookface tests "danas u 14" "u 2 poslijepodne" (datetime 2013 2 12 14) "25/4 U 16 sati" (datetime 2013 4 25 16) "15 sati sutra" (datetime 2013 2 13 15) ; winner is picked but has a different hash, strange ; Expected {:start #object[org.joda.time.DateTime 0x701d4ca1 "2013-02-12T14:00:00.000-02:00"], :grain :hour} ; Got {:start #object[org.joda.time.DateTime 0x78ce5efb "2013-02-12T14:00:00.000-02:00"], :grain :hour} ; "nakon 14 sati" ; "iza 14 sati" ; (datetime 2013 2 12 14 :direction :after) "nakon 5 dana" (datetime 2013 2 17 4 :direction :after) "prije 11" (datetime 2013 2 12 11 :direction :before) "poslijepodne" "popodne" (datetime-interval [2013 2 12 12] [2013 2 12 20]) "u 13:30" "13:30" (datetime 2013 2 12 13 30) "za 15 minuta" (datetime 2013 2 12 4 45 0) "poslije rucka" (datetime-interval [2013 2 12 13] [2013 2 12 17]) "10:30" (datetime 2013 2 12 10 30) "jutro" ;; how should we deal with fb mornings? (datetime-interval [2013 2 12 4] [2013 2 12 12]) "sljedeci ponedjeljak" (datetime 2013 2 18 :day-of-week 1) "u 12" "u podne" (datetime 2013 2 12 12) "u 12 u noci" "u ponoc" (datetime 2013 2 13 0) "ozujak" "u ozujku" (datetime 2013 3))
62374
(; Context map ; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests {:reference-time (time/t -2 2013 2 12 4 30 0) :min (time/t -2 1900) :max (time/t -2 2100)} "<NAME>" "sada" "upravo <NAME>" "ovaj t<NAME>" (datetime 2013 2 12 4 30 00) "<NAME>" (datetime 2013 2 12) "<NAME>" "<NAME>" (datetime 2013 2 11) "<NAME>" (datetime 2013 2 13) "<NAME>" "pon." "ov<NAME> p<NAME>" (datetime 2013 2 18 :day-of-week 1) "<NAME>, 18. vel<NAME>" "ponedjeljak, 18. veljače" (datetime 2013 2 18 :day-of-week 1 :day 18 :month 2) "<NAME>" "utorak 19." (datetime 2013 2 19) "<NAME>" "<NAME>" "<NAME>" "cet." (datetime 2013 2 14) "<NAME>" "pet" "pet." (datetime 2013 2 15) "<NAME>" "sub" "sub." (datetime 2013 2 16) "<NAME>" "<NAME>" "ned." (datetime 2013 2 17) "1. ozujak" "1. ožujak" "prvi ozujka" (datetime 2013 3 1 :day 1 :month 3) "treci ozujka" "treci ožujka" (datetime 2013 3 3 :day 3 :month 3) ; "marto<NAME> ide" ; (datetime 2013 3 15 :month 3) "3. ozujka 2015" "treci ozujka 2015" "3/3/2015" "3/3/15" "2015-3-3" "2015-03-03" (datetime 2015 3 3 :day 3 :month 3 :year 2015) "15ti drugi" (datetime 2013 2 15 :day 15) "15. veljace" "15. veljače" "15/02" (datetime 2013 2 15 :day 15 :month 2) "8. kolovoza" "8. kolovoz" (datetime 2013 8 8 :day 8 :month 8) "listopad 2014" (datetime 2014 10 :year 2014 :month 10) "31/10/1974" "31/10/74" "74-10-31" (datetime 1974 10 31 :day 31 :month 10 :year 1974) "14travanj 2015" "14. travnja, 2015" "14. travanj 15" (datetime 2015 4 14 :day 14 :month 4 :years 2015) "sljedeci utorak" "sljedeceg utorka" (datetime 2013 2 19 :day-of-week 2) "petak nakon sljedeceg" (datetime 2013 2 22 :day-of-week 2) "sljedeci ozujak" (datetime 2013 3) "ozujak nakon sljedeceg" (datetime 2014 3) "nedjelja, 10. veljace" "nedjelja, 10. veljače" (datetime 2013 2 10 :day-of-week 7 :day 10 :month 2) "Sri, 13. velj" (datetime 2013 2 13 :day-of-week 3 :day 13 :month 2) "ponedjeljak, veljaca 18." "Pon, 18. veljace" (datetime 2013 2 18 :day-of-week 1 :day 18 :month 2) ; ;; Cycles "ovaj tjedan" (datetime 2013 2 11 :grain :week) "prosli tjedan" "prošli tjedan" "prethodni tjedan" (datetime 2013 2 4 :grain :week) "sljedeci tjedan" (datetime 2013 2 18 :grain :week) "prethodni mjesec" (datetime 2013 1) "sljedeci mjesec" (datetime 2013 3) "ovaj kvartal" "ovo tromjesecje" (datetime 2013 1 1 :grain :quarter) "sljedeci kvartal" (datetime 2013 4 1 :grain :quarter) "treci kvartal" "3. kvartal" "trece tromjesecje" "3. tromjesečje" (datetime 2013 7 1 :grain :quarter) "4. kvartal 2018" "četvrto tromjesečje 2018" (datetime 2018 10 1 :grain :quarter) "prošla godina" "prethodna godina" (datetime 2012) "ova godina" (datetime 2013) "sljedece godina" (datetime 2014) "prosle nedjelje" "prosli tjedan u nedjelju" (datetime 2013 2 10 :day-of-week 7) "prosli utorak" (datetime 2013 2 5 :day-of-week 2) "sljedeci utorak" ; when today is Tuesday, "<NAME>" is a week from now (datetime 2013 2 19 :day-of-week 2) "sljedecu s<NAME>" ; when today is Tuesday, "mercredi prochain" is tomorrow (datetime 2013 2 13 :day-of-week 3) "sljedeci tjedan u <NAME>edu" "srijeda sljedeci tjedan" (datetime 2013 2 20 :day-of-week 3) "<NAME>ci <NAME>" (datetime 2013 2 15 :day-of-week 5) "ovaj tjedan u ponedjeljak" (datetime 2013 2 11 :day-of-week 1) "ovaj utorak" (datetime 2013 2 19 :day-of-week 2) "ova <NAME>" "ovaj tjedan u srijedu" (datetime 2013 2 13 :day-of-week 3) "prekosutra" (datetime 2013 2 14) "prekosutra u 5 popodne" "prekosutra u 17" (datetime 2013 2 14 17) "prekjucer" "prekjučer" (datetime 2013 2 10) "prekjučer u 8" "prekjučer u 8 sati" (datetime 2013 2 10 8) "zadnji ponedjeljak u ozujku" (datetime 2013 3 25 :day-of-week 1) "zadnja nedjelja u ozujku 2014" (datetime 2014 3 30 :day-of-week 7) "treci dan u listopadu" (datetime 2013 10 3) "prvi tjedan u listopadu 2014" (datetime 2014 10 6 :grain :week) "zadnji dan u listopadu 2015" (datetime 2015 10 31) "zadnji tjedan u rujnu 2014" (datetime 2014 9 22 :grain :week) ;; nth of "prvi utorak u listopadu" (datetime 2013 10 1) "treci utorak u rujnu 2014" (datetime 2014 9 16) "prva srijeda u listopadu 2014" (datetime 2014 10 1) "druga srijeda u listopadu 2014" (datetime 2014 10 8) ;; nth after "treci utorak poslije Bozica 2014" (datetime 2015 1 13) ;; Hours "3 u noci" "u 3 ujutro" "u tri sata u noci" (datetime 2013 2 13 3) "3:18 rano" (datetime 2013 2 12 3 18) "u 3 poslijepodne" "@ 15" "15" "15 sati poslijepodne" (datetime 2013 2 12 15 :hour 3 :meridiem :pm) "oko 3 poslijepodne" ;; FIXME pm overrides precision "otprilike u 3 poslijepodne" "cca 3 poslijepodne" "cca 15" (datetime 2013 2 12 15 :hour 3 :meridiem :pm) ;; :precision "approximate" "15 i 15" "3:15 poslijepodne" "15:15" (datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm) "cetvrt nakon 3 poslijepodne" (datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm :grain :second) "3 i 20 popodne" "3:20 poslijepodne" "3:20 popodne" "dvadeset nakon 3 popodne" "15:20" (datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm) "tri i po popodne" "pola 4 popodne" "15:30" "pola cetiri popodne" (datetime 2013 2 12 15 30 :hour 3 :minute 30) "15:23:24" (datetime 2013 2 12 15 23 24 :hour 15 :minute 23 :second 24) "petnaest do podne" "11:45" "četvrt do podneva" ; Ambiguous with interval (datetime 2013 2 12 11 45 :hour 11 :minute 45) "8 navecer" "osam sati navecer" "danas 8 navecer" (datetime 2013 2 12 20) ;; Mixing date and time "u 7:30 popodne u pet, 20. rujna" (datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm) "9 ujutro u subotu" "u subotu u 9 sati ujutro" (datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am) "pet, srp 18., 2014, 19:00" "pet, srp 18., 2014 u 19:00" (datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm) ; TODO reported as not found even tough it passes ; "pet, srp 18., 2014, 19 sati 10 minuta" ; (datetime 2014 7 18 19 10 :day-of-week 5 :hour 7 :meridiem :pm) ; ;; Involving periods "za jednu sekundu" (datetime 2013 2 12 4 30 1) "za jednu minutu" (datetime 2013 2 12 4 31 0) "za 2 minute" "za jos 2 minute" "2 minute od sad" (datetime 2013 2 12 4 32 0) "za 60 minuta" (datetime 2013 2 12 5 30 0) "oko cetvrt sata" "oko 1/4h" "oko 1/4 h" "oko 1/4 sata" (datetime 2013 2 12 4 45 0) "za pola sata" "za pol sata" "za 1/2h" "za 1/2 h" "za 1/2 sata" (datetime 2013 2 12 5 0 0) "za tri-cetvrt sata" "za 3/4h" "za 3/4 h" "za 3/4 sata" (datetime 2013 2 12 5 15 0) ; TODO reported as not found, ; "za dva i pol sata" "za 2.5 sata" (datetime 2013 2 12 7 0 0) "za <NAME>" "za 1h" (datetime 2013 2 12 5 30) "za <NAME>ati" (datetime 2013 2 12 6 30) "za nekoliko sati" (datetime 2013 2 12 7 30) "za 24 sata" "za 24h" (datetime 2013 2 13 4 30) "za 1 dan" "za <NAME>" (datetime 2013 2 13 4) "3 godine od danasnjeg dana" (datetime 2016 2) "za 7 dana" (datetime 2013 2 19 4) "za 1 <NAME>" (datetime 2013 2 19) "za oko pola sata" ;; FIXME precision is lost (datetime 2013 2 12 5 0 0) ;; :precision "approximate" "prije 7 dana" (datetime 2013 2 5 4) "prije 14 dana" (datetime 2013 1 29 4) "prije <NAME> <NAME>" "prije jednog tjedna" (datetime 2013 2 5) "prije tri tjedna" (datetime 2013 1 22) "prije tri mjeseca" (datetime 2012 11 12) "prije dvije godine" (datetime 2011 2) "1954" (datetime 1954) "za 7 dana" (datetime 2013 2 19 4) "za 14 dana" (datetime 2013 2 26 4) "za <NAME> <NAME>" (datetime 2013 2 19) "za tri tjedna" (datetime 2013 3 5) "za tri mjeseca" (datetime 2013 5 12) "za dvije godine" (datetime 2015 2) "jednu godinu poslije Bozica" (datetime 2013 12) ; resolves as after last Xmas... ; Seasons "ovog ljeta" "ovo ljeto" "ljetos" (datetime-interval [2013 6 21] [2013 9 24]) "ove zime" "zimus" (datetime-interval [2012 12 21] [2013 3 21]) ; US holidays (http://www.timeanddate.com/holidays/us/) "Bozic" "zicbo" (datetime 2013 12 25) "stara godina" (datetime 2013 12 31) "nova godina" (datetime 2014 1 1) "valentinovo" (datetime 2013 2 14) "<NAME>" (datetime 2013 5 12) "<NAME>" (datetime 2013 6 16) "noc vjestica" (datetime 2013 10 31) ; Part of day (morning, afternoon...) "<NAME>" "ove veceri" "<NAME>" (datetime-interval [2013 2 12 18] [2013 2 13 00]) "prosli vikend" (datetime-interval [2013 2 8 18] [2013 2 11 00]) "<NAME>" ;"Wednesday evening" (datetime-interval [2013 2 13 18] [2013 2 14 00]) "<NAME>" (datetime-interval [2013 2 13 12] [2013 2 13 14]) "<NAME>" "<NAME>thodne veceri" (datetime-interval [2013 2 11 18] [2013 2 12 00]) "ovaj vikend" "ovog vikenda" (datetime-interval [2013 2 15 18] [2013 2 18 00]) "ponedjeljak ujutro" (datetime-interval [2013 2 18 4] [2013 2 18 12]) "ponedjeljak rano ujutro" "ponedjeljak rano" "ponedjeljak u rane jutarnje sate" (datetime-interval [2013 2 18 3] [2013 2 18 9]) "15. veljace ujutro" (datetime-interval [2013 2 15 4] [2013 2 15 12]) ; Intervals involving cycles "prosle 2 sekunde" "prethodne dvije sekunde" (datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00]) "sljedece 3 sekunde" "sljedece tri sekunde" (datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04]) "prosle 2 minute" "prethodne dvije minute" (datetime-interval [2013 2 12 4 28] [2013 2 12 4 30]) "sljedece 3 minute" "sljedece tri minute" (datetime-interval [2013 2 12 4 31] [2013 2 12 4 34]) "prethodni jedan sat" (datetime-interval [2013 2 12 3] [2013 2 12 4]) "prethodna 24 sata" "prethodna dvadeset i cetiri sata" "prethodna dvadeset i cetiri sata" "prethodna 24h" (datetime-interval [2013 2 11 4] [2013 2 12 4]) "sljedeca 3 sata" "sljedeca tri sata" (datetime-interval [2013 2 12 5] [2013 2 12 8]) "prethodna dva dana" "prethodna 2 dana" "prosla 2 dana" (datetime-interval [2013 2 10] [2013 2 12]) "sljedeca 3 dana" "sljedeca tri dana" (datetime-interval [2013 2 13] [2013 2 16]) "sljedecih nekoliko dana" (datetime-interval [2013 2 13] [2013 2 16]) "prethodna 2 tjedna" "prethodna dva tjedna" "prosla 2 tjedna" (datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week]) "sljedeca 3 tjedna" "sljedeca tri tjedna" (datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week]) "prethodna 2 mjeseca" "prethodna dva mjeseca" (datetime-interval [2012 12] [2013 02]) "sljedeca 3 mjeseca" "sljedeca tri mjeseca" (datetime-interval [2013 3] [2013 6]) "prethodne 2 godine" "prethodne dvije godine" (datetime-interval [2011] [2013]) "sljedece 3 godine" "sljedece tri godine" (datetime-interval [2014] [2017]) ; Explicit intervals "srpanj 13-15" "srpanj 13 do 15" "srpanj 13 - srpanj 15" (datetime-interval [2013 7 13] [2013 7 16]) "kol 8 - kol 12" (datetime-interval [2013 8 8] [2013 8 13]) "9:30 - 11:00" (datetime-interval [2013 2 12 9 30] [2013 2 12 11 1]) "od 9:30 - 11:00 u cetvrtak" "između 9:30 i 11:00 u cetvrtak" "9:30 - 11:00 u cetvrtak" "izmedju 9:30 i 11:00 u cetvrtak" "cetvrtak od 9:30 do 11:00" "od 9:30 do 11:00 u cetvrtak" "cetvrtak od 9:30 do 11:00" (datetime-interval [2013 2 14 9 30] [2013 2 14 11 1]) "cetvrtak od 9 do 11 ujutro" (datetime-interval [2013 2 14 9] [2013 2 14 12]) "11:30-1:30" ; go train this rule! "11:30-1:30" "11:30-1:30" "11:30-1:30" "11:30-1:30" "11:30-1:30" "11:30-1:30" (datetime-interval [2013 2 12 11 30] [2013 2 12 13 31]) "1:30 poslijepodne u sub, ruj 21." (datetime 2013 9 21 13 30) "sljedeca 2 tjedna" (datetime-interval [2013 2 18 :grain :week] [2013 3 4 :grain :week]) "do 2 poslijepodne" (datetime 2013 2 12 14 :direction :before) "do kraja ovog dana" (datetime-interval [2013 2 12 4 30 0] [2013 2 13 0]) "do kraja dana" (datetime 2013 2 13 0) "do kraja ovog mjeseca" (datetime-interval [2013 2 12 4 30 0] [2013 3 1 0]) "do kraja sljedeceg mjeseca" (datetime-interval [2013 2 12 4 30 0] [2013 4 1 0]) ; Timezones "4 poslijepodne CET" (datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET") "cetvrtak 8:00 GMT" (datetime 2013 2 14 8 00 :timezone "GMT") ;; Bookface tests "danas u 14" "u 2 poslijepodne" (datetime 2013 2 12 14) "25/4 U 16 sati" (datetime 2013 4 25 16) "15 sati sutra" (datetime 2013 2 13 15) ; winner is picked but has a different hash, strange ; Expected {:start #object[org.joda.time.DateTime 0x701d4ca1 "2013-02-12T14:00:00.000-02:00"], :grain :hour} ; Got {:start #object[org.joda.time.DateTime 0x78ce5efb "2013-02-12T14:00:00.000-02:00"], :grain :hour} ; "nakon 14 sati" ; "iza 14 sati" ; (datetime 2013 2 12 14 :direction :after) "nakon 5 dana" (datetime 2013 2 17 4 :direction :after) "prije 11" (datetime 2013 2 12 11 :direction :before) "poslijepodne" "popodne" (datetime-interval [2013 2 12 12] [2013 2 12 20]) "u 13:30" "13:30" (datetime 2013 2 12 13 30) "za 15 minuta" (datetime 2013 2 12 4 45 0) "pos<NAME>" (datetime-interval [2013 2 12 13] [2013 2 12 17]) "10:30" (datetime 2013 2 12 10 30) "j<NAME>" ;; how should we deal with fb mornings? (datetime-interval [2013 2 12 4] [2013 2 12 12]) "<NAME>" (datetime 2013 2 18 :day-of-week 1) "u 12" "u podne" (datetime 2013 2 12 12) "u 12 u noci" "u ponoc" (datetime 2013 2 13 0) "ozu<NAME>" "u ozujku" (datetime 2013 3))
true
(; Context map ; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests {:reference-time (time/t -2 2013 2 12 4 30 0) :min (time/t -2 1900) :max (time/t -2 2100)} "PI:NAME:<NAME>END_PI" "sada" "upravo PI:NAME:<NAME>END_PI" "ovaj tPI:NAME:<NAME>END_PI" (datetime 2013 2 12 4 30 00) "PI:NAME:<NAME>END_PI" (datetime 2013 2 12) "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" (datetime 2013 2 11) "PI:NAME:<NAME>END_PI" (datetime 2013 2 13) "PI:NAME:<NAME>END_PI" "pon." "ovPI:NAME:<NAME>END_PI pPI:NAME:<NAME>END_PI" (datetime 2013 2 18 :day-of-week 1) "PI:NAME:<NAME>END_PI, 18. velPI:NAME:<NAME>END_PI" "ponedjeljak, 18. veljače" (datetime 2013 2 18 :day-of-week 1 :day 18 :month 2) "PI:NAME:<NAME>END_PI" "utorak 19." (datetime 2013 2 19) "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "cet." (datetime 2013 2 14) "PI:NAME:<NAME>END_PI" "pet" "pet." (datetime 2013 2 15) "PI:NAME:<NAME>END_PI" "sub" "sub." (datetime 2013 2 16) "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "ned." (datetime 2013 2 17) "1. ozujak" "1. ožujak" "prvi ozujka" (datetime 2013 3 1 :day 1 :month 3) "treci ozujka" "treci ožujka" (datetime 2013 3 3 :day 3 :month 3) ; "martoPI:NAME:<NAME>END_PI ide" ; (datetime 2013 3 15 :month 3) "3. ozujka 2015" "treci ozujka 2015" "3/3/2015" "3/3/15" "2015-3-3" "2015-03-03" (datetime 2015 3 3 :day 3 :month 3 :year 2015) "15ti drugi" (datetime 2013 2 15 :day 15) "15. veljace" "15. veljače" "15/02" (datetime 2013 2 15 :day 15 :month 2) "8. kolovoza" "8. kolovoz" (datetime 2013 8 8 :day 8 :month 8) "listopad 2014" (datetime 2014 10 :year 2014 :month 10) "31/10/1974" "31/10/74" "74-10-31" (datetime 1974 10 31 :day 31 :month 10 :year 1974) "14travanj 2015" "14. travnja, 2015" "14. travanj 15" (datetime 2015 4 14 :day 14 :month 4 :years 2015) "sljedeci utorak" "sljedeceg utorka" (datetime 2013 2 19 :day-of-week 2) "petak nakon sljedeceg" (datetime 2013 2 22 :day-of-week 2) "sljedeci ozujak" (datetime 2013 3) "ozujak nakon sljedeceg" (datetime 2014 3) "nedjelja, 10. veljace" "nedjelja, 10. veljače" (datetime 2013 2 10 :day-of-week 7 :day 10 :month 2) "Sri, 13. velj" (datetime 2013 2 13 :day-of-week 3 :day 13 :month 2) "ponedjeljak, veljaca 18." "Pon, 18. veljace" (datetime 2013 2 18 :day-of-week 1 :day 18 :month 2) ; ;; Cycles "ovaj tjedan" (datetime 2013 2 11 :grain :week) "prosli tjedan" "prošli tjedan" "prethodni tjedan" (datetime 2013 2 4 :grain :week) "sljedeci tjedan" (datetime 2013 2 18 :grain :week) "prethodni mjesec" (datetime 2013 1) "sljedeci mjesec" (datetime 2013 3) "ovaj kvartal" "ovo tromjesecje" (datetime 2013 1 1 :grain :quarter) "sljedeci kvartal" (datetime 2013 4 1 :grain :quarter) "treci kvartal" "3. kvartal" "trece tromjesecje" "3. tromjesečje" (datetime 2013 7 1 :grain :quarter) "4. kvartal 2018" "četvrto tromjesečje 2018" (datetime 2018 10 1 :grain :quarter) "prošla godina" "prethodna godina" (datetime 2012) "ova godina" (datetime 2013) "sljedece godina" (datetime 2014) "prosle nedjelje" "prosli tjedan u nedjelju" (datetime 2013 2 10 :day-of-week 7) "prosli utorak" (datetime 2013 2 5 :day-of-week 2) "sljedeci utorak" ; when today is Tuesday, "PI:NAME:<NAME>END_PI" is a week from now (datetime 2013 2 19 :day-of-week 2) "sljedecu sPI:NAME:<NAME>END_PI" ; when today is Tuesday, "mercredi prochain" is tomorrow (datetime 2013 2 13 :day-of-week 3) "sljedeci tjedan u PI:NAME:<NAME>END_PIedu" "srijeda sljedeci tjedan" (datetime 2013 2 20 :day-of-week 3) "PI:NAME:<NAME>END_PIci PI:NAME:<NAME>END_PI" (datetime 2013 2 15 :day-of-week 5) "ovaj tjedan u ponedjeljak" (datetime 2013 2 11 :day-of-week 1) "ovaj utorak" (datetime 2013 2 19 :day-of-week 2) "ova PI:NAME:<NAME>END_PI" "ovaj tjedan u srijedu" (datetime 2013 2 13 :day-of-week 3) "prekosutra" (datetime 2013 2 14) "prekosutra u 5 popodne" "prekosutra u 17" (datetime 2013 2 14 17) "prekjucer" "prekjučer" (datetime 2013 2 10) "prekjučer u 8" "prekjučer u 8 sati" (datetime 2013 2 10 8) "zadnji ponedjeljak u ozujku" (datetime 2013 3 25 :day-of-week 1) "zadnja nedjelja u ozujku 2014" (datetime 2014 3 30 :day-of-week 7) "treci dan u listopadu" (datetime 2013 10 3) "prvi tjedan u listopadu 2014" (datetime 2014 10 6 :grain :week) "zadnji dan u listopadu 2015" (datetime 2015 10 31) "zadnji tjedan u rujnu 2014" (datetime 2014 9 22 :grain :week) ;; nth of "prvi utorak u listopadu" (datetime 2013 10 1) "treci utorak u rujnu 2014" (datetime 2014 9 16) "prva srijeda u listopadu 2014" (datetime 2014 10 1) "druga srijeda u listopadu 2014" (datetime 2014 10 8) ;; nth after "treci utorak poslije Bozica 2014" (datetime 2015 1 13) ;; Hours "3 u noci" "u 3 ujutro" "u tri sata u noci" (datetime 2013 2 13 3) "3:18 rano" (datetime 2013 2 12 3 18) "u 3 poslijepodne" "@ 15" "15" "15 sati poslijepodne" (datetime 2013 2 12 15 :hour 3 :meridiem :pm) "oko 3 poslijepodne" ;; FIXME pm overrides precision "otprilike u 3 poslijepodne" "cca 3 poslijepodne" "cca 15" (datetime 2013 2 12 15 :hour 3 :meridiem :pm) ;; :precision "approximate" "15 i 15" "3:15 poslijepodne" "15:15" (datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm) "cetvrt nakon 3 poslijepodne" (datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm :grain :second) "3 i 20 popodne" "3:20 poslijepodne" "3:20 popodne" "dvadeset nakon 3 popodne" "15:20" (datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm) "tri i po popodne" "pola 4 popodne" "15:30" "pola cetiri popodne" (datetime 2013 2 12 15 30 :hour 3 :minute 30) "15:23:24" (datetime 2013 2 12 15 23 24 :hour 15 :minute 23 :second 24) "petnaest do podne" "11:45" "četvrt do podneva" ; Ambiguous with interval (datetime 2013 2 12 11 45 :hour 11 :minute 45) "8 navecer" "osam sati navecer" "danas 8 navecer" (datetime 2013 2 12 20) ;; Mixing date and time "u 7:30 popodne u pet, 20. rujna" (datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm) "9 ujutro u subotu" "u subotu u 9 sati ujutro" (datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am) "pet, srp 18., 2014, 19:00" "pet, srp 18., 2014 u 19:00" (datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm) ; TODO reported as not found even tough it passes ; "pet, srp 18., 2014, 19 sati 10 minuta" ; (datetime 2014 7 18 19 10 :day-of-week 5 :hour 7 :meridiem :pm) ; ;; Involving periods "za jednu sekundu" (datetime 2013 2 12 4 30 1) "za jednu minutu" (datetime 2013 2 12 4 31 0) "za 2 minute" "za jos 2 minute" "2 minute od sad" (datetime 2013 2 12 4 32 0) "za 60 minuta" (datetime 2013 2 12 5 30 0) "oko cetvrt sata" "oko 1/4h" "oko 1/4 h" "oko 1/4 sata" (datetime 2013 2 12 4 45 0) "za pola sata" "za pol sata" "za 1/2h" "za 1/2 h" "za 1/2 sata" (datetime 2013 2 12 5 0 0) "za tri-cetvrt sata" "za 3/4h" "za 3/4 h" "za 3/4 sata" (datetime 2013 2 12 5 15 0) ; TODO reported as not found, ; "za dva i pol sata" "za 2.5 sata" (datetime 2013 2 12 7 0 0) "za PI:NAME:<NAME>END_PI" "za 1h" (datetime 2013 2 12 5 30) "za PI:NAME:<NAME>END_PIati" (datetime 2013 2 12 6 30) "za nekoliko sati" (datetime 2013 2 12 7 30) "za 24 sata" "za 24h" (datetime 2013 2 13 4 30) "za 1 dan" "za PI:NAME:<NAME>END_PI" (datetime 2013 2 13 4) "3 godine od danasnjeg dana" (datetime 2016 2) "za 7 dana" (datetime 2013 2 19 4) "za 1 PI:NAME:<NAME>END_PI" (datetime 2013 2 19) "za oko pola sata" ;; FIXME precision is lost (datetime 2013 2 12 5 0 0) ;; :precision "approximate" "prije 7 dana" (datetime 2013 2 5 4) "prije 14 dana" (datetime 2013 1 29 4) "prije PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" "prije jednog tjedna" (datetime 2013 2 5) "prije tri tjedna" (datetime 2013 1 22) "prije tri mjeseca" (datetime 2012 11 12) "prije dvije godine" (datetime 2011 2) "1954" (datetime 1954) "za 7 dana" (datetime 2013 2 19 4) "za 14 dana" (datetime 2013 2 26 4) "za PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" (datetime 2013 2 19) "za tri tjedna" (datetime 2013 3 5) "za tri mjeseca" (datetime 2013 5 12) "za dvije godine" (datetime 2015 2) "jednu godinu poslije Bozica" (datetime 2013 12) ; resolves as after last Xmas... ; Seasons "ovog ljeta" "ovo ljeto" "ljetos" (datetime-interval [2013 6 21] [2013 9 24]) "ove zime" "zimus" (datetime-interval [2012 12 21] [2013 3 21]) ; US holidays (http://www.timeanddate.com/holidays/us/) "Bozic" "zicbo" (datetime 2013 12 25) "stara godina" (datetime 2013 12 31) "nova godina" (datetime 2014 1 1) "valentinovo" (datetime 2013 2 14) "PI:NAME:<NAME>END_PI" (datetime 2013 5 12) "PI:NAME:<NAME>END_PI" (datetime 2013 6 16) "noc vjestica" (datetime 2013 10 31) ; Part of day (morning, afternoon...) "PI:NAME:<NAME>END_PI" "ove veceri" "PI:NAME:<NAME>END_PI" (datetime-interval [2013 2 12 18] [2013 2 13 00]) "prosli vikend" (datetime-interval [2013 2 8 18] [2013 2 11 00]) "PI:NAME:<NAME>END_PI" ;"Wednesday evening" (datetime-interval [2013 2 13 18] [2013 2 14 00]) "PI:NAME:<NAME>END_PI" (datetime-interval [2013 2 13 12] [2013 2 13 14]) "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PIthodne veceri" (datetime-interval [2013 2 11 18] [2013 2 12 00]) "ovaj vikend" "ovog vikenda" (datetime-interval [2013 2 15 18] [2013 2 18 00]) "ponedjeljak ujutro" (datetime-interval [2013 2 18 4] [2013 2 18 12]) "ponedjeljak rano ujutro" "ponedjeljak rano" "ponedjeljak u rane jutarnje sate" (datetime-interval [2013 2 18 3] [2013 2 18 9]) "15. veljace ujutro" (datetime-interval [2013 2 15 4] [2013 2 15 12]) ; Intervals involving cycles "prosle 2 sekunde" "prethodne dvije sekunde" (datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00]) "sljedece 3 sekunde" "sljedece tri sekunde" (datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04]) "prosle 2 minute" "prethodne dvije minute" (datetime-interval [2013 2 12 4 28] [2013 2 12 4 30]) "sljedece 3 minute" "sljedece tri minute" (datetime-interval [2013 2 12 4 31] [2013 2 12 4 34]) "prethodni jedan sat" (datetime-interval [2013 2 12 3] [2013 2 12 4]) "prethodna 24 sata" "prethodna dvadeset i cetiri sata" "prethodna dvadeset i cetiri sata" "prethodna 24h" (datetime-interval [2013 2 11 4] [2013 2 12 4]) "sljedeca 3 sata" "sljedeca tri sata" (datetime-interval [2013 2 12 5] [2013 2 12 8]) "prethodna dva dana" "prethodna 2 dana" "prosla 2 dana" (datetime-interval [2013 2 10] [2013 2 12]) "sljedeca 3 dana" "sljedeca tri dana" (datetime-interval [2013 2 13] [2013 2 16]) "sljedecih nekoliko dana" (datetime-interval [2013 2 13] [2013 2 16]) "prethodna 2 tjedna" "prethodna dva tjedna" "prosla 2 tjedna" (datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week]) "sljedeca 3 tjedna" "sljedeca tri tjedna" (datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week]) "prethodna 2 mjeseca" "prethodna dva mjeseca" (datetime-interval [2012 12] [2013 02]) "sljedeca 3 mjeseca" "sljedeca tri mjeseca" (datetime-interval [2013 3] [2013 6]) "prethodne 2 godine" "prethodne dvije godine" (datetime-interval [2011] [2013]) "sljedece 3 godine" "sljedece tri godine" (datetime-interval [2014] [2017]) ; Explicit intervals "srpanj 13-15" "srpanj 13 do 15" "srpanj 13 - srpanj 15" (datetime-interval [2013 7 13] [2013 7 16]) "kol 8 - kol 12" (datetime-interval [2013 8 8] [2013 8 13]) "9:30 - 11:00" (datetime-interval [2013 2 12 9 30] [2013 2 12 11 1]) "od 9:30 - 11:00 u cetvrtak" "između 9:30 i 11:00 u cetvrtak" "9:30 - 11:00 u cetvrtak" "izmedju 9:30 i 11:00 u cetvrtak" "cetvrtak od 9:30 do 11:00" "od 9:30 do 11:00 u cetvrtak" "cetvrtak od 9:30 do 11:00" (datetime-interval [2013 2 14 9 30] [2013 2 14 11 1]) "cetvrtak od 9 do 11 ujutro" (datetime-interval [2013 2 14 9] [2013 2 14 12]) "11:30-1:30" ; go train this rule! "11:30-1:30" "11:30-1:30" "11:30-1:30" "11:30-1:30" "11:30-1:30" "11:30-1:30" (datetime-interval [2013 2 12 11 30] [2013 2 12 13 31]) "1:30 poslijepodne u sub, ruj 21." (datetime 2013 9 21 13 30) "sljedeca 2 tjedna" (datetime-interval [2013 2 18 :grain :week] [2013 3 4 :grain :week]) "do 2 poslijepodne" (datetime 2013 2 12 14 :direction :before) "do kraja ovog dana" (datetime-interval [2013 2 12 4 30 0] [2013 2 13 0]) "do kraja dana" (datetime 2013 2 13 0) "do kraja ovog mjeseca" (datetime-interval [2013 2 12 4 30 0] [2013 3 1 0]) "do kraja sljedeceg mjeseca" (datetime-interval [2013 2 12 4 30 0] [2013 4 1 0]) ; Timezones "4 poslijepodne CET" (datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET") "cetvrtak 8:00 GMT" (datetime 2013 2 14 8 00 :timezone "GMT") ;; Bookface tests "danas u 14" "u 2 poslijepodne" (datetime 2013 2 12 14) "25/4 U 16 sati" (datetime 2013 4 25 16) "15 sati sutra" (datetime 2013 2 13 15) ; winner is picked but has a different hash, strange ; Expected {:start #object[org.joda.time.DateTime 0x701d4ca1 "2013-02-12T14:00:00.000-02:00"], :grain :hour} ; Got {:start #object[org.joda.time.DateTime 0x78ce5efb "2013-02-12T14:00:00.000-02:00"], :grain :hour} ; "nakon 14 sati" ; "iza 14 sati" ; (datetime 2013 2 12 14 :direction :after) "nakon 5 dana" (datetime 2013 2 17 4 :direction :after) "prije 11" (datetime 2013 2 12 11 :direction :before) "poslijepodne" "popodne" (datetime-interval [2013 2 12 12] [2013 2 12 20]) "u 13:30" "13:30" (datetime 2013 2 12 13 30) "za 15 minuta" (datetime 2013 2 12 4 45 0) "posPI:NAME:<NAME>END_PI" (datetime-interval [2013 2 12 13] [2013 2 12 17]) "10:30" (datetime 2013 2 12 10 30) "jPI:NAME:<NAME>END_PI" ;; how should we deal with fb mornings? (datetime-interval [2013 2 12 4] [2013 2 12 12]) "PI:NAME:<NAME>END_PI" (datetime 2013 2 18 :day-of-week 1) "u 12" "u podne" (datetime 2013 2 12 12) "u 12 u noci" "u ponoc" (datetime 2013 2 13 0) "ozuPI:NAME:<NAME>END_PI" "u ozujku" (datetime 2013 3))
[ { "context": "29 2465 2821 6601])\n\n(deftest ex27-test\n (doseq [carmichael carmichael-numbers]\n (is (ch1/fast-prime? carm", "end": 25888, "score": 0.7232185006141663, "start": 25878, "tag": "NAME", "value": "carmichael" }, { "context": "ime? carmichael))))\n\n(deftest ex28-test\n (doseq [carmichael carmichael-numbers]\n (is (not (ch1/mill", "end": 26022, "score": 0.7584578394889832, "start": 26019, "tag": "NAME", "value": "car" } ]
test/sicp/ch1_test.clj
robert-mitchell/SICP
0
(ns sicp.ch1-test (:require [clojure.test :refer [deftest is testing]] [sicp.ch1 :as ch1])) (deftest ex1-test (is (= 10 10)) (is (= 12 (+ 5 3 4))) (is (= 8 (- 9 1))) (is (= 3 (/ 6 2))) (is (= 6 (+ (* 2 4) (- 4 6)))) (let [a 3 b (+ a 1)] (is (= 3 a)) (is (= 4 b)) (is (= 19 (+ a b (* a b)))) (is (= 4 (if (and (> b a) (< b (* a b))) b a))) (is (= 16 (cond (= a 4) 6 (= b 4) (+ 6 7 a) :else 25))) (is (= 6 (+ 2 (if (> b a) b a)))) (is (= 16 (* (cond (> a b) a (< a b) b :else -1) (+ a 1)))))) (deftest ex2-test (is (= -37/150 (/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5))))) (* 3 (- 6 2) (- 2 7)))))) (deftest ex3-test (testing "sum-larger-squares" (is (= 5 (ch1/sum-larger-squares 1 2 0))) (is (= 5 (ch1/sum-larger-squares 1 0 2))) (is (= 5 (ch1/sum-larger-squares 0 2 1))))) (deftest ex4-test (testing "a+abs-b" (is (= 11 (ch1/a+abs-b 5 6))) (is (= 11 (ch1/a+abs-b 5 -6))))) (comment ;; ex5-test ; invoking (test 0 (p)) "Invocations of (ch1/test 0 (ch1/p)) will never" " terminate, as long as test is a normal function;" " i.e. it uses applicative order evaluation, which" " will attempt to evaluate the infinitely recursive" " definition of p." " If test is a macro, i.e. it uses normal order" " evaluation, then it will not evaluate p until it" " needs the value, so 0 will be returned.") (comment ;; ex6-test : sqrt-iter using new-if "new-if is a function, not a macro, so its arguments are" " evaluated before it is invoked (applicative order)." " Consequently, the sqrt-iter function will loop forever," " as each invocation of new-if in sqrt-iter will result" " in another sqrt-iter call. This will stack overflow," " since the function is not tail recursive.") (deftest ex7-test (testing "sqrt with objective-good-enough?" (let [sqrt (ch1/sqrt ch1/objective-good-enough?)] (is (< (- (sqrt 1 16) 4) 0.0001)) (is (< (- (sqrt 300000 100000000000) 316227.7660) 0.0001)) (comment "The following test will fail, because the" " objective test effectiveness decreases more" " rapidly as the value approaches and becomes less" " than the threshold." (is (< (- (sqrt 0.1 0.000000001) 0.00001) 0.0001))))) (testing "sqrt with relative-good-enough?" (let [sqrt (ch1/sqrt ch1/relative-good-enough?)] (is (< (- (sqrt 1 16) 4) 0.0001)) (is (< (- (sqrt 300000 100000000000) 316227.7660) 0.0001)) (comment "The following test will fail for a similar reason" " to why the equivalent objective test will fail," " however the relative test results in a much closer" " value to the actual solution, since the threshold" " has a lessened impact since it is compared with" " a relative difference." (is (< (- (sqrt 0.1 0.000000001) 0.00001) 0.0001)))))) (deftest ex8-test (testing "cbrt" (is (< (- (ch1/cbrt 1 8) 2) 0.001)) (is (< (- (ch1/cbrt 1 18) 3) 0.001)) (is (< (- (ch1/cbrt 1 64) 4) 0.001)))) (deftest ex9-test (testing "+-recursive" (is (= 9 (ch1/+-recursive 4 5))) ;; Where + = +_recursive: ;; > (+ 4 5) ;; = (inc (+ 3 5)) ;; = (inc (inc (+ 2 5))) ;; = (inc (inc (inc (+ 1 5)))) ;; = (inc (inc (inc (inc (+ 0 5))))) ;; = (inc (inc (inc (inc 5)))) ;; = (inc (inc (inc 6))) ;; = (inc (inc 7)) ;; = (inc 8) ;; = 9 ) (testing "+-iterative" (is (= 9 (ch1/+-iterative 4 5))) ;; Where + = +_iterative ;; > (+ 4 5) ;; = (+ 3 6) ;; = (+ 2 7) ;; = (+ 1 8) ;; = (+ 0 9) ;; = 9 )) (deftest ex10-test (testing "A" (is (= 1024 (ch1/A 1 10))) ;; > (A 1 10) ;; = (A 0 (A 1 9)) ;; = (* 2 (A 0 (A 1 8))) ;; = (* 2 2 (A 0 (A 1 7))) ;; = (* 2 2 2 (A 0 (A 1 6))) ;; = (* 2 2 2 2 (A 0 (A 1 5))) ;; = (* 2 2 2 2 2 (A 0 (A 1 4))) ;; = (* 2 2 2 2 2 2 (A 0 (A 1 3))) ;; = (* 2 2 2 2 2 2 2 (A 0 (A 1 2))) ;; = (* 2 2 2 2 2 2 2 2 (A 0 (A 1 1))) ;; = (* 2 2 2 2 2 2 2 2 2 (A 1 2)) ;; = (* 2 2 2 2 2 2 2 2 2 2) ;; = 1024 = 2^10 (is (= 65536 (ch1/A 2 4))) ;; > (A 2 4) ;; = (A 1 (A 2 3)) ;; = (A 1 (A 1 (A 2 2))) ;; = (A 1 (A 1 (A 1 (A 2 1)))) ;; = (A 1 (A 1 (A 1 2))) ;; = (A 1 (A 1 (A 0 (A 1 1))))) ;; = (A 1 (A 1 (A 0 2))) ;; = (A 1 (A 1 4)) ;; = (A 1 (A 0 (A 1 3))) ;; = (A 1 (A 0 (A 0 (A 1 2)))) ;; = (A 1 (A 0 (A 0 (A 0 (A 1 1))))) ;; = (A 1 (A 0 (A 0 (A 0 2)))) ;; = (A 1 (A 0 (A 0 4))) ;; = (A 1 (A 0 8)) ;; = (A 1 16) ;; = (A 0 (A 1 15)) ;; = (A 0 (A 0 (A 1 14))) ;; = (A 0 (A 0 (A 0 (A 1 13)))) ;; = (A 0 (A 0 (A 0 (A 0 (A 1 12))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 11)))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 10))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 9)))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 8))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 7)))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 6))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 5)))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 4))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 3)))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 2))))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 1)))))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 2))))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 4)))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 8))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 16)))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 32))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 64)))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 128))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 256)))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 512))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 1024)))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 2048))))) ;; = (A 0 (A 0 (A 0 (A 0 4096)))) ;; = (A 0 (A 0 (A 0 8192))) ;; = (A 0 (A 0 16384)) ;; = (A 0 32768) ;; = 65536 (is (= 65536 (ch1/A 3 3))) ;; > (A 3 3) ;; = (A 2 (A 3 2)) ;; = (A 2 (A 2 (A 3 1))) ;; = (A 2 (A 2 2)) ;; = (A 2 (A 1 (A 2 1))) ;; = (A 2 (A 1 2)) ;; = (A 2 (A 0 (A 1 1))) ;; = (A 2 (A 0 2)) ;; = (A 2 4) ;; = 65536 ) (testing "f" (is (= (* 2 5) (ch1/f 5))) (is (= (* 2 6) (ch1/f 6))) (is (= (* 2 7) (ch1/f 7))) (is (= (* 2 8) (ch1/f 8)))) (testing "g" (is (= (int (Math/pow 2 5)) (ch1/g 5))) (is (= (int (Math/pow 2 6)) (ch1/g 6))) (is (= (int (Math/pow 2 7)) (ch1/g 7))) (is (= (int (Math/pow 2 8)) (ch1/g 8)))) (testing "h" (letfn [(expt [b e] (loop [e e a b] (if (<= e 1) a (recur (dec e) (* a b))))) (tetrate [b e] (loop [n e a b] (if (<= n 1) a (recur (dec n) (expt b a)))))] (is (= 4 (expt 2 2))) (is (= 8 (expt 2 3))) (is (= 16 (expt 2 4))) (is (= 16 (tetrate 2 3))) (is (= 65536 (tetrate 2 4))) (is (= (tetrate 2 2) (ch1/h 2))) (is (= (tetrate 2 3) (ch1/h 3))) (is (= (tetrate 2 4) (ch1/h 4)))))) (deftest ex11-test (testing "recursive-f" (is (= 0 (ch1/recursive-f 0))) (is (= 1 (ch1/recursive-f 1))) (is (= 2 (ch1/recursive-f 2))) (is (= 4 (ch1/recursive-f 3))) (is (= 11 (ch1/recursive-f 4)))) (testing "iterative-f" (is (= 0 (ch1/iterative-f 0))) (is (= 1 (ch1/iterative-f 1))) (is (= 2 (ch1/iterative-f 2))) (is (= 4 (ch1/iterative-f 3))) (is (= 11 (ch1/iterative-f 4))))) (deftest ex11-test (testing "pascal" ;; 0 1 2 3 4 ;; 0 1 ;; 1 1 1 ;; 2 1 2 1 ;; 3 1 3 3 1 ;; 4 1 4 6 4 1 (is (= 1 (ch1/pascal 0 0))) (is (= 1 (ch1/pascal 1 0))) (is (= 1 (ch1/pascal 1 1))) (is (= 1 (ch1/pascal 2 0))) (is (= 2 (ch1/pascal 2 1))) (is (= 1 (ch1/pascal 2 2))) (is (= 1 (ch1/pascal 3 0))) (is (= 3 (ch1/pascal 3 1))) (is (= 3 (ch1/pascal 3 2))) (is (= 1 (ch1/pascal 3 3))) (is (= 1 (ch1/pascal 4 0))) (is (= 4 (ch1/pascal 4 1))) (is (= 6 (ch1/pascal 4 2))) (is (= 4 (ch1/pascal 4 3))) (is (= 1 (ch1/pascal 4 4))))) (deftest ex14-test ;; There are 55 invocations of cc for 11 with 5 denominations. ;; Each invocation branches into two calls; one branch exhausting ;; the number of coins, the other exhausting the amount. Once the ;; coins are exhausted, the coin branch is degenerate and always ;; returns immediately, making the amount branch result in ~2 * amount ;; calls, or O(A). Thus, both branches are O(A * 2^K), ;; where A is the amount & K is the number of distinct kinds of coins. (is (= (ch1/cc 11 5) (reduce (fn [a b] (when (= a b) a)) (ch1/cc 11 5) [(+ (ch1/cc 11 4) (ch1/cc -39 5)) (+ (+ (ch1/cc 11 3) (ch1/cc -4 4)) 0) (+ (+ (+ (ch1/cc 11 2) (ch1/cc 1 3)) 0) 0) (+ (+ (+ (+ (ch1/cc 11 1) (ch1/cc 6 2)) (+ (ch1/cc 1 2) (ch1/cc -9 3))) 0) 0) (+ (+ (+ (+ (+ (ch1/cc 11 0) (ch1/cc 10 1)) (+ (ch1/cc 6 1) (ch1/cc 1 2))) (+ (+ (ch1/cc 1 1) (ch1/cc -4 2)) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ (ch1/cc 10 0) (ch1/cc 9 1))) (+ (+ (ch1/cc 6 0) (ch1/cc 5 1)) (+ (ch1/cc 1 1) (ch1/cc -4 2)))) (+ (+ (+ (ch1/cc 1 0) (ch1/cc 0 1)) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ (ch1/cc 9 0) (ch1/cc 8 1)))) (+ (+ 0 (+ (ch1/cc 5 0) (ch1/cc 4 1))) (+ (+ (ch1/cc 1 0) (ch1/cc 0 1)) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ (ch1/cc 8 0) (ch1/cc 7 1))))) (+ (+ 0 (+ 0 (+ (ch1/cc 4 0) (ch1/cc 3 1)))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 7 0) (ch1/cc 6 1)))))) (+ (+ 0 (+ 0 (+ 0 (+ (ch1/cc 3 0) (ch1/cc 2 1))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 6 0) (ch1/cc 5 1))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 2 0) (ch1/cc 1 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 5 0) (ch1/cc 4 1)))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 1 0) (ch1/cc 0 1))))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 4 0) (ch1/cc 3 1))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 3 0) (ch1/cc 2 1)))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 2 0) (ch1/cc 1 1))))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 1 0) (ch1/cc 0 1)))))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1))))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ 1 (+ 1 1)) 1) 0) 0) 4])))) (deftest ex15-test (is (= 6 ;; ex 1.15.a: sine is called 6 times ;; ex 1.15.b: N reduces by a factor of 3 each time, and the ;; process gains one stack frame per reduction, which is a ;; logarithmic rate; thus it requires O(log N) stack space, ;; performing O(log N) steps. (+ 1 ;; (sine 12.15) 1 ;; (p (sine 4.05)) 1 ;; (p (p (sine 1.3499999999999999))) 1 ;; (p (p (p (sine 0.44999999999999996)))) 1 ;; (p (p (p (p (sine 0.15))))) 1 ;; (p (p (p (p (p (sine 0.049999999999999996)))))) ))) (is (= (ch1/sine 12.15) (ch1/p (ch1/p (ch1/p (ch1/p (ch1/p (ch1/sine 0.049999999999999996))))))))) (deftest ex16-test (dotimes [n 10] (dotimes [m 10] (is (= (ch1/fast-expt n m) (ch1/fast-expt-iter n m)))))) (deftest ex17-test (dotimes [n 10] (dotimes [m 10] (is (= (* n m) (ch1/fast-* n m)))))) (deftest ex18-test (doseq [n (range 10)] (doseq [m (range 10)] (is (= (* n m) (ch1/fast-*-iter n m)))))) (deftest ex19-test (doseq [n (range 92)] (is (= (ch1/fib-iter n) (ch1/fib n))))) (deftest ex20-test ;; Applicative order evaluation: 4 remainder operations (is (= (ch1/gcd 206 40) (ch1/gcd 40 6) ;; (mod 206 40) => 6 (ch1/gcd 6 4) ;; (mod 40 6) => 4 (ch1/gcd 4 2) ;; (mod 6 4) => 2 (ch1/gcd 2 0) ;; (mod 4 2) => 0 2)) ;; Normal order evaluation: 21 remainder operations (is (= (ch1/gcd 206 40) (ch1/gcd 40 (mod 206 40)) (ch1/gcd (mod 206 40) (mod 40 (mod 206 40))) (ch1/gcd (mod 40 (mod 206 40)) (mod (mod 206 40) (mod 40 (mod 206 40)))) (ch1/gcd (mod (mod 206 40) (mod 40 (mod 206 40))) (mod (mod 40 (mod 206 40)) (mod (mod 206 40) (mod 40 (mod 206 40)))))))) (deftest ex21-test (is (= 199 (ch1/smallest-divisor 199))) (is (= 1999 (ch1/smallest-divisor 1999))) (is (= 7 (ch1/smallest-divisor 19999)))) (deftest ex22-test ;; These results suggest prime? runtime is proportional to O(sqrt n), ;; and that the runtime in general is proportional to the number of ;; computational steps. (is (<= (Math/abs (- (/ (apply min (ch1/prime-runtimes-between 999990 1000010)) (apply min (ch1/prime-runtimes-between 99990 100010))) (Math/sqrt 10))) 4)) (is (<= (Math/abs (- (/ (apply min (ch1/prime-runtimes-between 99990 100010)) (apply min (ch1/prime-runtimes-between 9990 10010))) (Math/sqrt 10))) 8)) (is (<= (Math/abs (- (/ (apply min (ch1/prime-runtimes-between 9990 10010)) (apply min (ch1/prime-runtimes-between 990 1010))) (Math/sqrt 10))) 16))) (comment (deftest ex23-test ;; The tests I ran showed speedups by factors ranging from 0.6 to ;; 0.8. However, repeated tests resulted in identical runtimes -- I ;; assume the JIT compiler optimized the checks similarly. ;; The runtimes are oddly variable, with either version occasionally ;; taking 4-8x longer than the other. This can cause the test to ;; fail randomly, so it's not really a good test. Because of that, ;; I've commented out the block. (is (<= (/ (ch1/profile (fn [] (ch1/prime-2? 199)) 100000) (ch1/profile (fn [] (ch1/prime? 199)) 100000)) 1)) (is (<= (/ (ch1/profile (fn [] (ch1/prime-2? 1999)) 100000) (ch1/profile (fn [] (ch1/prime? 1999)) 100000)) 1)) (is (<= (/ (ch1/profile (fn [] (ch1/prime-2? 19999)) 100000) (ch1/profile (fn [] (ch1/prime? 19999)) 100000)) 1)))) (deftest ex24-test ;; The results suggest fast-prime? runtime is proportional to O(lg n) (is (<= (Math/abs (- (/ (apply min (ch1/fast-prime-runtimes-between 999990 1000010)) (apply min (ch1/fast-prime-runtimes-between 99990 100010))) (Math/log 10))) 4)) (is (<= (Math/abs (- (/ (apply min (ch1/fast-prime-runtimes-between 99990 100010)) (apply min (ch1/fast-prime-runtimes-between 9990 10010))) (Math/log 10))) 4)) (is (<= (Math/abs (- (/ (apply min (ch1/fast-prime-runtimes-between 9990 10010)) (apply min (ch1/fast-prime-runtimes-between 990 1010))) (Math/log 10))) 4))) (deftest ex25-test ;; The naive method of computing b^e then taking that modulo m will ;; result in extremely large integers, overflowing the primitive ;; types. While this is not an issue when the numbers are already ;; larger than the primitive types, it does mean computations will ;; be significantly slower since even ones that can be done with ;; only primitives must be promoted to a bigint type. (try (ch1/bad-expmod 200 200 200) (catch ArithmeticException e (is (= (.getMessage e) "integer overflow")))) (is (= 0 (ch1/exp-mod 200 200 200)))) (deftest ex26-test (let [order (ch1/average-slope-order #(ch1/linear-expmod 2 % 7) 25)] ;; The order of growth has exponent 1, i.e. O(N); when the input ;; size doubles, the runtime also doubles. This is because, while ;; the (quot e 2) clause in linear-expmod does logarithmically ;; reduce the number of cases to run, that case is run twice since ;; it's called twice in the manual * clause (instead of once, were ;; the square function used). So, while there are O(log N) steps, ;; each step has the pattern for 2^N calls to linear-expmod, ;; resulting in O(2^(lg N)) = O(N) calls. (is (= 1 order)))) (def carmichael-numbers [561 1105 1729 2465 2821 6601]) (deftest ex27-test (doseq [carmichael carmichael-numbers] (is (ch1/fast-prime? carmichael 5)) (is (ch1/mod-prime? carmichael)))) (deftest ex28-test (doseq [carmichael carmichael-numbers] (is (not (ch1/miller-rabin-prime? carmichael 5)))) (let [data (range 2 100)] (is (= (map ch1/prime? data) (map #(ch1/miller-rabin-prime? % 7) data))))) (deftest ex29-test (is (<= (Math/abs (- (ch1/simpsons-rule ch1/cube 0 1 100) 0.25)) (Math/abs (- (ch1/integral ch1/cube 0 1 0.01) 0.25)))) (is (<= (Math/abs (- (ch1/simpsons-rule ch1/cube 0 1 1000) 0.25)) (Math/abs (- (ch1/integral ch1/cube 0 1 0.001) 0.25))))) (deftest ex30-test (is (= (ch1/sum-cubes 1 10) (ch1/sum-recursive ch1/cube 1 inc 10)))) (deftest ex31-a-test (letfn [(error [n] (Math/abs (- (ch1/approximate-pi n) Math/PI)))] (is (< (error 1024) (error 512) (error 256) (error 128) (error 64) (error 32) (error 16) (error 8))))) (deftest ex31-b-test (is (= (ch1/factorial 10) (ch1/product-recursive identity 1 inc 10)))) (deftest ex32-a-test (is (= (ch1/sum-cubes 1 10) (ch1/accumulate-sum ch1/cube 1 inc 10))) (is (= (ch1/factorial 10) (ch1/accumulate-product identity 1 inc 10)))) (deftest ex32-b-test (is (= (ch1/accumulate + 0 ch1/cube 1 inc 10) (ch1/accumulate-recursive + 0 ch1/cube 1 inc 10))) (is (= (ch1/accumulate * 1 identity 1 inc 10) (ch1/accumulate-recursive * 1 identity 1 inc 10)))) (deftest ex33-a-test (let [N 100] (is (= (ch1/sum-prime-squares 1 N) (transduce (comp (filter ch1/prime?) (map ch1/square)) + 0 (range (inc N))))))) (deftest ex33-b-test (let [N 20] (is (= (ch1/product-relatively-prime-ints N) (transduce (filter (partial ch1/relatively-prime? N)) * 1 (range 1 (inc N))))))) (deftest ex34-test (letfn [(f [g] (g 2))] (is (= 4 (f ch1/square))) (is (= 6 (f (fn [z] (* z (inc z)))))) ;; (f f) = (f 2) = (2 2); 2 is not an IFn, so a ClassCastException ;; is thrown. (try (f f) (catch Throwable e (is (= java.lang.ClassCastException (class e))))))) (deftest ex35-test (is (ch1/close-enough? ch1/phi (/ (inc (Math/sqrt 5)) 2)))) (deftest ex36-test (is (= "f(5.0000000000) = 4.2920296742 f(4.2920296742) = 4.7418631199 f(4.7418631199) = 4.4382045698 f(4.4382045698) = 4.6352998871 f(4.6352998871) = 4.5039781161 f(4.5039781161) = 4.5899894627 f(4.5899894627) = 4.5330115077 f(4.5330115077) = 4.5704756729 f(4.5704756729) = 4.5457203897 f(4.5457203897) = 4.5620249366 f(4.5620249366) = 4.5512632341 f(4.5512632341) = 4.5583563877 f(4.5583563877) = 4.5536768522 f(4.5536768522) = 4.5567621643 f(4.5567621643) = 4.5547271307 f(4.5547271307) = 4.5560690548 f(4.5560690548) = 4.5551840188 f(4.5551840188) = 4.5557676565 f(4.5557676565) = 4.5553827466 f(4.5553827466) = 4.5556365824 f(4.5556365824) = 4.5554691802 f(4.5554691802) = 4.5555795779 f(4.5555795779) = 4.5555067723 f(4.5555067723) = 4.5555547860 f(4.5555547860) = 4.5555231218 f(4.5555231218) = 4.5555440037 f(4.5555440037) = 4.5555302325 f(4.5555302325) = 4.5555393144 f(4.5555393144) = 4.5555333250 f(4.5555333250) = 4.5555372749 f(4.5555372749) = 4.5555346700 f(4.5555346700) = 4.5555363879 f(4.5555363879) = 4.5555352550 f(4.5555352550) = 4.5555360021 " (with-out-str (ch1/fixed-point-showing-work (fn [x] (/ (Math/log 1000) (Math/log x))) 5)))) (is (= 34 (ch1/number-of-steps-for-fixed-point (fn [x] (/ (Math/log 1000) (Math/log x))) 5))) ;; Note that with average dampening, the number of steps is ;; significantly reduced. (is (= 9 (ch1/number-of-steps-for-fixed-point (fn [x] (ch1/average x (/ (Math/log 1000) (Math/log x)))) 5)))) (deftest ex37-a-test ;; k must be at least 10 to have 4 decimal places of accuracy. (letfn [(close-enough? [a b] (< (ch1/abs (- a b)) 0.0001))] (is (close-enough? (/ 1 ch1/phi) (ch1/cont-frac (constantly 1) (constantly 1) 10))))) (deftest ex37-b-test (is (= (ch1/cont-frac (constantly 1) (constantly 1) 10) (ch1/cont-frac-recursive (constantly 1) (constantly 1) 10)))) (deftest ex38-test (is (= Math/E ch1/e))) (deftest ex39-test (letfn [(close-enough? [a b] (< (ch1/abs (- a b)) 0.000000001)) (tan [x] (double (ch1/tan-cf x 100)))] (is (close-enough? (Math/tan 0) (tan 0))) (is (close-enough? (Math/tan 1) (tan 1))) (is (close-enough? (Math/tan Math/PI) (tan Math/PI))) (is (close-enough? (Math/tan (* 2 Math/PI)) (tan (* 2 Math/PI)))))) (deftest ex40-test (is (ch1/close-enough? 0 (ch1/newtons-method (ch1/cubic 0 0 0) 1))) (is (ch1/close-enough? -2 (ch1/newtons-method (ch1/cubic 0 0 8) 1))) (is (ch1/close-enough? -2.1325 (ch1/newtons-method (ch1/cubic 2 3 7) 1)))) (deftest ex41-test (is (= 2 ((ch1/double inc) 0))) (is (= 13 ((ch1/double inc) 11)))) (deftest ex42-test (is (= 49 ((ch1/compose ch1/square inc) 6)))) (deftest ex43-test (is (= 625 ((ch1/repeated ch1/square 2) 5))) (is (= 10 ((ch1/repeated inc 10) 0))) (is (= 11 ((ch1/repeated inc 11) 0))) (is (= 625 ((ch1/repeated-fast ch1/square 2) 5))) (is (= 10 ((ch1/repeated-fast inc 10) 0))) (is (= 11 ((ch1/repeated-fast inc 11) 0)))) (deftest ex44-test (is (= 1.0 ((ch1/smooth inc) 0))) (is (= (/ (+ (ch1/square (- 2 ch1/dx)) 4 (ch1/square (+ 2 ch1/dx))) 3) ((ch1/smooth ch1/square) 2))) (is (= ((ch1/smooth (ch1/smooth (ch1/smooth ch1/square))) 2) ((ch1/n-smooth ch1/square 3) 2)))) (deftest ex45-test (is (ch1/close-enough? 2 (ch1/nth-root 4 2))) (is (ch1/close-enough? 2 (ch1/nth-root 8 3))) (is (ch1/close-enough? 2 (ch1/nth-root 16 4))) (is (ch1/close-enough? 2 (ch1/nth-root 32 5))) (is (ch1/close-enough? 2 (ch1/nth-root 64 6))) (is (ch1/close-enough? 2 (ch1/nth-root 128 7))) (is (ch1/close-enough? 2 (ch1/nth-root 256 8))) (is (ch1/close-enough? 2 (ch1/nth-root 512 9))) (is (ch1/close-enough? 2 (ch1/nth-root 1024 10)))) (deftest ex46-test (doseq [x [2 4 8 16 32 64 128 256 512]] (is (ch1/close-enough? (ch1/sqrt-via-average-damp x) (ch1/sqrt-via-iterative-improve x 1.0)))) (doseq [x [2 4 8 16 32 64 128 256 512]] (let [f (fn [y] (ch1/average y (/ x y)))] (is (ch1/close-enough? (ch1/fixed-point f 1.0) (ch1/fixed-point-via-iterative-improve f 1.0))))))
57866
(ns sicp.ch1-test (:require [clojure.test :refer [deftest is testing]] [sicp.ch1 :as ch1])) (deftest ex1-test (is (= 10 10)) (is (= 12 (+ 5 3 4))) (is (= 8 (- 9 1))) (is (= 3 (/ 6 2))) (is (= 6 (+ (* 2 4) (- 4 6)))) (let [a 3 b (+ a 1)] (is (= 3 a)) (is (= 4 b)) (is (= 19 (+ a b (* a b)))) (is (= 4 (if (and (> b a) (< b (* a b))) b a))) (is (= 16 (cond (= a 4) 6 (= b 4) (+ 6 7 a) :else 25))) (is (= 6 (+ 2 (if (> b a) b a)))) (is (= 16 (* (cond (> a b) a (< a b) b :else -1) (+ a 1)))))) (deftest ex2-test (is (= -37/150 (/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5))))) (* 3 (- 6 2) (- 2 7)))))) (deftest ex3-test (testing "sum-larger-squares" (is (= 5 (ch1/sum-larger-squares 1 2 0))) (is (= 5 (ch1/sum-larger-squares 1 0 2))) (is (= 5 (ch1/sum-larger-squares 0 2 1))))) (deftest ex4-test (testing "a+abs-b" (is (= 11 (ch1/a+abs-b 5 6))) (is (= 11 (ch1/a+abs-b 5 -6))))) (comment ;; ex5-test ; invoking (test 0 (p)) "Invocations of (ch1/test 0 (ch1/p)) will never" " terminate, as long as test is a normal function;" " i.e. it uses applicative order evaluation, which" " will attempt to evaluate the infinitely recursive" " definition of p." " If test is a macro, i.e. it uses normal order" " evaluation, then it will not evaluate p until it" " needs the value, so 0 will be returned.") (comment ;; ex6-test : sqrt-iter using new-if "new-if is a function, not a macro, so its arguments are" " evaluated before it is invoked (applicative order)." " Consequently, the sqrt-iter function will loop forever," " as each invocation of new-if in sqrt-iter will result" " in another sqrt-iter call. This will stack overflow," " since the function is not tail recursive.") (deftest ex7-test (testing "sqrt with objective-good-enough?" (let [sqrt (ch1/sqrt ch1/objective-good-enough?)] (is (< (- (sqrt 1 16) 4) 0.0001)) (is (< (- (sqrt 300000 100000000000) 316227.7660) 0.0001)) (comment "The following test will fail, because the" " objective test effectiveness decreases more" " rapidly as the value approaches and becomes less" " than the threshold." (is (< (- (sqrt 0.1 0.000000001) 0.00001) 0.0001))))) (testing "sqrt with relative-good-enough?" (let [sqrt (ch1/sqrt ch1/relative-good-enough?)] (is (< (- (sqrt 1 16) 4) 0.0001)) (is (< (- (sqrt 300000 100000000000) 316227.7660) 0.0001)) (comment "The following test will fail for a similar reason" " to why the equivalent objective test will fail," " however the relative test results in a much closer" " value to the actual solution, since the threshold" " has a lessened impact since it is compared with" " a relative difference." (is (< (- (sqrt 0.1 0.000000001) 0.00001) 0.0001)))))) (deftest ex8-test (testing "cbrt" (is (< (- (ch1/cbrt 1 8) 2) 0.001)) (is (< (- (ch1/cbrt 1 18) 3) 0.001)) (is (< (- (ch1/cbrt 1 64) 4) 0.001)))) (deftest ex9-test (testing "+-recursive" (is (= 9 (ch1/+-recursive 4 5))) ;; Where + = +_recursive: ;; > (+ 4 5) ;; = (inc (+ 3 5)) ;; = (inc (inc (+ 2 5))) ;; = (inc (inc (inc (+ 1 5)))) ;; = (inc (inc (inc (inc (+ 0 5))))) ;; = (inc (inc (inc (inc 5)))) ;; = (inc (inc (inc 6))) ;; = (inc (inc 7)) ;; = (inc 8) ;; = 9 ) (testing "+-iterative" (is (= 9 (ch1/+-iterative 4 5))) ;; Where + = +_iterative ;; > (+ 4 5) ;; = (+ 3 6) ;; = (+ 2 7) ;; = (+ 1 8) ;; = (+ 0 9) ;; = 9 )) (deftest ex10-test (testing "A" (is (= 1024 (ch1/A 1 10))) ;; > (A 1 10) ;; = (A 0 (A 1 9)) ;; = (* 2 (A 0 (A 1 8))) ;; = (* 2 2 (A 0 (A 1 7))) ;; = (* 2 2 2 (A 0 (A 1 6))) ;; = (* 2 2 2 2 (A 0 (A 1 5))) ;; = (* 2 2 2 2 2 (A 0 (A 1 4))) ;; = (* 2 2 2 2 2 2 (A 0 (A 1 3))) ;; = (* 2 2 2 2 2 2 2 (A 0 (A 1 2))) ;; = (* 2 2 2 2 2 2 2 2 (A 0 (A 1 1))) ;; = (* 2 2 2 2 2 2 2 2 2 (A 1 2)) ;; = (* 2 2 2 2 2 2 2 2 2 2) ;; = 1024 = 2^10 (is (= 65536 (ch1/A 2 4))) ;; > (A 2 4) ;; = (A 1 (A 2 3)) ;; = (A 1 (A 1 (A 2 2))) ;; = (A 1 (A 1 (A 1 (A 2 1)))) ;; = (A 1 (A 1 (A 1 2))) ;; = (A 1 (A 1 (A 0 (A 1 1))))) ;; = (A 1 (A 1 (A 0 2))) ;; = (A 1 (A 1 4)) ;; = (A 1 (A 0 (A 1 3))) ;; = (A 1 (A 0 (A 0 (A 1 2)))) ;; = (A 1 (A 0 (A 0 (A 0 (A 1 1))))) ;; = (A 1 (A 0 (A 0 (A 0 2)))) ;; = (A 1 (A 0 (A 0 4))) ;; = (A 1 (A 0 8)) ;; = (A 1 16) ;; = (A 0 (A 1 15)) ;; = (A 0 (A 0 (A 1 14))) ;; = (A 0 (A 0 (A 0 (A 1 13)))) ;; = (A 0 (A 0 (A 0 (A 0 (A 1 12))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 11)))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 10))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 9)))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 8))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 7)))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 6))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 5)))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 4))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 3)))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 2))))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 1)))))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 2))))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 4)))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 8))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 16)))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 32))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 64)))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 128))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 256)))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 512))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 1024)))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 2048))))) ;; = (A 0 (A 0 (A 0 (A 0 4096)))) ;; = (A 0 (A 0 (A 0 8192))) ;; = (A 0 (A 0 16384)) ;; = (A 0 32768) ;; = 65536 (is (= 65536 (ch1/A 3 3))) ;; > (A 3 3) ;; = (A 2 (A 3 2)) ;; = (A 2 (A 2 (A 3 1))) ;; = (A 2 (A 2 2)) ;; = (A 2 (A 1 (A 2 1))) ;; = (A 2 (A 1 2)) ;; = (A 2 (A 0 (A 1 1))) ;; = (A 2 (A 0 2)) ;; = (A 2 4) ;; = 65536 ) (testing "f" (is (= (* 2 5) (ch1/f 5))) (is (= (* 2 6) (ch1/f 6))) (is (= (* 2 7) (ch1/f 7))) (is (= (* 2 8) (ch1/f 8)))) (testing "g" (is (= (int (Math/pow 2 5)) (ch1/g 5))) (is (= (int (Math/pow 2 6)) (ch1/g 6))) (is (= (int (Math/pow 2 7)) (ch1/g 7))) (is (= (int (Math/pow 2 8)) (ch1/g 8)))) (testing "h" (letfn [(expt [b e] (loop [e e a b] (if (<= e 1) a (recur (dec e) (* a b))))) (tetrate [b e] (loop [n e a b] (if (<= n 1) a (recur (dec n) (expt b a)))))] (is (= 4 (expt 2 2))) (is (= 8 (expt 2 3))) (is (= 16 (expt 2 4))) (is (= 16 (tetrate 2 3))) (is (= 65536 (tetrate 2 4))) (is (= (tetrate 2 2) (ch1/h 2))) (is (= (tetrate 2 3) (ch1/h 3))) (is (= (tetrate 2 4) (ch1/h 4)))))) (deftest ex11-test (testing "recursive-f" (is (= 0 (ch1/recursive-f 0))) (is (= 1 (ch1/recursive-f 1))) (is (= 2 (ch1/recursive-f 2))) (is (= 4 (ch1/recursive-f 3))) (is (= 11 (ch1/recursive-f 4)))) (testing "iterative-f" (is (= 0 (ch1/iterative-f 0))) (is (= 1 (ch1/iterative-f 1))) (is (= 2 (ch1/iterative-f 2))) (is (= 4 (ch1/iterative-f 3))) (is (= 11 (ch1/iterative-f 4))))) (deftest ex11-test (testing "pascal" ;; 0 1 2 3 4 ;; 0 1 ;; 1 1 1 ;; 2 1 2 1 ;; 3 1 3 3 1 ;; 4 1 4 6 4 1 (is (= 1 (ch1/pascal 0 0))) (is (= 1 (ch1/pascal 1 0))) (is (= 1 (ch1/pascal 1 1))) (is (= 1 (ch1/pascal 2 0))) (is (= 2 (ch1/pascal 2 1))) (is (= 1 (ch1/pascal 2 2))) (is (= 1 (ch1/pascal 3 0))) (is (= 3 (ch1/pascal 3 1))) (is (= 3 (ch1/pascal 3 2))) (is (= 1 (ch1/pascal 3 3))) (is (= 1 (ch1/pascal 4 0))) (is (= 4 (ch1/pascal 4 1))) (is (= 6 (ch1/pascal 4 2))) (is (= 4 (ch1/pascal 4 3))) (is (= 1 (ch1/pascal 4 4))))) (deftest ex14-test ;; There are 55 invocations of cc for 11 with 5 denominations. ;; Each invocation branches into two calls; one branch exhausting ;; the number of coins, the other exhausting the amount. Once the ;; coins are exhausted, the coin branch is degenerate and always ;; returns immediately, making the amount branch result in ~2 * amount ;; calls, or O(A). Thus, both branches are O(A * 2^K), ;; where A is the amount & K is the number of distinct kinds of coins. (is (= (ch1/cc 11 5) (reduce (fn [a b] (when (= a b) a)) (ch1/cc 11 5) [(+ (ch1/cc 11 4) (ch1/cc -39 5)) (+ (+ (ch1/cc 11 3) (ch1/cc -4 4)) 0) (+ (+ (+ (ch1/cc 11 2) (ch1/cc 1 3)) 0) 0) (+ (+ (+ (+ (ch1/cc 11 1) (ch1/cc 6 2)) (+ (ch1/cc 1 2) (ch1/cc -9 3))) 0) 0) (+ (+ (+ (+ (+ (ch1/cc 11 0) (ch1/cc 10 1)) (+ (ch1/cc 6 1) (ch1/cc 1 2))) (+ (+ (ch1/cc 1 1) (ch1/cc -4 2)) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ (ch1/cc 10 0) (ch1/cc 9 1))) (+ (+ (ch1/cc 6 0) (ch1/cc 5 1)) (+ (ch1/cc 1 1) (ch1/cc -4 2)))) (+ (+ (+ (ch1/cc 1 0) (ch1/cc 0 1)) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ (ch1/cc 9 0) (ch1/cc 8 1)))) (+ (+ 0 (+ (ch1/cc 5 0) (ch1/cc 4 1))) (+ (+ (ch1/cc 1 0) (ch1/cc 0 1)) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ (ch1/cc 8 0) (ch1/cc 7 1))))) (+ (+ 0 (+ 0 (+ (ch1/cc 4 0) (ch1/cc 3 1)))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 7 0) (ch1/cc 6 1)))))) (+ (+ 0 (+ 0 (+ 0 (+ (ch1/cc 3 0) (ch1/cc 2 1))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 6 0) (ch1/cc 5 1))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 2 0) (ch1/cc 1 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 5 0) (ch1/cc 4 1)))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 1 0) (ch1/cc 0 1))))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 4 0) (ch1/cc 3 1))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 3 0) (ch1/cc 2 1)))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 2 0) (ch1/cc 1 1))))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 1 0) (ch1/cc 0 1)))))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1))))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ 1 (+ 1 1)) 1) 0) 0) 4])))) (deftest ex15-test (is (= 6 ;; ex 1.15.a: sine is called 6 times ;; ex 1.15.b: N reduces by a factor of 3 each time, and the ;; process gains one stack frame per reduction, which is a ;; logarithmic rate; thus it requires O(log N) stack space, ;; performing O(log N) steps. (+ 1 ;; (sine 12.15) 1 ;; (p (sine 4.05)) 1 ;; (p (p (sine 1.3499999999999999))) 1 ;; (p (p (p (sine 0.44999999999999996)))) 1 ;; (p (p (p (p (sine 0.15))))) 1 ;; (p (p (p (p (p (sine 0.049999999999999996)))))) ))) (is (= (ch1/sine 12.15) (ch1/p (ch1/p (ch1/p (ch1/p (ch1/p (ch1/sine 0.049999999999999996))))))))) (deftest ex16-test (dotimes [n 10] (dotimes [m 10] (is (= (ch1/fast-expt n m) (ch1/fast-expt-iter n m)))))) (deftest ex17-test (dotimes [n 10] (dotimes [m 10] (is (= (* n m) (ch1/fast-* n m)))))) (deftest ex18-test (doseq [n (range 10)] (doseq [m (range 10)] (is (= (* n m) (ch1/fast-*-iter n m)))))) (deftest ex19-test (doseq [n (range 92)] (is (= (ch1/fib-iter n) (ch1/fib n))))) (deftest ex20-test ;; Applicative order evaluation: 4 remainder operations (is (= (ch1/gcd 206 40) (ch1/gcd 40 6) ;; (mod 206 40) => 6 (ch1/gcd 6 4) ;; (mod 40 6) => 4 (ch1/gcd 4 2) ;; (mod 6 4) => 2 (ch1/gcd 2 0) ;; (mod 4 2) => 0 2)) ;; Normal order evaluation: 21 remainder operations (is (= (ch1/gcd 206 40) (ch1/gcd 40 (mod 206 40)) (ch1/gcd (mod 206 40) (mod 40 (mod 206 40))) (ch1/gcd (mod 40 (mod 206 40)) (mod (mod 206 40) (mod 40 (mod 206 40)))) (ch1/gcd (mod (mod 206 40) (mod 40 (mod 206 40))) (mod (mod 40 (mod 206 40)) (mod (mod 206 40) (mod 40 (mod 206 40)))))))) (deftest ex21-test (is (= 199 (ch1/smallest-divisor 199))) (is (= 1999 (ch1/smallest-divisor 1999))) (is (= 7 (ch1/smallest-divisor 19999)))) (deftest ex22-test ;; These results suggest prime? runtime is proportional to O(sqrt n), ;; and that the runtime in general is proportional to the number of ;; computational steps. (is (<= (Math/abs (- (/ (apply min (ch1/prime-runtimes-between 999990 1000010)) (apply min (ch1/prime-runtimes-between 99990 100010))) (Math/sqrt 10))) 4)) (is (<= (Math/abs (- (/ (apply min (ch1/prime-runtimes-between 99990 100010)) (apply min (ch1/prime-runtimes-between 9990 10010))) (Math/sqrt 10))) 8)) (is (<= (Math/abs (- (/ (apply min (ch1/prime-runtimes-between 9990 10010)) (apply min (ch1/prime-runtimes-between 990 1010))) (Math/sqrt 10))) 16))) (comment (deftest ex23-test ;; The tests I ran showed speedups by factors ranging from 0.6 to ;; 0.8. However, repeated tests resulted in identical runtimes -- I ;; assume the JIT compiler optimized the checks similarly. ;; The runtimes are oddly variable, with either version occasionally ;; taking 4-8x longer than the other. This can cause the test to ;; fail randomly, so it's not really a good test. Because of that, ;; I've commented out the block. (is (<= (/ (ch1/profile (fn [] (ch1/prime-2? 199)) 100000) (ch1/profile (fn [] (ch1/prime? 199)) 100000)) 1)) (is (<= (/ (ch1/profile (fn [] (ch1/prime-2? 1999)) 100000) (ch1/profile (fn [] (ch1/prime? 1999)) 100000)) 1)) (is (<= (/ (ch1/profile (fn [] (ch1/prime-2? 19999)) 100000) (ch1/profile (fn [] (ch1/prime? 19999)) 100000)) 1)))) (deftest ex24-test ;; The results suggest fast-prime? runtime is proportional to O(lg n) (is (<= (Math/abs (- (/ (apply min (ch1/fast-prime-runtimes-between 999990 1000010)) (apply min (ch1/fast-prime-runtimes-between 99990 100010))) (Math/log 10))) 4)) (is (<= (Math/abs (- (/ (apply min (ch1/fast-prime-runtimes-between 99990 100010)) (apply min (ch1/fast-prime-runtimes-between 9990 10010))) (Math/log 10))) 4)) (is (<= (Math/abs (- (/ (apply min (ch1/fast-prime-runtimes-between 9990 10010)) (apply min (ch1/fast-prime-runtimes-between 990 1010))) (Math/log 10))) 4))) (deftest ex25-test ;; The naive method of computing b^e then taking that modulo m will ;; result in extremely large integers, overflowing the primitive ;; types. While this is not an issue when the numbers are already ;; larger than the primitive types, it does mean computations will ;; be significantly slower since even ones that can be done with ;; only primitives must be promoted to a bigint type. (try (ch1/bad-expmod 200 200 200) (catch ArithmeticException e (is (= (.getMessage e) "integer overflow")))) (is (= 0 (ch1/exp-mod 200 200 200)))) (deftest ex26-test (let [order (ch1/average-slope-order #(ch1/linear-expmod 2 % 7) 25)] ;; The order of growth has exponent 1, i.e. O(N); when the input ;; size doubles, the runtime also doubles. This is because, while ;; the (quot e 2) clause in linear-expmod does logarithmically ;; reduce the number of cases to run, that case is run twice since ;; it's called twice in the manual * clause (instead of once, were ;; the square function used). So, while there are O(log N) steps, ;; each step has the pattern for 2^N calls to linear-expmod, ;; resulting in O(2^(lg N)) = O(N) calls. (is (= 1 order)))) (def carmichael-numbers [561 1105 1729 2465 2821 6601]) (deftest ex27-test (doseq [<NAME> carmichael-numbers] (is (ch1/fast-prime? carmichael 5)) (is (ch1/mod-prime? carmichael)))) (deftest ex28-test (doseq [<NAME>michael carmichael-numbers] (is (not (ch1/miller-rabin-prime? carmichael 5)))) (let [data (range 2 100)] (is (= (map ch1/prime? data) (map #(ch1/miller-rabin-prime? % 7) data))))) (deftest ex29-test (is (<= (Math/abs (- (ch1/simpsons-rule ch1/cube 0 1 100) 0.25)) (Math/abs (- (ch1/integral ch1/cube 0 1 0.01) 0.25)))) (is (<= (Math/abs (- (ch1/simpsons-rule ch1/cube 0 1 1000) 0.25)) (Math/abs (- (ch1/integral ch1/cube 0 1 0.001) 0.25))))) (deftest ex30-test (is (= (ch1/sum-cubes 1 10) (ch1/sum-recursive ch1/cube 1 inc 10)))) (deftest ex31-a-test (letfn [(error [n] (Math/abs (- (ch1/approximate-pi n) Math/PI)))] (is (< (error 1024) (error 512) (error 256) (error 128) (error 64) (error 32) (error 16) (error 8))))) (deftest ex31-b-test (is (= (ch1/factorial 10) (ch1/product-recursive identity 1 inc 10)))) (deftest ex32-a-test (is (= (ch1/sum-cubes 1 10) (ch1/accumulate-sum ch1/cube 1 inc 10))) (is (= (ch1/factorial 10) (ch1/accumulate-product identity 1 inc 10)))) (deftest ex32-b-test (is (= (ch1/accumulate + 0 ch1/cube 1 inc 10) (ch1/accumulate-recursive + 0 ch1/cube 1 inc 10))) (is (= (ch1/accumulate * 1 identity 1 inc 10) (ch1/accumulate-recursive * 1 identity 1 inc 10)))) (deftest ex33-a-test (let [N 100] (is (= (ch1/sum-prime-squares 1 N) (transduce (comp (filter ch1/prime?) (map ch1/square)) + 0 (range (inc N))))))) (deftest ex33-b-test (let [N 20] (is (= (ch1/product-relatively-prime-ints N) (transduce (filter (partial ch1/relatively-prime? N)) * 1 (range 1 (inc N))))))) (deftest ex34-test (letfn [(f [g] (g 2))] (is (= 4 (f ch1/square))) (is (= 6 (f (fn [z] (* z (inc z)))))) ;; (f f) = (f 2) = (2 2); 2 is not an IFn, so a ClassCastException ;; is thrown. (try (f f) (catch Throwable e (is (= java.lang.ClassCastException (class e))))))) (deftest ex35-test (is (ch1/close-enough? ch1/phi (/ (inc (Math/sqrt 5)) 2)))) (deftest ex36-test (is (= "f(5.0000000000) = 4.2920296742 f(4.2920296742) = 4.7418631199 f(4.7418631199) = 4.4382045698 f(4.4382045698) = 4.6352998871 f(4.6352998871) = 4.5039781161 f(4.5039781161) = 4.5899894627 f(4.5899894627) = 4.5330115077 f(4.5330115077) = 4.5704756729 f(4.5704756729) = 4.5457203897 f(4.5457203897) = 4.5620249366 f(4.5620249366) = 4.5512632341 f(4.5512632341) = 4.5583563877 f(4.5583563877) = 4.5536768522 f(4.5536768522) = 4.5567621643 f(4.5567621643) = 4.5547271307 f(4.5547271307) = 4.5560690548 f(4.5560690548) = 4.5551840188 f(4.5551840188) = 4.5557676565 f(4.5557676565) = 4.5553827466 f(4.5553827466) = 4.5556365824 f(4.5556365824) = 4.5554691802 f(4.5554691802) = 4.5555795779 f(4.5555795779) = 4.5555067723 f(4.5555067723) = 4.5555547860 f(4.5555547860) = 4.5555231218 f(4.5555231218) = 4.5555440037 f(4.5555440037) = 4.5555302325 f(4.5555302325) = 4.5555393144 f(4.5555393144) = 4.5555333250 f(4.5555333250) = 4.5555372749 f(4.5555372749) = 4.5555346700 f(4.5555346700) = 4.5555363879 f(4.5555363879) = 4.5555352550 f(4.5555352550) = 4.5555360021 " (with-out-str (ch1/fixed-point-showing-work (fn [x] (/ (Math/log 1000) (Math/log x))) 5)))) (is (= 34 (ch1/number-of-steps-for-fixed-point (fn [x] (/ (Math/log 1000) (Math/log x))) 5))) ;; Note that with average dampening, the number of steps is ;; significantly reduced. (is (= 9 (ch1/number-of-steps-for-fixed-point (fn [x] (ch1/average x (/ (Math/log 1000) (Math/log x)))) 5)))) (deftest ex37-a-test ;; k must be at least 10 to have 4 decimal places of accuracy. (letfn [(close-enough? [a b] (< (ch1/abs (- a b)) 0.0001))] (is (close-enough? (/ 1 ch1/phi) (ch1/cont-frac (constantly 1) (constantly 1) 10))))) (deftest ex37-b-test (is (= (ch1/cont-frac (constantly 1) (constantly 1) 10) (ch1/cont-frac-recursive (constantly 1) (constantly 1) 10)))) (deftest ex38-test (is (= Math/E ch1/e))) (deftest ex39-test (letfn [(close-enough? [a b] (< (ch1/abs (- a b)) 0.000000001)) (tan [x] (double (ch1/tan-cf x 100)))] (is (close-enough? (Math/tan 0) (tan 0))) (is (close-enough? (Math/tan 1) (tan 1))) (is (close-enough? (Math/tan Math/PI) (tan Math/PI))) (is (close-enough? (Math/tan (* 2 Math/PI)) (tan (* 2 Math/PI)))))) (deftest ex40-test (is (ch1/close-enough? 0 (ch1/newtons-method (ch1/cubic 0 0 0) 1))) (is (ch1/close-enough? -2 (ch1/newtons-method (ch1/cubic 0 0 8) 1))) (is (ch1/close-enough? -2.1325 (ch1/newtons-method (ch1/cubic 2 3 7) 1)))) (deftest ex41-test (is (= 2 ((ch1/double inc) 0))) (is (= 13 ((ch1/double inc) 11)))) (deftest ex42-test (is (= 49 ((ch1/compose ch1/square inc) 6)))) (deftest ex43-test (is (= 625 ((ch1/repeated ch1/square 2) 5))) (is (= 10 ((ch1/repeated inc 10) 0))) (is (= 11 ((ch1/repeated inc 11) 0))) (is (= 625 ((ch1/repeated-fast ch1/square 2) 5))) (is (= 10 ((ch1/repeated-fast inc 10) 0))) (is (= 11 ((ch1/repeated-fast inc 11) 0)))) (deftest ex44-test (is (= 1.0 ((ch1/smooth inc) 0))) (is (= (/ (+ (ch1/square (- 2 ch1/dx)) 4 (ch1/square (+ 2 ch1/dx))) 3) ((ch1/smooth ch1/square) 2))) (is (= ((ch1/smooth (ch1/smooth (ch1/smooth ch1/square))) 2) ((ch1/n-smooth ch1/square 3) 2)))) (deftest ex45-test (is (ch1/close-enough? 2 (ch1/nth-root 4 2))) (is (ch1/close-enough? 2 (ch1/nth-root 8 3))) (is (ch1/close-enough? 2 (ch1/nth-root 16 4))) (is (ch1/close-enough? 2 (ch1/nth-root 32 5))) (is (ch1/close-enough? 2 (ch1/nth-root 64 6))) (is (ch1/close-enough? 2 (ch1/nth-root 128 7))) (is (ch1/close-enough? 2 (ch1/nth-root 256 8))) (is (ch1/close-enough? 2 (ch1/nth-root 512 9))) (is (ch1/close-enough? 2 (ch1/nth-root 1024 10)))) (deftest ex46-test (doseq [x [2 4 8 16 32 64 128 256 512]] (is (ch1/close-enough? (ch1/sqrt-via-average-damp x) (ch1/sqrt-via-iterative-improve x 1.0)))) (doseq [x [2 4 8 16 32 64 128 256 512]] (let [f (fn [y] (ch1/average y (/ x y)))] (is (ch1/close-enough? (ch1/fixed-point f 1.0) (ch1/fixed-point-via-iterative-improve f 1.0))))))
true
(ns sicp.ch1-test (:require [clojure.test :refer [deftest is testing]] [sicp.ch1 :as ch1])) (deftest ex1-test (is (= 10 10)) (is (= 12 (+ 5 3 4))) (is (= 8 (- 9 1))) (is (= 3 (/ 6 2))) (is (= 6 (+ (* 2 4) (- 4 6)))) (let [a 3 b (+ a 1)] (is (= 3 a)) (is (= 4 b)) (is (= 19 (+ a b (* a b)))) (is (= 4 (if (and (> b a) (< b (* a b))) b a))) (is (= 16 (cond (= a 4) 6 (= b 4) (+ 6 7 a) :else 25))) (is (= 6 (+ 2 (if (> b a) b a)))) (is (= 16 (* (cond (> a b) a (< a b) b :else -1) (+ a 1)))))) (deftest ex2-test (is (= -37/150 (/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5))))) (* 3 (- 6 2) (- 2 7)))))) (deftest ex3-test (testing "sum-larger-squares" (is (= 5 (ch1/sum-larger-squares 1 2 0))) (is (= 5 (ch1/sum-larger-squares 1 0 2))) (is (= 5 (ch1/sum-larger-squares 0 2 1))))) (deftest ex4-test (testing "a+abs-b" (is (= 11 (ch1/a+abs-b 5 6))) (is (= 11 (ch1/a+abs-b 5 -6))))) (comment ;; ex5-test ; invoking (test 0 (p)) "Invocations of (ch1/test 0 (ch1/p)) will never" " terminate, as long as test is a normal function;" " i.e. it uses applicative order evaluation, which" " will attempt to evaluate the infinitely recursive" " definition of p." " If test is a macro, i.e. it uses normal order" " evaluation, then it will not evaluate p until it" " needs the value, so 0 will be returned.") (comment ;; ex6-test : sqrt-iter using new-if "new-if is a function, not a macro, so its arguments are" " evaluated before it is invoked (applicative order)." " Consequently, the sqrt-iter function will loop forever," " as each invocation of new-if in sqrt-iter will result" " in another sqrt-iter call. This will stack overflow," " since the function is not tail recursive.") (deftest ex7-test (testing "sqrt with objective-good-enough?" (let [sqrt (ch1/sqrt ch1/objective-good-enough?)] (is (< (- (sqrt 1 16) 4) 0.0001)) (is (< (- (sqrt 300000 100000000000) 316227.7660) 0.0001)) (comment "The following test will fail, because the" " objective test effectiveness decreases more" " rapidly as the value approaches and becomes less" " than the threshold." (is (< (- (sqrt 0.1 0.000000001) 0.00001) 0.0001))))) (testing "sqrt with relative-good-enough?" (let [sqrt (ch1/sqrt ch1/relative-good-enough?)] (is (< (- (sqrt 1 16) 4) 0.0001)) (is (< (- (sqrt 300000 100000000000) 316227.7660) 0.0001)) (comment "The following test will fail for a similar reason" " to why the equivalent objective test will fail," " however the relative test results in a much closer" " value to the actual solution, since the threshold" " has a lessened impact since it is compared with" " a relative difference." (is (< (- (sqrt 0.1 0.000000001) 0.00001) 0.0001)))))) (deftest ex8-test (testing "cbrt" (is (< (- (ch1/cbrt 1 8) 2) 0.001)) (is (< (- (ch1/cbrt 1 18) 3) 0.001)) (is (< (- (ch1/cbrt 1 64) 4) 0.001)))) (deftest ex9-test (testing "+-recursive" (is (= 9 (ch1/+-recursive 4 5))) ;; Where + = +_recursive: ;; > (+ 4 5) ;; = (inc (+ 3 5)) ;; = (inc (inc (+ 2 5))) ;; = (inc (inc (inc (+ 1 5)))) ;; = (inc (inc (inc (inc (+ 0 5))))) ;; = (inc (inc (inc (inc 5)))) ;; = (inc (inc (inc 6))) ;; = (inc (inc 7)) ;; = (inc 8) ;; = 9 ) (testing "+-iterative" (is (= 9 (ch1/+-iterative 4 5))) ;; Where + = +_iterative ;; > (+ 4 5) ;; = (+ 3 6) ;; = (+ 2 7) ;; = (+ 1 8) ;; = (+ 0 9) ;; = 9 )) (deftest ex10-test (testing "A" (is (= 1024 (ch1/A 1 10))) ;; > (A 1 10) ;; = (A 0 (A 1 9)) ;; = (* 2 (A 0 (A 1 8))) ;; = (* 2 2 (A 0 (A 1 7))) ;; = (* 2 2 2 (A 0 (A 1 6))) ;; = (* 2 2 2 2 (A 0 (A 1 5))) ;; = (* 2 2 2 2 2 (A 0 (A 1 4))) ;; = (* 2 2 2 2 2 2 (A 0 (A 1 3))) ;; = (* 2 2 2 2 2 2 2 (A 0 (A 1 2))) ;; = (* 2 2 2 2 2 2 2 2 (A 0 (A 1 1))) ;; = (* 2 2 2 2 2 2 2 2 2 (A 1 2)) ;; = (* 2 2 2 2 2 2 2 2 2 2) ;; = 1024 = 2^10 (is (= 65536 (ch1/A 2 4))) ;; > (A 2 4) ;; = (A 1 (A 2 3)) ;; = (A 1 (A 1 (A 2 2))) ;; = (A 1 (A 1 (A 1 (A 2 1)))) ;; = (A 1 (A 1 (A 1 2))) ;; = (A 1 (A 1 (A 0 (A 1 1))))) ;; = (A 1 (A 1 (A 0 2))) ;; = (A 1 (A 1 4)) ;; = (A 1 (A 0 (A 1 3))) ;; = (A 1 (A 0 (A 0 (A 1 2)))) ;; = (A 1 (A 0 (A 0 (A 0 (A 1 1))))) ;; = (A 1 (A 0 (A 0 (A 0 2)))) ;; = (A 1 (A 0 (A 0 4))) ;; = (A 1 (A 0 8)) ;; = (A 1 16) ;; = (A 0 (A 1 15)) ;; = (A 0 (A 0 (A 1 14))) ;; = (A 0 (A 0 (A 0 (A 1 13)))) ;; = (A 0 (A 0 (A 0 (A 0 (A 1 12))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 11)))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 10))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 9)))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 8))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 7)))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 6))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 5)))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 4))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 3)))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 2))))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 1)))))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 2))))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 4)))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 8))))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 16)))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 32))))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 64)))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 128))))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 256)))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 512))))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 1024)))))) ;; = (A 0 (A 0 (A 0 (A 0 (A 0 2048))))) ;; = (A 0 (A 0 (A 0 (A 0 4096)))) ;; = (A 0 (A 0 (A 0 8192))) ;; = (A 0 (A 0 16384)) ;; = (A 0 32768) ;; = 65536 (is (= 65536 (ch1/A 3 3))) ;; > (A 3 3) ;; = (A 2 (A 3 2)) ;; = (A 2 (A 2 (A 3 1))) ;; = (A 2 (A 2 2)) ;; = (A 2 (A 1 (A 2 1))) ;; = (A 2 (A 1 2)) ;; = (A 2 (A 0 (A 1 1))) ;; = (A 2 (A 0 2)) ;; = (A 2 4) ;; = 65536 ) (testing "f" (is (= (* 2 5) (ch1/f 5))) (is (= (* 2 6) (ch1/f 6))) (is (= (* 2 7) (ch1/f 7))) (is (= (* 2 8) (ch1/f 8)))) (testing "g" (is (= (int (Math/pow 2 5)) (ch1/g 5))) (is (= (int (Math/pow 2 6)) (ch1/g 6))) (is (= (int (Math/pow 2 7)) (ch1/g 7))) (is (= (int (Math/pow 2 8)) (ch1/g 8)))) (testing "h" (letfn [(expt [b e] (loop [e e a b] (if (<= e 1) a (recur (dec e) (* a b))))) (tetrate [b e] (loop [n e a b] (if (<= n 1) a (recur (dec n) (expt b a)))))] (is (= 4 (expt 2 2))) (is (= 8 (expt 2 3))) (is (= 16 (expt 2 4))) (is (= 16 (tetrate 2 3))) (is (= 65536 (tetrate 2 4))) (is (= (tetrate 2 2) (ch1/h 2))) (is (= (tetrate 2 3) (ch1/h 3))) (is (= (tetrate 2 4) (ch1/h 4)))))) (deftest ex11-test (testing "recursive-f" (is (= 0 (ch1/recursive-f 0))) (is (= 1 (ch1/recursive-f 1))) (is (= 2 (ch1/recursive-f 2))) (is (= 4 (ch1/recursive-f 3))) (is (= 11 (ch1/recursive-f 4)))) (testing "iterative-f" (is (= 0 (ch1/iterative-f 0))) (is (= 1 (ch1/iterative-f 1))) (is (= 2 (ch1/iterative-f 2))) (is (= 4 (ch1/iterative-f 3))) (is (= 11 (ch1/iterative-f 4))))) (deftest ex11-test (testing "pascal" ;; 0 1 2 3 4 ;; 0 1 ;; 1 1 1 ;; 2 1 2 1 ;; 3 1 3 3 1 ;; 4 1 4 6 4 1 (is (= 1 (ch1/pascal 0 0))) (is (= 1 (ch1/pascal 1 0))) (is (= 1 (ch1/pascal 1 1))) (is (= 1 (ch1/pascal 2 0))) (is (= 2 (ch1/pascal 2 1))) (is (= 1 (ch1/pascal 2 2))) (is (= 1 (ch1/pascal 3 0))) (is (= 3 (ch1/pascal 3 1))) (is (= 3 (ch1/pascal 3 2))) (is (= 1 (ch1/pascal 3 3))) (is (= 1 (ch1/pascal 4 0))) (is (= 4 (ch1/pascal 4 1))) (is (= 6 (ch1/pascal 4 2))) (is (= 4 (ch1/pascal 4 3))) (is (= 1 (ch1/pascal 4 4))))) (deftest ex14-test ;; There are 55 invocations of cc for 11 with 5 denominations. ;; Each invocation branches into two calls; one branch exhausting ;; the number of coins, the other exhausting the amount. Once the ;; coins are exhausted, the coin branch is degenerate and always ;; returns immediately, making the amount branch result in ~2 * amount ;; calls, or O(A). Thus, both branches are O(A * 2^K), ;; where A is the amount & K is the number of distinct kinds of coins. (is (= (ch1/cc 11 5) (reduce (fn [a b] (when (= a b) a)) (ch1/cc 11 5) [(+ (ch1/cc 11 4) (ch1/cc -39 5)) (+ (+ (ch1/cc 11 3) (ch1/cc -4 4)) 0) (+ (+ (+ (ch1/cc 11 2) (ch1/cc 1 3)) 0) 0) (+ (+ (+ (+ (ch1/cc 11 1) (ch1/cc 6 2)) (+ (ch1/cc 1 2) (ch1/cc -9 3))) 0) 0) (+ (+ (+ (+ (+ (ch1/cc 11 0) (ch1/cc 10 1)) (+ (ch1/cc 6 1) (ch1/cc 1 2))) (+ (+ (ch1/cc 1 1) (ch1/cc -4 2)) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ (ch1/cc 10 0) (ch1/cc 9 1))) (+ (+ (ch1/cc 6 0) (ch1/cc 5 1)) (+ (ch1/cc 1 1) (ch1/cc -4 2)))) (+ (+ (+ (ch1/cc 1 0) (ch1/cc 0 1)) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ (ch1/cc 9 0) (ch1/cc 8 1)))) (+ (+ 0 (+ (ch1/cc 5 0) (ch1/cc 4 1))) (+ (+ (ch1/cc 1 0) (ch1/cc 0 1)) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ (ch1/cc 8 0) (ch1/cc 7 1))))) (+ (+ 0 (+ 0 (+ (ch1/cc 4 0) (ch1/cc 3 1)))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 7 0) (ch1/cc 6 1)))))) (+ (+ 0 (+ 0 (+ 0 (+ (ch1/cc 3 0) (ch1/cc 2 1))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 6 0) (ch1/cc 5 1))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 2 0) (ch1/cc 1 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 5 0) (ch1/cc 4 1)))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 1 0) (ch1/cc 0 1))))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 4 0) (ch1/cc 3 1))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 3 0) (ch1/cc 2 1)))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 2 0) (ch1/cc 1 1))))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ (ch1/cc 1 0) (ch1/cc 0 1)))))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1))))))))))) (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 1)))))) (+ (+ 0 1) 0))) (+ (+ (+ 0 1) 0) 0)) 0) 0) (+ (+ (+ (+ 1 (+ 1 1)) 1) 0) 0) 4])))) (deftest ex15-test (is (= 6 ;; ex 1.15.a: sine is called 6 times ;; ex 1.15.b: N reduces by a factor of 3 each time, and the ;; process gains one stack frame per reduction, which is a ;; logarithmic rate; thus it requires O(log N) stack space, ;; performing O(log N) steps. (+ 1 ;; (sine 12.15) 1 ;; (p (sine 4.05)) 1 ;; (p (p (sine 1.3499999999999999))) 1 ;; (p (p (p (sine 0.44999999999999996)))) 1 ;; (p (p (p (p (sine 0.15))))) 1 ;; (p (p (p (p (p (sine 0.049999999999999996)))))) ))) (is (= (ch1/sine 12.15) (ch1/p (ch1/p (ch1/p (ch1/p (ch1/p (ch1/sine 0.049999999999999996))))))))) (deftest ex16-test (dotimes [n 10] (dotimes [m 10] (is (= (ch1/fast-expt n m) (ch1/fast-expt-iter n m)))))) (deftest ex17-test (dotimes [n 10] (dotimes [m 10] (is (= (* n m) (ch1/fast-* n m)))))) (deftest ex18-test (doseq [n (range 10)] (doseq [m (range 10)] (is (= (* n m) (ch1/fast-*-iter n m)))))) (deftest ex19-test (doseq [n (range 92)] (is (= (ch1/fib-iter n) (ch1/fib n))))) (deftest ex20-test ;; Applicative order evaluation: 4 remainder operations (is (= (ch1/gcd 206 40) (ch1/gcd 40 6) ;; (mod 206 40) => 6 (ch1/gcd 6 4) ;; (mod 40 6) => 4 (ch1/gcd 4 2) ;; (mod 6 4) => 2 (ch1/gcd 2 0) ;; (mod 4 2) => 0 2)) ;; Normal order evaluation: 21 remainder operations (is (= (ch1/gcd 206 40) (ch1/gcd 40 (mod 206 40)) (ch1/gcd (mod 206 40) (mod 40 (mod 206 40))) (ch1/gcd (mod 40 (mod 206 40)) (mod (mod 206 40) (mod 40 (mod 206 40)))) (ch1/gcd (mod (mod 206 40) (mod 40 (mod 206 40))) (mod (mod 40 (mod 206 40)) (mod (mod 206 40) (mod 40 (mod 206 40)))))))) (deftest ex21-test (is (= 199 (ch1/smallest-divisor 199))) (is (= 1999 (ch1/smallest-divisor 1999))) (is (= 7 (ch1/smallest-divisor 19999)))) (deftest ex22-test ;; These results suggest prime? runtime is proportional to O(sqrt n), ;; and that the runtime in general is proportional to the number of ;; computational steps. (is (<= (Math/abs (- (/ (apply min (ch1/prime-runtimes-between 999990 1000010)) (apply min (ch1/prime-runtimes-between 99990 100010))) (Math/sqrt 10))) 4)) (is (<= (Math/abs (- (/ (apply min (ch1/prime-runtimes-between 99990 100010)) (apply min (ch1/prime-runtimes-between 9990 10010))) (Math/sqrt 10))) 8)) (is (<= (Math/abs (- (/ (apply min (ch1/prime-runtimes-between 9990 10010)) (apply min (ch1/prime-runtimes-between 990 1010))) (Math/sqrt 10))) 16))) (comment (deftest ex23-test ;; The tests I ran showed speedups by factors ranging from 0.6 to ;; 0.8. However, repeated tests resulted in identical runtimes -- I ;; assume the JIT compiler optimized the checks similarly. ;; The runtimes are oddly variable, with either version occasionally ;; taking 4-8x longer than the other. This can cause the test to ;; fail randomly, so it's not really a good test. Because of that, ;; I've commented out the block. (is (<= (/ (ch1/profile (fn [] (ch1/prime-2? 199)) 100000) (ch1/profile (fn [] (ch1/prime? 199)) 100000)) 1)) (is (<= (/ (ch1/profile (fn [] (ch1/prime-2? 1999)) 100000) (ch1/profile (fn [] (ch1/prime? 1999)) 100000)) 1)) (is (<= (/ (ch1/profile (fn [] (ch1/prime-2? 19999)) 100000) (ch1/profile (fn [] (ch1/prime? 19999)) 100000)) 1)))) (deftest ex24-test ;; The results suggest fast-prime? runtime is proportional to O(lg n) (is (<= (Math/abs (- (/ (apply min (ch1/fast-prime-runtimes-between 999990 1000010)) (apply min (ch1/fast-prime-runtimes-between 99990 100010))) (Math/log 10))) 4)) (is (<= (Math/abs (- (/ (apply min (ch1/fast-prime-runtimes-between 99990 100010)) (apply min (ch1/fast-prime-runtimes-between 9990 10010))) (Math/log 10))) 4)) (is (<= (Math/abs (- (/ (apply min (ch1/fast-prime-runtimes-between 9990 10010)) (apply min (ch1/fast-prime-runtimes-between 990 1010))) (Math/log 10))) 4))) (deftest ex25-test ;; The naive method of computing b^e then taking that modulo m will ;; result in extremely large integers, overflowing the primitive ;; types. While this is not an issue when the numbers are already ;; larger than the primitive types, it does mean computations will ;; be significantly slower since even ones that can be done with ;; only primitives must be promoted to a bigint type. (try (ch1/bad-expmod 200 200 200) (catch ArithmeticException e (is (= (.getMessage e) "integer overflow")))) (is (= 0 (ch1/exp-mod 200 200 200)))) (deftest ex26-test (let [order (ch1/average-slope-order #(ch1/linear-expmod 2 % 7) 25)] ;; The order of growth has exponent 1, i.e. O(N); when the input ;; size doubles, the runtime also doubles. This is because, while ;; the (quot e 2) clause in linear-expmod does logarithmically ;; reduce the number of cases to run, that case is run twice since ;; it's called twice in the manual * clause (instead of once, were ;; the square function used). So, while there are O(log N) steps, ;; each step has the pattern for 2^N calls to linear-expmod, ;; resulting in O(2^(lg N)) = O(N) calls. (is (= 1 order)))) (def carmichael-numbers [561 1105 1729 2465 2821 6601]) (deftest ex27-test (doseq [PI:NAME:<NAME>END_PI carmichael-numbers] (is (ch1/fast-prime? carmichael 5)) (is (ch1/mod-prime? carmichael)))) (deftest ex28-test (doseq [PI:NAME:<NAME>END_PImichael carmichael-numbers] (is (not (ch1/miller-rabin-prime? carmichael 5)))) (let [data (range 2 100)] (is (= (map ch1/prime? data) (map #(ch1/miller-rabin-prime? % 7) data))))) (deftest ex29-test (is (<= (Math/abs (- (ch1/simpsons-rule ch1/cube 0 1 100) 0.25)) (Math/abs (- (ch1/integral ch1/cube 0 1 0.01) 0.25)))) (is (<= (Math/abs (- (ch1/simpsons-rule ch1/cube 0 1 1000) 0.25)) (Math/abs (- (ch1/integral ch1/cube 0 1 0.001) 0.25))))) (deftest ex30-test (is (= (ch1/sum-cubes 1 10) (ch1/sum-recursive ch1/cube 1 inc 10)))) (deftest ex31-a-test (letfn [(error [n] (Math/abs (- (ch1/approximate-pi n) Math/PI)))] (is (< (error 1024) (error 512) (error 256) (error 128) (error 64) (error 32) (error 16) (error 8))))) (deftest ex31-b-test (is (= (ch1/factorial 10) (ch1/product-recursive identity 1 inc 10)))) (deftest ex32-a-test (is (= (ch1/sum-cubes 1 10) (ch1/accumulate-sum ch1/cube 1 inc 10))) (is (= (ch1/factorial 10) (ch1/accumulate-product identity 1 inc 10)))) (deftest ex32-b-test (is (= (ch1/accumulate + 0 ch1/cube 1 inc 10) (ch1/accumulate-recursive + 0 ch1/cube 1 inc 10))) (is (= (ch1/accumulate * 1 identity 1 inc 10) (ch1/accumulate-recursive * 1 identity 1 inc 10)))) (deftest ex33-a-test (let [N 100] (is (= (ch1/sum-prime-squares 1 N) (transduce (comp (filter ch1/prime?) (map ch1/square)) + 0 (range (inc N))))))) (deftest ex33-b-test (let [N 20] (is (= (ch1/product-relatively-prime-ints N) (transduce (filter (partial ch1/relatively-prime? N)) * 1 (range 1 (inc N))))))) (deftest ex34-test (letfn [(f [g] (g 2))] (is (= 4 (f ch1/square))) (is (= 6 (f (fn [z] (* z (inc z)))))) ;; (f f) = (f 2) = (2 2); 2 is not an IFn, so a ClassCastException ;; is thrown. (try (f f) (catch Throwable e (is (= java.lang.ClassCastException (class e))))))) (deftest ex35-test (is (ch1/close-enough? ch1/phi (/ (inc (Math/sqrt 5)) 2)))) (deftest ex36-test (is (= "f(5.0000000000) = 4.2920296742 f(4.2920296742) = 4.7418631199 f(4.7418631199) = 4.4382045698 f(4.4382045698) = 4.6352998871 f(4.6352998871) = 4.5039781161 f(4.5039781161) = 4.5899894627 f(4.5899894627) = 4.5330115077 f(4.5330115077) = 4.5704756729 f(4.5704756729) = 4.5457203897 f(4.5457203897) = 4.5620249366 f(4.5620249366) = 4.5512632341 f(4.5512632341) = 4.5583563877 f(4.5583563877) = 4.5536768522 f(4.5536768522) = 4.5567621643 f(4.5567621643) = 4.5547271307 f(4.5547271307) = 4.5560690548 f(4.5560690548) = 4.5551840188 f(4.5551840188) = 4.5557676565 f(4.5557676565) = 4.5553827466 f(4.5553827466) = 4.5556365824 f(4.5556365824) = 4.5554691802 f(4.5554691802) = 4.5555795779 f(4.5555795779) = 4.5555067723 f(4.5555067723) = 4.5555547860 f(4.5555547860) = 4.5555231218 f(4.5555231218) = 4.5555440037 f(4.5555440037) = 4.5555302325 f(4.5555302325) = 4.5555393144 f(4.5555393144) = 4.5555333250 f(4.5555333250) = 4.5555372749 f(4.5555372749) = 4.5555346700 f(4.5555346700) = 4.5555363879 f(4.5555363879) = 4.5555352550 f(4.5555352550) = 4.5555360021 " (with-out-str (ch1/fixed-point-showing-work (fn [x] (/ (Math/log 1000) (Math/log x))) 5)))) (is (= 34 (ch1/number-of-steps-for-fixed-point (fn [x] (/ (Math/log 1000) (Math/log x))) 5))) ;; Note that with average dampening, the number of steps is ;; significantly reduced. (is (= 9 (ch1/number-of-steps-for-fixed-point (fn [x] (ch1/average x (/ (Math/log 1000) (Math/log x)))) 5)))) (deftest ex37-a-test ;; k must be at least 10 to have 4 decimal places of accuracy. (letfn [(close-enough? [a b] (< (ch1/abs (- a b)) 0.0001))] (is (close-enough? (/ 1 ch1/phi) (ch1/cont-frac (constantly 1) (constantly 1) 10))))) (deftest ex37-b-test (is (= (ch1/cont-frac (constantly 1) (constantly 1) 10) (ch1/cont-frac-recursive (constantly 1) (constantly 1) 10)))) (deftest ex38-test (is (= Math/E ch1/e))) (deftest ex39-test (letfn [(close-enough? [a b] (< (ch1/abs (- a b)) 0.000000001)) (tan [x] (double (ch1/tan-cf x 100)))] (is (close-enough? (Math/tan 0) (tan 0))) (is (close-enough? (Math/tan 1) (tan 1))) (is (close-enough? (Math/tan Math/PI) (tan Math/PI))) (is (close-enough? (Math/tan (* 2 Math/PI)) (tan (* 2 Math/PI)))))) (deftest ex40-test (is (ch1/close-enough? 0 (ch1/newtons-method (ch1/cubic 0 0 0) 1))) (is (ch1/close-enough? -2 (ch1/newtons-method (ch1/cubic 0 0 8) 1))) (is (ch1/close-enough? -2.1325 (ch1/newtons-method (ch1/cubic 2 3 7) 1)))) (deftest ex41-test (is (= 2 ((ch1/double inc) 0))) (is (= 13 ((ch1/double inc) 11)))) (deftest ex42-test (is (= 49 ((ch1/compose ch1/square inc) 6)))) (deftest ex43-test (is (= 625 ((ch1/repeated ch1/square 2) 5))) (is (= 10 ((ch1/repeated inc 10) 0))) (is (= 11 ((ch1/repeated inc 11) 0))) (is (= 625 ((ch1/repeated-fast ch1/square 2) 5))) (is (= 10 ((ch1/repeated-fast inc 10) 0))) (is (= 11 ((ch1/repeated-fast inc 11) 0)))) (deftest ex44-test (is (= 1.0 ((ch1/smooth inc) 0))) (is (= (/ (+ (ch1/square (- 2 ch1/dx)) 4 (ch1/square (+ 2 ch1/dx))) 3) ((ch1/smooth ch1/square) 2))) (is (= ((ch1/smooth (ch1/smooth (ch1/smooth ch1/square))) 2) ((ch1/n-smooth ch1/square 3) 2)))) (deftest ex45-test (is (ch1/close-enough? 2 (ch1/nth-root 4 2))) (is (ch1/close-enough? 2 (ch1/nth-root 8 3))) (is (ch1/close-enough? 2 (ch1/nth-root 16 4))) (is (ch1/close-enough? 2 (ch1/nth-root 32 5))) (is (ch1/close-enough? 2 (ch1/nth-root 64 6))) (is (ch1/close-enough? 2 (ch1/nth-root 128 7))) (is (ch1/close-enough? 2 (ch1/nth-root 256 8))) (is (ch1/close-enough? 2 (ch1/nth-root 512 9))) (is (ch1/close-enough? 2 (ch1/nth-root 1024 10)))) (deftest ex46-test (doseq [x [2 4 8 16 32 64 128 256 512]] (is (ch1/close-enough? (ch1/sqrt-via-average-damp x) (ch1/sqrt-via-iterative-improve x 1.0)))) (doseq [x [2 4 8 16 32 64 128 256 512]] (let [f (fn [y] (ch1/average y (/ x y)))] (is (ch1/close-enough? (ch1/fixed-point f 1.0) (ch1/fixed-point-via-iterative-improve f 1.0))))))
[ { "context": "- Project definition \n\n; Copyright (c) 2014 - 2020 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 88, "score": 0.9998579621315002, "start": 74, "tag": "NAME", "value": "Burkhardt Renz" }, { "context": " is not available as a maven jar\n; compile github/esb-dev/ltl2buchi and put the ltl2buchi.jar into your loc", "end": 1503, "score": 0.9985440969467163, "start": 1496, "tag": "USERNAME", "value": "esb-dev" } ]
project.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Project definition ; Copyright (c) 2014 - 2020 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. ; Remember: update rev and date in consts.clj too (defproject lwb "2.2.4" :date "2021-06-29" :description "lwb Logic WorkBench" :url "http://esb-dev.github.io/lwb.html" :scm {:name "git" :url "https://github.com/esb-lwb/lwb"} :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.10.3"] [org.clojure/spec.alpha "0.2.194"] [org.clojure/core.specs.alpha "0.2.56"] [org.clojure/core.logic "1.0.0"] [net.mikera/core.matrix "0.62.0"] [org.clojure/tools.macro "0.1.5"] [org.clojure/math.combinatorics "0.1.6"] [org.clojure/math.numeric-tower "0.0.4"] [potemkin "0.4.5"] [org.ow2.sat4j/org.ow2.sat4j.core "2.3.6"] [de.fosd.typechef/javabdd_repackaged_2.10 "0.1"] [ltl2buchi/ltl2buchi "1.0.0"] [kodkod/kodkod "2.1.0"]] :jvm-opts ["-Xms2G"] :uberjar-name "lwb.jar") ; ltl2buchi is not available as a maven jar ; compile github/esb-dev/ltl2buchi and put the ltl2buchi.jar into your local maven repo ; lein localrepo install ltl2buchi.jar ltl2buchi 1.0.0 ; kodkod is not available as a maven jar ; download kodkod.jar from http://emina.github.io/kodkod/ ; lein localrepo install kodkod.jar kodkod 2.1.0
34966
; lwb Logic WorkBench -- Project definition ; Copyright (c) 2014 - 2020 <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. ; Remember: update rev and date in consts.clj too (defproject lwb "2.2.4" :date "2021-06-29" :description "lwb Logic WorkBench" :url "http://esb-dev.github.io/lwb.html" :scm {:name "git" :url "https://github.com/esb-lwb/lwb"} :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.10.3"] [org.clojure/spec.alpha "0.2.194"] [org.clojure/core.specs.alpha "0.2.56"] [org.clojure/core.logic "1.0.0"] [net.mikera/core.matrix "0.62.0"] [org.clojure/tools.macro "0.1.5"] [org.clojure/math.combinatorics "0.1.6"] [org.clojure/math.numeric-tower "0.0.4"] [potemkin "0.4.5"] [org.ow2.sat4j/org.ow2.sat4j.core "2.3.6"] [de.fosd.typechef/javabdd_repackaged_2.10 "0.1"] [ltl2buchi/ltl2buchi "1.0.0"] [kodkod/kodkod "2.1.0"]] :jvm-opts ["-Xms2G"] :uberjar-name "lwb.jar") ; ltl2buchi is not available as a maven jar ; compile github/esb-dev/ltl2buchi and put the ltl2buchi.jar into your local maven repo ; lein localrepo install ltl2buchi.jar ltl2buchi 1.0.0 ; kodkod is not available as a maven jar ; download kodkod.jar from http://emina.github.io/kodkod/ ; lein localrepo install kodkod.jar kodkod 2.1.0
true
; lwb Logic WorkBench -- Project definition ; Copyright (c) 2014 - 2020 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. ; Remember: update rev and date in consts.clj too (defproject lwb "2.2.4" :date "2021-06-29" :description "lwb Logic WorkBench" :url "http://esb-dev.github.io/lwb.html" :scm {:name "git" :url "https://github.com/esb-lwb/lwb"} :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.10.3"] [org.clojure/spec.alpha "0.2.194"] [org.clojure/core.specs.alpha "0.2.56"] [org.clojure/core.logic "1.0.0"] [net.mikera/core.matrix "0.62.0"] [org.clojure/tools.macro "0.1.5"] [org.clojure/math.combinatorics "0.1.6"] [org.clojure/math.numeric-tower "0.0.4"] [potemkin "0.4.5"] [org.ow2.sat4j/org.ow2.sat4j.core "2.3.6"] [de.fosd.typechef/javabdd_repackaged_2.10 "0.1"] [ltl2buchi/ltl2buchi "1.0.0"] [kodkod/kodkod "2.1.0"]] :jvm-opts ["-Xms2G"] :uberjar-name "lwb.jar") ; ltl2buchi is not available as a maven jar ; compile github/esb-dev/ltl2buchi and put the ltl2buchi.jar into your local maven repo ; lein localrepo install ltl2buchi.jar ltl2buchi 1.0.0 ; kodkod is not available as a maven jar ; download kodkod.jar from http://emina.github.io/kodkod/ ; lein localrepo install kodkod.jar kodkod 2.1.0
[ { "context": "940518bb379ae9c962a7d\",\n :username \"username\",\n :session \"4fb56c501d3340d398bb8d", "end": 1173, "score": 0.9995751976966858, "start": 1165, "tag": "USERNAME", "value": "username" }, { "context": " :header\n {:msg_id \"e93eb6ef140940518bb379ae9c962a7d\",\n :username \"username\",\n ", "end": 3202, "score": 0.8306567668914795, "start": 3182, "tag": "KEY", "value": "40518bb379ae9c962a7d" }, { "context": "518bb379ae9c962a7d\",\n :username \"username\",\n :session \"4fb56c501d3340d398b", "end": 3242, "score": 0.9996187090873718, "start": 3234, "tag": "USERNAME", "value": "username" }, { "context": "0518bb379ae9c962a7d\",\n :username \"username\",\n :session \"4fb56c501d3340d398bb", "end": 5019, "score": 0.9996597766876221, "start": 5011, "tag": "USERNAME", "value": "username" } ]
test/clojupyter/kernel/middleware/execute_test.clj
Pilloxa/clojupyter
0
(ns clojupyter.kernel.middleware.execute-test (:require [midje.sweet :refer [before fact with-state-changes =>]] [nrepl.core :as nrepl] ,, [clojupyter.kernel.init :as init] [clojupyter.kernel.middleware :as M] [clojupyter.kernel.state :as state] [clojupyter.kernel.cljsrv.nrepl-server :as clojupyter-nrepl-server] [clojupyter.kernel.cljsrv.nrepl-comm :as nrepl-comm] ,, [clojupyter.kernel.transport-test :as TT])) ;;; ---------------------------------------------------------------------------------------------------- ;;; BASIC EVALUATION ;;; ---------------------------------------------------------------------------------------------------- (def EXE-MSG {:envelope [(byte-array [52, 102, 98, 53, 54, 99, 53, 48, 49, 100, 51, 51, 52, 48, 100, 51, 57, 56, 98, 98, 56, 100, 51, 55, 52, 50, 99, 100, 57, 101, 53, 48])], :delimiter "<IDS|MSG>", :signature "5a98d552a77da7f1595030a8771f4ef861a5ca406d13b1001d4acfa7a58ace88", :header {:msg_id "e93eb6ef140940518bb379ae9c962a7d", :username "username", :session "4fb56c501d3340d398bb8d3742cd9e50", :msg_type "execute_request", :version "5.2"}, :parent-header {}, :content {:code "(+ 1 2 3)", :silent false, :store_history true, :user_expressions {}, :allow_stdin true, :stop_on_error true}}) (with-state-changes [(before :facts (init/init-global-state!))] (fact "execute_request yields execute_input and execute_result on iopub and execute_reply on :req" (with-open [nrepl-server (clojupyter-nrepl-server/start-nrepl-server) nrepl-conn (nrepl/connect :port (:port nrepl-server))] (let [nrepl-comm (nrepl-comm/make-nrepl-comm nrepl-server nrepl-conn) H ((comp M/wrapin-bind-msgtype M/wrap-base-handlers) TT/UNHANDLED) ctx (TT/test-ctx {:nrepl-comm nrepl-comm} EXE-MSG) hist0 (count (state/get-history))] (H ctx) [(let [sent (-> ctx :transport TT/sent)] (mapv (partial get-in sent) [[:iopub 0 :msgtype] [:iopub 0 :message :code] [:iopub 1 :msgtype] [:iopub 1 :message :data] [:req 0 :msgtype] [:req 0 :message :status]])) (- (count (state/get-history)) hist0)])) => [["execute_input" "(+ 1 2 3)" "execute_result" {:text/plain "6"} "execute_reply" "ok"] 1])) ;;; ---------------------------------------------------------------------------------------------------- ;;; SILENT ;;; ---------------------------------------------------------------------------------------------------- (def SILENT-MSG {:envelope [(byte-array [52, 102, 98])], :delimiter "<IDS|MSG>", :signature "5a98d552a77da7f1595030a8771f4ef861a5ca406d13b1001d4acfa7a58ace88", :header {:msg_id "e93eb6ef140940518bb379ae9c962a7d", :username "username", :session "4fb56c501d3340d398bb8d3742cd9e50", :msg_type "execute_request", :version "5.2"}, :parent-header {}, :content {:code "(+ 1 2 3)", :silent true, :store_history true, :user_expressions {}, :allow_stdin true, :stop_on_error true}}) (with-state-changes [(before :facts (init/init-global-state!))] (fact "silent execute_request is respect" (with-open [nrepl-server (clojupyter-nrepl-server/start-nrepl-server) nrepl-conn (nrepl/connect :port (:port nrepl-server))] (let [nrepl-comm (nrepl-comm/make-nrepl-comm nrepl-server nrepl-conn) H ((comp M/wrapin-bind-msgtype M/wrap-base-handlers) TT/UNHANDLED) ctx (TT/test-ctx {:nrepl-comm nrepl-comm} SILENT-MSG)] (H ctx) (let [sent (-> ctx :transport TT/sent)] (mapv (partial get-in sent) [[:req 0 :msgtype] [:req 0 :message :status] [:iopub]])))) => ["execute_reply" "ok" nil])) ;;; ---------------------------------------------------------------------------------------------------- ;;; EMPTY CODE STRING ;;; ---------------------------------------------------------------------------------------------------- (def EMPTY-MSG {:envelope [(byte-array [52, 102, 98])], :delimiter "<IDS|MSG>", :signature "5a98d552a77da7f1595030a8771f4ef861a5ca406d13b1001d4acfa7a58ace88", :header {:msg_id "e93eb6ef140940518bb379ae9c962a7d", :username "username", :session "4fb56c501d3340d398bb8d3742cd9e50", :msg_type "execute_request", :version "5.2"}, :parent-header {}, :content {:code "", :silent true, :store_history true, :user_expressions {}, :allow_stdin true, :stop_on_error true}}) (with-state-changes [(before :facts (init/init-global-state!))] (fact "execute_request with empty `code` string and silent `true` yields execute counter without updating it" (with-open [nrepl-server (clojupyter-nrepl-server/start-nrepl-server) nrepl-conn (nrepl/connect :port (:port nrepl-server))] (let [nrepl-comm (nrepl-comm/make-nrepl-comm nrepl-server nrepl-conn) H ((comp M/wrapin-bind-msgtype M/wrap-base-handlers) TT/UNHANDLED) ctx (TT/test-ctx {:nrepl-comm nrepl-comm} EMPTY-MSG) hist0 (count (state/get-history))] (do ;; send empty message twice to verify the execution counter is not updated (H ctx) (H ctx)) [(let [sent (-> ctx :transport TT/sent)] (mapv (partial get-in sent) [[:req 0 :msgtype] [:req 0 :message :execution_count] [:req 1 :msgtype] [:req 1 :message :execution_count] [:iopub]])) (- hist0 (count (state/get-history)))])) => [["execute_reply" 1N "execute_reply" 1N nil] 0]))
113447
(ns clojupyter.kernel.middleware.execute-test (:require [midje.sweet :refer [before fact with-state-changes =>]] [nrepl.core :as nrepl] ,, [clojupyter.kernel.init :as init] [clojupyter.kernel.middleware :as M] [clojupyter.kernel.state :as state] [clojupyter.kernel.cljsrv.nrepl-server :as clojupyter-nrepl-server] [clojupyter.kernel.cljsrv.nrepl-comm :as nrepl-comm] ,, [clojupyter.kernel.transport-test :as TT])) ;;; ---------------------------------------------------------------------------------------------------- ;;; BASIC EVALUATION ;;; ---------------------------------------------------------------------------------------------------- (def EXE-MSG {:envelope [(byte-array [52, 102, 98, 53, 54, 99, 53, 48, 49, 100, 51, 51, 52, 48, 100, 51, 57, 56, 98, 98, 56, 100, 51, 55, 52, 50, 99, 100, 57, 101, 53, 48])], :delimiter "<IDS|MSG>", :signature "5a98d552a77da7f1595030a8771f4ef861a5ca406d13b1001d4acfa7a58ace88", :header {:msg_id "e93eb6ef140940518bb379ae9c962a7d", :username "username", :session "4fb56c501d3340d398bb8d3742cd9e50", :msg_type "execute_request", :version "5.2"}, :parent-header {}, :content {:code "(+ 1 2 3)", :silent false, :store_history true, :user_expressions {}, :allow_stdin true, :stop_on_error true}}) (with-state-changes [(before :facts (init/init-global-state!))] (fact "execute_request yields execute_input and execute_result on iopub and execute_reply on :req" (with-open [nrepl-server (clojupyter-nrepl-server/start-nrepl-server) nrepl-conn (nrepl/connect :port (:port nrepl-server))] (let [nrepl-comm (nrepl-comm/make-nrepl-comm nrepl-server nrepl-conn) H ((comp M/wrapin-bind-msgtype M/wrap-base-handlers) TT/UNHANDLED) ctx (TT/test-ctx {:nrepl-comm nrepl-comm} EXE-MSG) hist0 (count (state/get-history))] (H ctx) [(let [sent (-> ctx :transport TT/sent)] (mapv (partial get-in sent) [[:iopub 0 :msgtype] [:iopub 0 :message :code] [:iopub 1 :msgtype] [:iopub 1 :message :data] [:req 0 :msgtype] [:req 0 :message :status]])) (- (count (state/get-history)) hist0)])) => [["execute_input" "(+ 1 2 3)" "execute_result" {:text/plain "6"} "execute_reply" "ok"] 1])) ;;; ---------------------------------------------------------------------------------------------------- ;;; SILENT ;;; ---------------------------------------------------------------------------------------------------- (def SILENT-MSG {:envelope [(byte-array [52, 102, 98])], :delimiter "<IDS|MSG>", :signature "5a98d552a77da7f1595030a8771f4ef861a5ca406d13b1001d4acfa7a58ace88", :header {:msg_id "e93eb6ef1409<KEY>", :username "username", :session "4fb56c501d3340d398bb8d3742cd9e50", :msg_type "execute_request", :version "5.2"}, :parent-header {}, :content {:code "(+ 1 2 3)", :silent true, :store_history true, :user_expressions {}, :allow_stdin true, :stop_on_error true}}) (with-state-changes [(before :facts (init/init-global-state!))] (fact "silent execute_request is respect" (with-open [nrepl-server (clojupyter-nrepl-server/start-nrepl-server) nrepl-conn (nrepl/connect :port (:port nrepl-server))] (let [nrepl-comm (nrepl-comm/make-nrepl-comm nrepl-server nrepl-conn) H ((comp M/wrapin-bind-msgtype M/wrap-base-handlers) TT/UNHANDLED) ctx (TT/test-ctx {:nrepl-comm nrepl-comm} SILENT-MSG)] (H ctx) (let [sent (-> ctx :transport TT/sent)] (mapv (partial get-in sent) [[:req 0 :msgtype] [:req 0 :message :status] [:iopub]])))) => ["execute_reply" "ok" nil])) ;;; ---------------------------------------------------------------------------------------------------- ;;; EMPTY CODE STRING ;;; ---------------------------------------------------------------------------------------------------- (def EMPTY-MSG {:envelope [(byte-array [52, 102, 98])], :delimiter "<IDS|MSG>", :signature "5a98d552a77da7f1595030a8771f4ef861a5ca406d13b1001d4acfa7a58ace88", :header {:msg_id "e93eb6ef140940518bb379ae9c962a7d", :username "username", :session "4fb56c501d3340d398bb8d3742cd9e50", :msg_type "execute_request", :version "5.2"}, :parent-header {}, :content {:code "", :silent true, :store_history true, :user_expressions {}, :allow_stdin true, :stop_on_error true}}) (with-state-changes [(before :facts (init/init-global-state!))] (fact "execute_request with empty `code` string and silent `true` yields execute counter without updating it" (with-open [nrepl-server (clojupyter-nrepl-server/start-nrepl-server) nrepl-conn (nrepl/connect :port (:port nrepl-server))] (let [nrepl-comm (nrepl-comm/make-nrepl-comm nrepl-server nrepl-conn) H ((comp M/wrapin-bind-msgtype M/wrap-base-handlers) TT/UNHANDLED) ctx (TT/test-ctx {:nrepl-comm nrepl-comm} EMPTY-MSG) hist0 (count (state/get-history))] (do ;; send empty message twice to verify the execution counter is not updated (H ctx) (H ctx)) [(let [sent (-> ctx :transport TT/sent)] (mapv (partial get-in sent) [[:req 0 :msgtype] [:req 0 :message :execution_count] [:req 1 :msgtype] [:req 1 :message :execution_count] [:iopub]])) (- hist0 (count (state/get-history)))])) => [["execute_reply" 1N "execute_reply" 1N nil] 0]))
true
(ns clojupyter.kernel.middleware.execute-test (:require [midje.sweet :refer [before fact with-state-changes =>]] [nrepl.core :as nrepl] ,, [clojupyter.kernel.init :as init] [clojupyter.kernel.middleware :as M] [clojupyter.kernel.state :as state] [clojupyter.kernel.cljsrv.nrepl-server :as clojupyter-nrepl-server] [clojupyter.kernel.cljsrv.nrepl-comm :as nrepl-comm] ,, [clojupyter.kernel.transport-test :as TT])) ;;; ---------------------------------------------------------------------------------------------------- ;;; BASIC EVALUATION ;;; ---------------------------------------------------------------------------------------------------- (def EXE-MSG {:envelope [(byte-array [52, 102, 98, 53, 54, 99, 53, 48, 49, 100, 51, 51, 52, 48, 100, 51, 57, 56, 98, 98, 56, 100, 51, 55, 52, 50, 99, 100, 57, 101, 53, 48])], :delimiter "<IDS|MSG>", :signature "5a98d552a77da7f1595030a8771f4ef861a5ca406d13b1001d4acfa7a58ace88", :header {:msg_id "e93eb6ef140940518bb379ae9c962a7d", :username "username", :session "4fb56c501d3340d398bb8d3742cd9e50", :msg_type "execute_request", :version "5.2"}, :parent-header {}, :content {:code "(+ 1 2 3)", :silent false, :store_history true, :user_expressions {}, :allow_stdin true, :stop_on_error true}}) (with-state-changes [(before :facts (init/init-global-state!))] (fact "execute_request yields execute_input and execute_result on iopub and execute_reply on :req" (with-open [nrepl-server (clojupyter-nrepl-server/start-nrepl-server) nrepl-conn (nrepl/connect :port (:port nrepl-server))] (let [nrepl-comm (nrepl-comm/make-nrepl-comm nrepl-server nrepl-conn) H ((comp M/wrapin-bind-msgtype M/wrap-base-handlers) TT/UNHANDLED) ctx (TT/test-ctx {:nrepl-comm nrepl-comm} EXE-MSG) hist0 (count (state/get-history))] (H ctx) [(let [sent (-> ctx :transport TT/sent)] (mapv (partial get-in sent) [[:iopub 0 :msgtype] [:iopub 0 :message :code] [:iopub 1 :msgtype] [:iopub 1 :message :data] [:req 0 :msgtype] [:req 0 :message :status]])) (- (count (state/get-history)) hist0)])) => [["execute_input" "(+ 1 2 3)" "execute_result" {:text/plain "6"} "execute_reply" "ok"] 1])) ;;; ---------------------------------------------------------------------------------------------------- ;;; SILENT ;;; ---------------------------------------------------------------------------------------------------- (def SILENT-MSG {:envelope [(byte-array [52, 102, 98])], :delimiter "<IDS|MSG>", :signature "5a98d552a77da7f1595030a8771f4ef861a5ca406d13b1001d4acfa7a58ace88", :header {:msg_id "e93eb6ef1409PI:KEY:<KEY>END_PI", :username "username", :session "4fb56c501d3340d398bb8d3742cd9e50", :msg_type "execute_request", :version "5.2"}, :parent-header {}, :content {:code "(+ 1 2 3)", :silent true, :store_history true, :user_expressions {}, :allow_stdin true, :stop_on_error true}}) (with-state-changes [(before :facts (init/init-global-state!))] (fact "silent execute_request is respect" (with-open [nrepl-server (clojupyter-nrepl-server/start-nrepl-server) nrepl-conn (nrepl/connect :port (:port nrepl-server))] (let [nrepl-comm (nrepl-comm/make-nrepl-comm nrepl-server nrepl-conn) H ((comp M/wrapin-bind-msgtype M/wrap-base-handlers) TT/UNHANDLED) ctx (TT/test-ctx {:nrepl-comm nrepl-comm} SILENT-MSG)] (H ctx) (let [sent (-> ctx :transport TT/sent)] (mapv (partial get-in sent) [[:req 0 :msgtype] [:req 0 :message :status] [:iopub]])))) => ["execute_reply" "ok" nil])) ;;; ---------------------------------------------------------------------------------------------------- ;;; EMPTY CODE STRING ;;; ---------------------------------------------------------------------------------------------------- (def EMPTY-MSG {:envelope [(byte-array [52, 102, 98])], :delimiter "<IDS|MSG>", :signature "5a98d552a77da7f1595030a8771f4ef861a5ca406d13b1001d4acfa7a58ace88", :header {:msg_id "e93eb6ef140940518bb379ae9c962a7d", :username "username", :session "4fb56c501d3340d398bb8d3742cd9e50", :msg_type "execute_request", :version "5.2"}, :parent-header {}, :content {:code "", :silent true, :store_history true, :user_expressions {}, :allow_stdin true, :stop_on_error true}}) (with-state-changes [(before :facts (init/init-global-state!))] (fact "execute_request with empty `code` string and silent `true` yields execute counter without updating it" (with-open [nrepl-server (clojupyter-nrepl-server/start-nrepl-server) nrepl-conn (nrepl/connect :port (:port nrepl-server))] (let [nrepl-comm (nrepl-comm/make-nrepl-comm nrepl-server nrepl-conn) H ((comp M/wrapin-bind-msgtype M/wrap-base-handlers) TT/UNHANDLED) ctx (TT/test-ctx {:nrepl-comm nrepl-comm} EMPTY-MSG) hist0 (count (state/get-history))] (do ;; send empty message twice to verify the execution counter is not updated (H ctx) (H ctx)) [(let [sent (-> ctx :transport TT/sent)] (mapv (partial get-in sent) [[:req 0 :msgtype] [:req 0 :message :execution_count] [:req 1 :msgtype] [:req 1 :message :execution_count] [:iopub]])) (- hist0 (count (state/get-history)))])) => [["execute_reply" 1N "execute_reply" 1N nil] 0]))
[ { "context": ";;\n;;\n;; Copyright 2013 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 28, "score": 0.941811740398407, "start": 25, "tag": "NAME", "value": "Net" } ]
src/test/clojure/pigpen/set_test.clj
magomimmo/PigPen
1
;; ;; ;; Copyright 2013 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.set-test (:use clojure.test) (:require [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]] [pigpen.raw :as raw] [pigpen.set :as pig])) (deftest test-split-opts-relations (is (= (#'pigpen.set/split-opts-relations [{:o1 1 :o2 2} {:id 1, :type :load} {:id 2, :type :load} {:id 3, :type :load}]) [{:o1 1 :o2 2} [{:id 1, :type :load} {:id 2, :type :load} {:id 3, :type :load}]]))) (deftest test-pig-intersection (is (= #{1} (pig/pig-intersection [1 1 1] [1 1] [1 1 1]))) (is (= #{1} (pig/pig-intersection [1 1 1] [1 1] [1 1 1]))) (is (= #{1} (pig/pig-intersection [1 1 1])))) (deftest test-pig-intersection-multiset (is (= [1 1] (pig/pig-intersection-multiset [1 1 1] [1 1]))) (is (= [] (pig/pig-intersection-multiset [1 1 1] [] [1 1]))) (is (= [1 1 1] (pig/pig-intersection-multiset [1 1 1])))) (deftest test-pig-difference (is (= #{} (pig/pig-difference [1 1 1] [1 1] [1 1 1]))) (is (= #{1} (pig/pig-difference [1 1 1] [] []))) (is (= #{1} (pig/pig-difference [1 1 1])))) (deftest test-pig-difference-multiset (is (= [1] (pig/pig-difference-multiset [1 1 1 1] [1 1] [1]))) (is (= [1 1] (pig/pig-difference-multiset [1 1 1] [] [1]))) (is (= [1 1 1] (pig/pig-difference-multiset [1 1 1])))) (deftest test-distinct (with-redefs [pigpen.raw/pigsym pigsym-zero] (let [r {:fields '[value]}] (test-diff (pig/distinct {:parallel 20} r) '{:type :distinct :id distinct0 :description nil :ancestors [{:fields [value]}] :fields [value] :field-type :frozen :opts {:type :distinct-opts :parallel 20}})))) (deftest test-union (with-redefs [pigpen.raw/pigsym pigsym-zero] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/union r0 r1) '{:type :distinct :id distinct0 :description nil :ancestors [{:type :union :id union0 :description nil :fields [value] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :union-opts}}] :fields [value] :field-type :frozen :opts {:type :distinct-opts}}) (test-diff (pig/union {:parallel 20} r0 r1) '{:type :distinct :id distinct0 :description nil :ancestors [{:type :union :id union0 :description nil :fields [value] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :union-opts}}] :fields [value] :field-type :frozen :opts {:type :distinct-opts :parallel 20}})))) (deftest test-union-multiset (with-redefs [pigpen.raw/pigsym pigsym-zero] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/union-multiset r0 r1) '{:type :union :id union0 :description nil :fields [value] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :union-opts}})))) (deftest test-intersection (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/intersection {:parallel 20} r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-intersection) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts :parallel 20}}]})))) (deftest test-intersection-multiset (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/intersection-multiset r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-intersection-multiset) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts}}]})))) (deftest test-difference (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/difference r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-difference) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts}}]})))) (deftest test-difference-multiset (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/difference-multiset r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-difference-multiset) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts}}]}))))
56670
;; ;; ;; Copyright 2013 <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.set-test (:use clojure.test) (:require [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]] [pigpen.raw :as raw] [pigpen.set :as pig])) (deftest test-split-opts-relations (is (= (#'pigpen.set/split-opts-relations [{:o1 1 :o2 2} {:id 1, :type :load} {:id 2, :type :load} {:id 3, :type :load}]) [{:o1 1 :o2 2} [{:id 1, :type :load} {:id 2, :type :load} {:id 3, :type :load}]]))) (deftest test-pig-intersection (is (= #{1} (pig/pig-intersection [1 1 1] [1 1] [1 1 1]))) (is (= #{1} (pig/pig-intersection [1 1 1] [1 1] [1 1 1]))) (is (= #{1} (pig/pig-intersection [1 1 1])))) (deftest test-pig-intersection-multiset (is (= [1 1] (pig/pig-intersection-multiset [1 1 1] [1 1]))) (is (= [] (pig/pig-intersection-multiset [1 1 1] [] [1 1]))) (is (= [1 1 1] (pig/pig-intersection-multiset [1 1 1])))) (deftest test-pig-difference (is (= #{} (pig/pig-difference [1 1 1] [1 1] [1 1 1]))) (is (= #{1} (pig/pig-difference [1 1 1] [] []))) (is (= #{1} (pig/pig-difference [1 1 1])))) (deftest test-pig-difference-multiset (is (= [1] (pig/pig-difference-multiset [1 1 1 1] [1 1] [1]))) (is (= [1 1] (pig/pig-difference-multiset [1 1 1] [] [1]))) (is (= [1 1 1] (pig/pig-difference-multiset [1 1 1])))) (deftest test-distinct (with-redefs [pigpen.raw/pigsym pigsym-zero] (let [r {:fields '[value]}] (test-diff (pig/distinct {:parallel 20} r) '{:type :distinct :id distinct0 :description nil :ancestors [{:fields [value]}] :fields [value] :field-type :frozen :opts {:type :distinct-opts :parallel 20}})))) (deftest test-union (with-redefs [pigpen.raw/pigsym pigsym-zero] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/union r0 r1) '{:type :distinct :id distinct0 :description nil :ancestors [{:type :union :id union0 :description nil :fields [value] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :union-opts}}] :fields [value] :field-type :frozen :opts {:type :distinct-opts}}) (test-diff (pig/union {:parallel 20} r0 r1) '{:type :distinct :id distinct0 :description nil :ancestors [{:type :union :id union0 :description nil :fields [value] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :union-opts}}] :fields [value] :field-type :frozen :opts {:type :distinct-opts :parallel 20}})))) (deftest test-union-multiset (with-redefs [pigpen.raw/pigsym pigsym-zero] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/union-multiset r0 r1) '{:type :union :id union0 :description nil :fields [value] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :union-opts}})))) (deftest test-intersection (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/intersection {:parallel 20} r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-intersection) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts :parallel 20}}]})))) (deftest test-intersection-multiset (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/intersection-multiset r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-intersection-multiset) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts}}]})))) (deftest test-difference (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/difference r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-difference) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts}}]})))) (deftest test-difference-multiset (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/difference-multiset r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-difference-multiset) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts}}]}))))
true
;; ;; ;; Copyright 2013 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.set-test (:use clojure.test) (:require [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]] [pigpen.raw :as raw] [pigpen.set :as pig])) (deftest test-split-opts-relations (is (= (#'pigpen.set/split-opts-relations [{:o1 1 :o2 2} {:id 1, :type :load} {:id 2, :type :load} {:id 3, :type :load}]) [{:o1 1 :o2 2} [{:id 1, :type :load} {:id 2, :type :load} {:id 3, :type :load}]]))) (deftest test-pig-intersection (is (= #{1} (pig/pig-intersection [1 1 1] [1 1] [1 1 1]))) (is (= #{1} (pig/pig-intersection [1 1 1] [1 1] [1 1 1]))) (is (= #{1} (pig/pig-intersection [1 1 1])))) (deftest test-pig-intersection-multiset (is (= [1 1] (pig/pig-intersection-multiset [1 1 1] [1 1]))) (is (= [] (pig/pig-intersection-multiset [1 1 1] [] [1 1]))) (is (= [1 1 1] (pig/pig-intersection-multiset [1 1 1])))) (deftest test-pig-difference (is (= #{} (pig/pig-difference [1 1 1] [1 1] [1 1 1]))) (is (= #{1} (pig/pig-difference [1 1 1] [] []))) (is (= #{1} (pig/pig-difference [1 1 1])))) (deftest test-pig-difference-multiset (is (= [1] (pig/pig-difference-multiset [1 1 1 1] [1 1] [1]))) (is (= [1 1] (pig/pig-difference-multiset [1 1 1] [] [1]))) (is (= [1 1 1] (pig/pig-difference-multiset [1 1 1])))) (deftest test-distinct (with-redefs [pigpen.raw/pigsym pigsym-zero] (let [r {:fields '[value]}] (test-diff (pig/distinct {:parallel 20} r) '{:type :distinct :id distinct0 :description nil :ancestors [{:fields [value]}] :fields [value] :field-type :frozen :opts {:type :distinct-opts :parallel 20}})))) (deftest test-union (with-redefs [pigpen.raw/pigsym pigsym-zero] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/union r0 r1) '{:type :distinct :id distinct0 :description nil :ancestors [{:type :union :id union0 :description nil :fields [value] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :union-opts}}] :fields [value] :field-type :frozen :opts {:type :distinct-opts}}) (test-diff (pig/union {:parallel 20} r0 r1) '{:type :distinct :id distinct0 :description nil :ancestors [{:type :union :id union0 :description nil :fields [value] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :union-opts}}] :fields [value] :field-type :frozen :opts {:type :distinct-opts :parallel 20}})))) (deftest test-union-multiset (with-redefs [pigpen.raw/pigsym pigsym-zero] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/union-multiset r0 r1) '{:type :union :id union0 :description nil :fields [value] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :union-opts}})))) (deftest test-intersection (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/intersection {:parallel 20} r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-intersection) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts :parallel 20}}]})))) (deftest test-intersection-multiset (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/intersection-multiset r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-intersection-multiset) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts}}]})))) (deftest test-difference (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/difference r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-difference) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts}}]})))) (deftest test-difference-multiset (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (let [r0 '{:id r0, :type :load, :fields [value]} r1 '{:id r1, :type :load, :fields [value]}] (test-diff (pig/difference-multiset r0 r1) '{:type :bind :id bind2 :description nil :func (pigpen.pig/mapcat->bind pigpen.set/pig-difference-multiset) :args [[[r0] value] [[r1] value]] :requires [pigpen.set] :fields [value] :field-type-in :frozen :field-type-out :frozen :opts {:type :bind-opts} :ancestors [{:type :group :id group1 :description nil :keys [[value] [value]] :join-types [:optional :optional] :fields [group [[r0] value] [[r1] value]] :field-type :frozen :ancestors [{:id r0, :type :load, :fields [value]} {:id r1, :type :load, :fields [value]}] :opts {:type :group-opts}}]}))))
[ { "context": "1\")))))\n\n(def web-token (auth/generate-web-token 12345 1000 false \"qa@artstor.org\"))\n\n;REPL/unit test op", "end": 1206, "score": 0.6096714735031128, "start": 1202, "tag": "PASSWORD", "value": "2345" }, { "context": "-token (auth/generate-web-token 12345 1000 false \"qa@artstor.org\"))\n\n;REPL/unit test option-- [#schema.core.Option", "end": 1233, "score": 0.9999081492424011, "start": 1219, "tag": "EMAIL", "value": "qa@artstor.org" }, { "context": "ssid\"\n (let [_ (spit \"simulatedimage.png\" \"Iwannahippopatamousforchristmas\")\n my-i", "end": 8177, "score": 0.5405036807060242, "start": 8175, "tag": "USERNAME", "value": "Iw" }, { "context": "\n (let [_ (spit \"simulatedimage.png\" \"Iwannahippopatamousforchristmas\")\n my-image (io/f", "end": 8187, "score": 0.5280073285102844, "start": 8180, "tag": "USERNAME", "value": "ahippop" }, { "context": "let [_ (spit \"simulatedimage.png\" \"Iwannahippopatamousforchristmas\")\n my-image (io/file \"si", "end": 8194, "score": 0.507714569568634, "start": 8190, "tag": "USERNAME", "value": "mous" }, { "context": "ices-login (fn [] {:status 200, :body {:username \"pc@artstor.org\"}})\n http/put (fn [_ _] {:stat", "end": 8918, "score": 0.9999215006828308, "start": 8904, "tag": "EMAIL", "value": "pc@artstor.org" }, { "context": " :body \"{\\\"assets\\\": [{\\\"fd_68602_s\\\":\\\"Mr Pumpkin\\\", \\\"id\\\": 1234567890, \\\"created_by\\\": 123456, \\\"", "end": 9281, "score": 0.9195432662963867, "start": 9271, "tag": "NAME", "value": "Mr Pumpkin" }, { "context": " :metadata [{:field_id \"fd_68602_s\", :value \"Mr Pumpkin\"}\n ", "end": 9942, "score": 0.9847777485847473, "start": 9932, "tag": "NAME", "value": "Mr Pumpkin" }, { "context": " {:field_id \"fd_68619_s\", :value \"Pumpkin\"}]}])\n response (app (-> (mock/reque", "end": 10051, "score": 0.7989081144332886, "start": 10044, "tag": "NAME", "value": "Pumpkin" }, { "context": " :metadata [{:field_id \"fd_68602_s\", :value \"Mr Pumpkin\"}\n ", "end": 10945, "score": 0.6851059198379517, "start": 10939, "tag": "NAME", "value": "umpkin" }, { "context": " (mock/header \"fastly-client-ip\" \"38.66.77.2\")))]\n (is (= (:status response) 200))\n ", "end": 12034, "score": 0.9961850047111511, "start": 12024, "tag": "IP_ADDRESS", "value": "38.66.77.2" }, { "context": " (mock/header \"fastly-client-ip\" \"38.66.77.2\")))]\n (is (= (:status response) 200))\n ", "end": 12840, "score": 0.9996193647384644, "start": 12830, "tag": "IP_ADDRESS", "value": "38.66.77.2" }, { "context": " (mock/header \"fastly-client-ip\" \"38.66.77.2\")))]\n (is (= (:status response) 400))\n ", "end": 13534, "score": 0.9996280670166016, "start": 13524, "tag": "IP_ADDRESS", "value": "38.66.77.2" }, { "context": " (mock/header \"fastly-client-ip\" \"38.66.77.2\")))]\n (is (= (:status response) 200))\n ", "end": 14366, "score": 0.9994513392448425, "start": 14356, "tag": "IP_ADDRESS", "value": "38.66.77.2" } ]
test/artstor_collection_service_os/core_test.clj
ithaka/artstor-collection-service-os
0
(ns artstor-collection-service-os.core-test (:require [artstor-collection-service-os.forum :as forum] [artstor-collection-service-os.auth :as auth] [artstor-collection-service-os.core :as core] [artstor-collection-service-os.repository :as repo] [artstor-collection-service-os.tokens :as tokens] [artstor-collection-service-os.conf :refer [config-file]] [clojure.test :refer :all] [clojure.test.check.clojure-test :refer [defspec]] [clojure.tools.logging :as logger] [ragtime.jdbc :as rag] [ragtime.repl :refer [migrate rollback]] [ring.mock.request :as mock] [peridot.core :as peridot] [clojure.java.io :as io] [cheshire.core :as cheshire] [clj-http.client :as http])) (def config {:datastore (rag/sql-database {:connection-uri (config-file :artstor-ccollection-db-url)}) :migrations (rag/load-resources "test-migrations")}) (defmacro with-db [conf & body] `(do (migrate ~conf) (try ~@body (finally (rollback ~conf "001"))))) (def web-token (auth/generate-web-token 12345 1000 false "qa@artstor.org")) ;REPL/unit test option-- [#schema.core.OptionalKey{:k :tempfile} java.io.File] (deftest personal-collection-image-upload (let [app core/app file {:filename "BillsFunFile.png" :content-type "image/png" :size 1234}] (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] {:success true :id "123456012"}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test invalid parameters image upload" (let [response (app (-> (mock/request :post "/api/v1/pcollection/image" ) (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 400))))) (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] {:success true :id "123456012"}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test not authorized to upload" (let [response (app (-> (mock/request :post "/api/v1/pcollection/image")))] (is (= (:status response) 401))))) ;;Uses peridot instead of mock to generate multipart/form-data (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] (do (println "uploading file redef....") {:success true :id "123456012"})) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test good image upload" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image" :request-method :post :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))))) (deftest personal-collection-image-upload-handle-long-number (let [app core/app file {:filename "BillsFunFile.png" :content-type "image/png" :size 1234}] ;;Uses peridot instead of mock to generate multipart/form-data (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] (do (println "uploading file redef....") {:success true :id "123456012789"})) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test good image upload" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image" :request-method :post :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))))) (deftest personal-collection-image-delete (let [app core/app] (with-redefs [forum/delete-images-from-personal-collection (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test delete image from personal collection - single image" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=123456789") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)))) (testing "Test delete image from personal collection - single image with long number ssid" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=123456012789") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)))) (testing "Test delete image from personal collection - multiple images" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=123456789&object_ids=123456780") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)))) (testing "Test delete image from personal collection - no image" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=") "web-token" web-token)))] (is (= (:status response) 400))))))) (deftest personal-collection-media-replace (let [app core/app file {:filename "tmpimages.jpeg" :content-type "image/jpeg" :size 1234}] (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] {:success true :id "123456012"}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test invalid parameters image upload" (let [response (app (-> (mock/request :put "/api/v1/pcollection/image/123456012") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 400))))) (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] {:success true :id "123456012"})] (testing "Test not authorized to upload" (let [response (app (-> (mock/request :put "/api/v1/pcollection/image/123456012" )))] (is (= (:status response) 401))))) ;;Uses peridot instead of mock to generate multipart/form-data (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] (do (println "updating media redef....") {:success true :id "123456012"})) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test good image replacement" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image/123456012" :request-method :put :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))) (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] (do (println "updating media redef for long ssid....") {:success true :id "123456012789"})) logger/log* (fn [_ _ _ message] (println "Test Log Message for long ssid=" message))] (testing "Test good image replacement for long ssid" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image/123456012789" :request-method :put :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))))) (deftest update-personal-collection-image-metadata (let [app core/app] (testing "Test update image metadata for personal collection - single image" (with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "pc@artstor.org"}}) http/put (fn [_ _] {:status 200, :headers {"Server" "gunicorn/19.0.0", "Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"}, :body "{\"assets\": [{\"fd_68602_s\":\"Mr Pumpkin\", \"id\": 1234567890, \"created_by\": 123456, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"}) forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true}) forum/publish-asset-at-forum (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [request-data (cheshire/generate-string [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "Mr Pumpkin"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]) response (app (-> (mock/request :post "/api/v1/pcollection/image/metadata" request-data) (mock/content-type "application/json") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= (body :success)))))) (testing "Test update image metadata for personal collection - log post body when 500" (with-redefs [forum/update-multiple-images-metadata (fn [_ _] {:success false}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [request-data (cheshire/generate-string [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "Mr Pumpkin"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]) response (app (-> (mock/request :post "/api/v1/pcollection/image/metadata" request-data) (mock/content-type "application/json") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 500)) (is (= "An error occurred uploading personal collection metadata" (body :error)))))))) (deftest cors-options-test (with-redefs [forum/update-multiple-images-metadata (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "Options call returns CORS headers" (let [response (app (-> (mock/header (mock/request :options "/api/v1/pcollection/image/metadata") "origin" "weird-domain") (mock/header "fastly-client-ip" "38.66.77.2")))] (is (= (:status response) 200)) (is (= (get (:headers response) "Access-Control-Allow-Origin") "weird-domain")) (is (= (get (:headers response) "Access-Control-Allow-Methods") "GET, POST, PUT, DELETE, OPTIONS"))))))) (deftest cors-post-options-test (with-redefs [forum/update-multiple-images-metadata (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "POST call does not return CORS headers" (let [response (app (-> (mock/header (mock/request :post "/api/v1/pcollection/image/metadata") "origin" "weird-domain") (mock/header "web-token" web-token) (mock/header "fastly-client-ip" "38.66.77.2")))] (is (= (:status response) 200)) (is (= (not (contains? (:headers response) "Access-Control-Allow-Origin")))) (is (= (not (contains? (:headers response) "Access-Control-Allow-Methods"))))))))) (deftest cors-put-options-test (with-redefs [logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "PUT call returns CORS headers" (let [response (app (-> (mock/header (mock/request :put "/api/v1/pcollection/image/1234") "origin" "totally-not-nefarious") (mock/header "web-token" web-token) (mock/header "fastly-client-ip" "38.66.77.2")))] (is (= (:status response) 400)) (is (= (get (:headers response) "Access-Control-Allow-Origin") "totally-not-nefarious")) (is (= (get (:headers response) "Access-Control-Allow-Methods") "GET, POST, PUT, DELETE, OPTIONS"))))))) (deftest cors-delete-options-test (with-redefs [forum/delete-images-from-personal-collection (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "DELETE call returns CORS headers" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=12345") "origin" "totally-not-nefarious") (mock/header "web-token" web-token) (mock/header "fastly-client-ip" "38.66.77.2")))] (is (= (:status response) 200)) (is (= (get (:headers response) "Access-Control-Allow-Origin") "totally-not-nefarious")) (is (= (get (:headers response) "Access-Control-Allow-Methods") "GET, POST, PUT, DELETE, OPTIONS"))))))) (deftest personal-collection-image-status (let [app core/app] (with-redefs [repo/process-records (fn [_] 123) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] ["obj1"]) repo/record-ready? (fn [_] true) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/123") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:status body) :message "OK")))))) (with-redefs [repo/process-records (fn [_] nil) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] []) repo/record-ready? (fn [_] false) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status by passing invalid ssid" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/12356") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:error body) :code "500")))))))) (deftest test-get-category-description (with-redefs [logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (with-db config (testing "Test get category description when valid category 123456789" (let [response (app (-> (mock/request :get "/api/v1/categorydesc/123456789") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= 123456789 (body :id))) (is (= "Test Image Description 1" (body :imageDesc))) (is (= "/path-to-image-url/filename1.jpg" (body :imageUrl))) (is (= "<html> <p>Testing html Blurb Url 1<br><A HREF=\"http://www.artstor.org\">artstor1</A></p></html>" (body :blurbUrl))) (is (= "Testing Short Description 1" (body :shortDescription))) (is (= "OBJ1" (body :leadObjectId))) (is (= "Test Category Name 1" (body :name))))) (testing "Test get category description when valid category 987654321" (let [response (app (-> (mock/request :get "/api/v1/categorydesc/987654321") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= 987654321 (body :id))) (is (= "Test Image Description 2" (body :imageDesc))) (is (= "/path-to-image-url/filename2.jpg" (body :imageUrl))) (is (= "<html> <p>Testing html Blurb Url 2<br><A HREF=\"http://www.artstor.org\">artstor2</A></p></html>" (body :blurbUrl))) (is (= "Testing Short Description 2" (body :shortDescription))) (is (= "OBJ2" (body :leadObjectId))) (is (= "Test Category Name 2" (body :name))))) (testing "Test get category description when invalid long category id" (let [response (app (-> (mock/request :get "/api/v1/categorydesc/111111111") (mock/header "web-token" web-token)))] (is (= (:status response) 404)) (is (= "Category Id Unavailable" (:body response))))) (testing "Test get category description when invalid category with " (let [response (app (-> (mock/request :get "/api/v1/categorydesc/11111aaaa") (mock/header "web-token" web-token)))] (is (= (:status response) 400)))))))) (deftest personal-collection-image-status (let [app core/app] (with-redefs [repo/process-records (fn [_] 123) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] ["obj1"]) repo/record-ready? (fn [_] true) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/123") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:status body) :message "OK")))))) (with-redefs [repo/process-records (fn [_] nil) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] []) repo/record-ready? (fn [_] false) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status by passing invalid ssid" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/12356") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:error body) :code "500"))))))))
84249
(ns artstor-collection-service-os.core-test (:require [artstor-collection-service-os.forum :as forum] [artstor-collection-service-os.auth :as auth] [artstor-collection-service-os.core :as core] [artstor-collection-service-os.repository :as repo] [artstor-collection-service-os.tokens :as tokens] [artstor-collection-service-os.conf :refer [config-file]] [clojure.test :refer :all] [clojure.test.check.clojure-test :refer [defspec]] [clojure.tools.logging :as logger] [ragtime.jdbc :as rag] [ragtime.repl :refer [migrate rollback]] [ring.mock.request :as mock] [peridot.core :as peridot] [clojure.java.io :as io] [cheshire.core :as cheshire] [clj-http.client :as http])) (def config {:datastore (rag/sql-database {:connection-uri (config-file :artstor-ccollection-db-url)}) :migrations (rag/load-resources "test-migrations")}) (defmacro with-db [conf & body] `(do (migrate ~conf) (try ~@body (finally (rollback ~conf "001"))))) (def web-token (auth/generate-web-token 1<PASSWORD> 1000 false "<EMAIL>")) ;REPL/unit test option-- [#schema.core.OptionalKey{:k :tempfile} java.io.File] (deftest personal-collection-image-upload (let [app core/app file {:filename "BillsFunFile.png" :content-type "image/png" :size 1234}] (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] {:success true :id "123456012"}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test invalid parameters image upload" (let [response (app (-> (mock/request :post "/api/v1/pcollection/image" ) (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 400))))) (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] {:success true :id "123456012"}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test not authorized to upload" (let [response (app (-> (mock/request :post "/api/v1/pcollection/image")))] (is (= (:status response) 401))))) ;;Uses peridot instead of mock to generate multipart/form-data (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] (do (println "uploading file redef....") {:success true :id "123456012"})) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test good image upload" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image" :request-method :post :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))))) (deftest personal-collection-image-upload-handle-long-number (let [app core/app file {:filename "BillsFunFile.png" :content-type "image/png" :size 1234}] ;;Uses peridot instead of mock to generate multipart/form-data (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] (do (println "uploading file redef....") {:success true :id "123456012789"})) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test good image upload" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image" :request-method :post :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))))) (deftest personal-collection-image-delete (let [app core/app] (with-redefs [forum/delete-images-from-personal-collection (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test delete image from personal collection - single image" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=123456789") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)))) (testing "Test delete image from personal collection - single image with long number ssid" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=123456012789") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)))) (testing "Test delete image from personal collection - multiple images" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=123456789&object_ids=123456780") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)))) (testing "Test delete image from personal collection - no image" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=") "web-token" web-token)))] (is (= (:status response) 400))))))) (deftest personal-collection-media-replace (let [app core/app file {:filename "tmpimages.jpeg" :content-type "image/jpeg" :size 1234}] (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] {:success true :id "123456012"}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test invalid parameters image upload" (let [response (app (-> (mock/request :put "/api/v1/pcollection/image/123456012") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 400))))) (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] {:success true :id "123456012"})] (testing "Test not authorized to upload" (let [response (app (-> (mock/request :put "/api/v1/pcollection/image/123456012" )))] (is (= (:status response) 401))))) ;;Uses peridot instead of mock to generate multipart/form-data (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] (do (println "updating media redef....") {:success true :id "123456012"})) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test good image replacement" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image/123456012" :request-method :put :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))) (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] (do (println "updating media redef for long ssid....") {:success true :id "123456012789"})) logger/log* (fn [_ _ _ message] (println "Test Log Message for long ssid=" message))] (testing "Test good image replacement for long ssid" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image/123456012789" :request-method :put :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))))) (deftest update-personal-collection-image-metadata (let [app core/app] (testing "Test update image metadata for personal collection - single image" (with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "<EMAIL>"}}) http/put (fn [_ _] {:status 200, :headers {"Server" "gunicorn/19.0.0", "Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"}, :body "{\"assets\": [{\"fd_68602_s\":\"<NAME>\", \"id\": 1234567890, \"created_by\": 123456, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"}) forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true}) forum/publish-asset-at-forum (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [request-data (cheshire/generate-string [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "<NAME>"} {:field_id "fd_68619_s", :value "<NAME>"}]}]) response (app (-> (mock/request :post "/api/v1/pcollection/image/metadata" request-data) (mock/content-type "application/json") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= (body :success)))))) (testing "Test update image metadata for personal collection - log post body when 500" (with-redefs [forum/update-multiple-images-metadata (fn [_ _] {:success false}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [request-data (cheshire/generate-string [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "Mr P<NAME>"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]) response (app (-> (mock/request :post "/api/v1/pcollection/image/metadata" request-data) (mock/content-type "application/json") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 500)) (is (= "An error occurred uploading personal collection metadata" (body :error)))))))) (deftest cors-options-test (with-redefs [forum/update-multiple-images-metadata (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "Options call returns CORS headers" (let [response (app (-> (mock/header (mock/request :options "/api/v1/pcollection/image/metadata") "origin" "weird-domain") (mock/header "fastly-client-ip" "172.16.31.10")))] (is (= (:status response) 200)) (is (= (get (:headers response) "Access-Control-Allow-Origin") "weird-domain")) (is (= (get (:headers response) "Access-Control-Allow-Methods") "GET, POST, PUT, DELETE, OPTIONS"))))))) (deftest cors-post-options-test (with-redefs [forum/update-multiple-images-metadata (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "POST call does not return CORS headers" (let [response (app (-> (mock/header (mock/request :post "/api/v1/pcollection/image/metadata") "origin" "weird-domain") (mock/header "web-token" web-token) (mock/header "fastly-client-ip" "172.16.31.10")))] (is (= (:status response) 200)) (is (= (not (contains? (:headers response) "Access-Control-Allow-Origin")))) (is (= (not (contains? (:headers response) "Access-Control-Allow-Methods"))))))))) (deftest cors-put-options-test (with-redefs [logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "PUT call returns CORS headers" (let [response (app (-> (mock/header (mock/request :put "/api/v1/pcollection/image/1234") "origin" "totally-not-nefarious") (mock/header "web-token" web-token) (mock/header "fastly-client-ip" "172.16.31.10")))] (is (= (:status response) 400)) (is (= (get (:headers response) "Access-Control-Allow-Origin") "totally-not-nefarious")) (is (= (get (:headers response) "Access-Control-Allow-Methods") "GET, POST, PUT, DELETE, OPTIONS"))))))) (deftest cors-delete-options-test (with-redefs [forum/delete-images-from-personal-collection (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "DELETE call returns CORS headers" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=12345") "origin" "totally-not-nefarious") (mock/header "web-token" web-token) (mock/header "fastly-client-ip" "172.16.31.10")))] (is (= (:status response) 200)) (is (= (get (:headers response) "Access-Control-Allow-Origin") "totally-not-nefarious")) (is (= (get (:headers response) "Access-Control-Allow-Methods") "GET, POST, PUT, DELETE, OPTIONS"))))))) (deftest personal-collection-image-status (let [app core/app] (with-redefs [repo/process-records (fn [_] 123) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] ["obj1"]) repo/record-ready? (fn [_] true) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/123") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:status body) :message "OK")))))) (with-redefs [repo/process-records (fn [_] nil) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] []) repo/record-ready? (fn [_] false) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status by passing invalid ssid" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/12356") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:error body) :code "500")))))))) (deftest test-get-category-description (with-redefs [logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (with-db config (testing "Test get category description when valid category 123456789" (let [response (app (-> (mock/request :get "/api/v1/categorydesc/123456789") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= 123456789 (body :id))) (is (= "Test Image Description 1" (body :imageDesc))) (is (= "/path-to-image-url/filename1.jpg" (body :imageUrl))) (is (= "<html> <p>Testing html Blurb Url 1<br><A HREF=\"http://www.artstor.org\">artstor1</A></p></html>" (body :blurbUrl))) (is (= "Testing Short Description 1" (body :shortDescription))) (is (= "OBJ1" (body :leadObjectId))) (is (= "Test Category Name 1" (body :name))))) (testing "Test get category description when valid category 987654321" (let [response (app (-> (mock/request :get "/api/v1/categorydesc/987654321") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= 987654321 (body :id))) (is (= "Test Image Description 2" (body :imageDesc))) (is (= "/path-to-image-url/filename2.jpg" (body :imageUrl))) (is (= "<html> <p>Testing html Blurb Url 2<br><A HREF=\"http://www.artstor.org\">artstor2</A></p></html>" (body :blurbUrl))) (is (= "Testing Short Description 2" (body :shortDescription))) (is (= "OBJ2" (body :leadObjectId))) (is (= "Test Category Name 2" (body :name))))) (testing "Test get category description when invalid long category id" (let [response (app (-> (mock/request :get "/api/v1/categorydesc/111111111") (mock/header "web-token" web-token)))] (is (= (:status response) 404)) (is (= "Category Id Unavailable" (:body response))))) (testing "Test get category description when invalid category with " (let [response (app (-> (mock/request :get "/api/v1/categorydesc/11111aaaa") (mock/header "web-token" web-token)))] (is (= (:status response) 400)))))))) (deftest personal-collection-image-status (let [app core/app] (with-redefs [repo/process-records (fn [_] 123) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] ["obj1"]) repo/record-ready? (fn [_] true) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/123") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:status body) :message "OK")))))) (with-redefs [repo/process-records (fn [_] nil) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] []) repo/record-ready? (fn [_] false) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status by passing invalid ssid" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/12356") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:error body) :code "500"))))))))
true
(ns artstor-collection-service-os.core-test (:require [artstor-collection-service-os.forum :as forum] [artstor-collection-service-os.auth :as auth] [artstor-collection-service-os.core :as core] [artstor-collection-service-os.repository :as repo] [artstor-collection-service-os.tokens :as tokens] [artstor-collection-service-os.conf :refer [config-file]] [clojure.test :refer :all] [clojure.test.check.clojure-test :refer [defspec]] [clojure.tools.logging :as logger] [ragtime.jdbc :as rag] [ragtime.repl :refer [migrate rollback]] [ring.mock.request :as mock] [peridot.core :as peridot] [clojure.java.io :as io] [cheshire.core :as cheshire] [clj-http.client :as http])) (def config {:datastore (rag/sql-database {:connection-uri (config-file :artstor-ccollection-db-url)}) :migrations (rag/load-resources "test-migrations")}) (defmacro with-db [conf & body] `(do (migrate ~conf) (try ~@body (finally (rollback ~conf "001"))))) (def web-token (auth/generate-web-token 1PI:PASSWORD:<PASSWORD>END_PI 1000 false "PI:EMAIL:<EMAIL>END_PI")) ;REPL/unit test option-- [#schema.core.OptionalKey{:k :tempfile} java.io.File] (deftest personal-collection-image-upload (let [app core/app file {:filename "BillsFunFile.png" :content-type "image/png" :size 1234}] (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] {:success true :id "123456012"}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test invalid parameters image upload" (let [response (app (-> (mock/request :post "/api/v1/pcollection/image" ) (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 400))))) (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] {:success true :id "123456012"}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test not authorized to upload" (let [response (app (-> (mock/request :post "/api/v1/pcollection/image")))] (is (= (:status response) 401))))) ;;Uses peridot instead of mock to generate multipart/form-data (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] (do (println "uploading file redef....") {:success true :id "123456012"})) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test good image upload" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image" :request-method :post :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))))) (deftest personal-collection-image-upload-handle-long-number (let [app core/app file {:filename "BillsFunFile.png" :content-type "image/png" :size 1234}] ;;Uses peridot instead of mock to generate multipart/form-data (with-redefs [forum/upload-image-to-personal-collection (fn [_ _] (do (println "uploading file redef....") {:success true :id "123456012789"})) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test good image upload" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image" :request-method :post :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))))) (deftest personal-collection-image-delete (let [app core/app] (with-redefs [forum/delete-images-from-personal-collection (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test delete image from personal collection - single image" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=123456789") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)))) (testing "Test delete image from personal collection - single image with long number ssid" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=123456012789") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)))) (testing "Test delete image from personal collection - multiple images" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=123456789&object_ids=123456780") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)))) (testing "Test delete image from personal collection - no image" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=") "web-token" web-token)))] (is (= (:status response) 400))))))) (deftest personal-collection-media-replace (let [app core/app file {:filename "tmpimages.jpeg" :content-type "image/jpeg" :size 1234}] (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] {:success true :id "123456012"}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test invalid parameters image upload" (let [response (app (-> (mock/request :put "/api/v1/pcollection/image/123456012") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 400))))) (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] {:success true :id "123456012"})] (testing "Test not authorized to upload" (let [response (app (-> (mock/request :put "/api/v1/pcollection/image/123456012" )))] (is (= (:status response) 401))))) ;;Uses peridot instead of mock to generate multipart/form-data (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] (do (println "updating media redef....") {:success true :id "123456012"})) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test good image replacement" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image/123456012" :request-method :put :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))) (with-redefs [forum/update-media-in-personal-collection (fn [_ _ _] (do (println "updating media redef for long ssid....") {:success true :id "123456012789"})) logger/log* (fn [_ _ _ message] (println "Test Log Message for long ssid=" message))] (testing "Test good image replacement for long ssid" (let [_ (spit "simulatedimage.png" "Iwannahippopatamousforchristmas") my-image (io/file "simulatedimage.png") state-info (-> (peridot/session app) ;Use your ring app (peridot/header "web-token" web-token) (peridot/request "/api/v1/pcollection/image/123456012789" :request-method :put :params {:file my-image})) deleted (io/delete-file "simulatedimage.png" true)] (is (= ((state-info :response) :status) 200))))))) (deftest update-personal-collection-image-metadata (let [app core/app] (testing "Test update image metadata for personal collection - single image" (with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "PI:EMAIL:<EMAIL>END_PI"}}) http/put (fn [_ _] {:status 200, :headers {"Server" "gunicorn/19.0.0", "Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"}, :body "{\"assets\": [{\"fd_68602_s\":\"PI:NAME:<NAME>END_PI\", \"id\": 1234567890, \"created_by\": 123456, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"}) forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true}) forum/publish-asset-at-forum (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [request-data (cheshire/generate-string [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "PI:NAME:<NAME>END_PI"} {:field_id "fd_68619_s", :value "PI:NAME:<NAME>END_PI"}]}]) response (app (-> (mock/request :post "/api/v1/pcollection/image/metadata" request-data) (mock/content-type "application/json") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= (body :success)))))) (testing "Test update image metadata for personal collection - log post body when 500" (with-redefs [forum/update-multiple-images-metadata (fn [_ _] {:success false}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [request-data (cheshire/generate-string [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "Mr PPI:NAME:<NAME>END_PI"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]) response (app (-> (mock/request :post "/api/v1/pcollection/image/metadata" request-data) (mock/content-type "application/json") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 500)) (is (= "An error occurred uploading personal collection metadata" (body :error)))))))) (deftest cors-options-test (with-redefs [forum/update-multiple-images-metadata (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "Options call returns CORS headers" (let [response (app (-> (mock/header (mock/request :options "/api/v1/pcollection/image/metadata") "origin" "weird-domain") (mock/header "fastly-client-ip" "PI:IP_ADDRESS:172.16.31.10END_PI")))] (is (= (:status response) 200)) (is (= (get (:headers response) "Access-Control-Allow-Origin") "weird-domain")) (is (= (get (:headers response) "Access-Control-Allow-Methods") "GET, POST, PUT, DELETE, OPTIONS"))))))) (deftest cors-post-options-test (with-redefs [forum/update-multiple-images-metadata (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "POST call does not return CORS headers" (let [response (app (-> (mock/header (mock/request :post "/api/v1/pcollection/image/metadata") "origin" "weird-domain") (mock/header "web-token" web-token) (mock/header "fastly-client-ip" "PI:IP_ADDRESS:172.16.31.10END_PI")))] (is (= (:status response) 200)) (is (= (not (contains? (:headers response) "Access-Control-Allow-Origin")))) (is (= (not (contains? (:headers response) "Access-Control-Allow-Methods"))))))))) (deftest cors-put-options-test (with-redefs [logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "PUT call returns CORS headers" (let [response (app (-> (mock/header (mock/request :put "/api/v1/pcollection/image/1234") "origin" "totally-not-nefarious") (mock/header "web-token" web-token) (mock/header "fastly-client-ip" "PI:IP_ADDRESS:172.16.31.10END_PI")))] (is (= (:status response) 400)) (is (= (get (:headers response) "Access-Control-Allow-Origin") "totally-not-nefarious")) (is (= (get (:headers response) "Access-Control-Allow-Methods") "GET, POST, PUT, DELETE, OPTIONS"))))))) (deftest cors-delete-options-test (with-redefs [forum/delete-images-from-personal-collection (fn [_ _] {:success true}) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (testing "DELETE call returns CORS headers" (let [response (app (-> (mock/header (mock/request :delete "/api/v1/pcollection/image?ssids=12345") "origin" "totally-not-nefarious") (mock/header "web-token" web-token) (mock/header "fastly-client-ip" "PI:IP_ADDRESS:172.16.31.10END_PI")))] (is (= (:status response) 200)) (is (= (get (:headers response) "Access-Control-Allow-Origin") "totally-not-nefarious")) (is (= (get (:headers response) "Access-Control-Allow-Methods") "GET, POST, PUT, DELETE, OPTIONS"))))))) (deftest personal-collection-image-status (let [app core/app] (with-redefs [repo/process-records (fn [_] 123) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] ["obj1"]) repo/record-ready? (fn [_] true) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/123") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:status body) :message "OK")))))) (with-redefs [repo/process-records (fn [_] nil) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] []) repo/record-ready? (fn [_] false) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status by passing invalid ssid" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/12356") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:error body) :code "500")))))))) (deftest test-get-category-description (with-redefs [logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (let [app core/app] (with-db config (testing "Test get category description when valid category 123456789" (let [response (app (-> (mock/request :get "/api/v1/categorydesc/123456789") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= 123456789 (body :id))) (is (= "Test Image Description 1" (body :imageDesc))) (is (= "/path-to-image-url/filename1.jpg" (body :imageUrl))) (is (= "<html> <p>Testing html Blurb Url 1<br><A HREF=\"http://www.artstor.org\">artstor1</A></p></html>" (body :blurbUrl))) (is (= "Testing Short Description 1" (body :shortDescription))) (is (= "OBJ1" (body :leadObjectId))) (is (= "Test Category Name 1" (body :name))))) (testing "Test get category description when valid category 987654321" (let [response (app (-> (mock/request :get "/api/v1/categorydesc/987654321") (mock/header "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= 987654321 (body :id))) (is (= "Test Image Description 2" (body :imageDesc))) (is (= "/path-to-image-url/filename2.jpg" (body :imageUrl))) (is (= "<html> <p>Testing html Blurb Url 2<br><A HREF=\"http://www.artstor.org\">artstor2</A></p></html>" (body :blurbUrl))) (is (= "Testing Short Description 2" (body :shortDescription))) (is (= "OBJ2" (body :leadObjectId))) (is (= "Test Category Name 2" (body :name))))) (testing "Test get category description when invalid long category id" (let [response (app (-> (mock/request :get "/api/v1/categorydesc/111111111") (mock/header "web-token" web-token)))] (is (= (:status response) 404)) (is (= "Category Id Unavailable" (:body response))))) (testing "Test get category description when invalid category with " (let [response (app (-> (mock/request :get "/api/v1/categorydesc/11111aaaa") (mock/header "web-token" web-token)))] (is (= (:status response) 400)))))))) (deftest personal-collection-image-status (let [app core/app] (with-redefs [repo/process-records (fn [_] 123) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] ["obj1"]) repo/record-ready? (fn [_] true) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/123") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:status body) :message "OK")))))) (with-redefs [repo/process-records (fn [_] nil) tokens/get-eme-tokens (fn [_] []) repo/find-assets-solr (fn [_ _] []) repo/record-ready? (fn [_] false) logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))] (testing "Test poll for personal collection image status by passing invalid ssid" (let [response (app (-> (mock/header (mock/request :get "/api/v1/pcollection/image-status/12356") "web-token" web-token))) raw-body (slurp (:body response)) body (cheshire.core/parse-string raw-body true)] (is (= (:status response) 200)) (is (= ((:error body) :code "500"))))))))
[ { "context": "/region \"us-west-2\"\n :aws.creds/access-key \"AKIAIU3CQIP2EY643CTA\"\n :aws.creds/secret-key \"J8iCGik2Pg4Jw1mePx", "end": 3824, "score": 0.9996215105056763, "start": 3804, "tag": "KEY", "value": "AKIAIU3CQIP2EY643CTA" }, { "context": "IAIU3CQIP2EY643CTA\"\n :aws.creds/secret-key \"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\"}))\n\n\n (<run-and-report\n (compile-command\n ", "end": 3896, "score": 0.9997418522834778, "start": 3856, "tag": "KEY", "value": "J8iCGik2Pg4Jw1mePxYpZuwEG0RLRN0TbpGBAeY9" }, { "context": "egion \"us-west-2\"\n :aws.creds/access-key \"AKIAIU3CQIP2EY643CTA\"\n :aws.creds/secret-key \"J8iCGik2Pg4Jw1me", "end": 4608, "score": 0.9996123313903809, "start": 4588, "tag": "KEY", "value": "AKIAIU3CQIP2EY643CTA" }, { "context": "IU3CQIP2EY643CTA\"\n :aws.creds/secret-key \"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\"})))\n\n (<run-and-report [\"ls\" \"-aul\"])\n \n (prn", "end": 4682, "score": 0.9997726082801819, "start": 4642, "tag": "KEY", "value": "J8iCGik2Pg4Jw1mePxYpZuwEG0RLRN0TbpGBAeY9" } ]
src/cljs-node/rx/node/awsdeploy.cljs
zk/rx-lib
0
(ns rx.node.awsdeploy (:require [rx.kitchen-sink :as ks] [rx.node.aws :as aws] [rx.specs :as specs] [cljs.spec.alpha :as s] [cljs.core.async :as async :refer [put! <! close! chan] :refer-macros [go]])) (s/def :aws.lda/function-id :rx.specs/non-empty-string) (s/def :aws.lda/runtime-name :rx.specs/non-empty-string) (s/def :aws.lda/memory-mb #(and (nat-int? %) (>= % 128) (<= % 3008) (= 0 (mod % 64)))) (s/def :aws.lda/timeout-seconds nat-int?) (s/def :aws.lda/handler :rx.specs/non-empty-string) (s/def :aws.lda/role-arn :rx.specs/non-empty-string) (s/def :aws.lda/include-node-modules? boolean?) (s/def :aws.lda/clean-script vector?) (s/def :aws.lda/package-script vector?) (s/def :aws.lda/package-dir :rx.specs/non-empty-string) (s/def :aws.creds/region :rx.specs/non-empty-string) (s/def :aws.creds/access-key :rx.specs/non-empty-string) (s/def :aws.creds/secret-key :rx.specs/non-empty-string) (s/def :aws.lda/deploy-spec (s/keys :req [:aws.lda/function-id :aws.lda/runtime-name :aws.lda/memory-mb :aws.lda/timeout-seconds :aws.lda/handler :aws.lda/role-arn] :opt [:aws.lda/include-node-modules? :aws.lda/clean-script :aws.lda/package-script :aws.lda/package-dir :aws.creds/regtion :aws.creds/access-key :aws.creds/secret-key])) (def CP (js/require "child_process")) (defn <run-and-report [ss & [opts]] (println " * Running" ss) (let [ch (chan) proc (.spawn CP (first ss) (clj->js (rest ss)) (if opts (clj->js opts) #js {}))] (.on (.-stdout proc) "data" (fn [s] (print (.toString s)))) (.on (.-stderr proc) "data" (fn [s] (print (.toString s)))) (.on proc "close" (fn [exit-code] (put! ch exit-code) (close! ch))) ch)) (defn <exit-on-non-zero [in-fs] (go (loop [fs (remove nil? in-fs)] (when-not (empty? fs) (let [f (first fs) res (<! (f))] (if (= 0 res) (recur (rest fs)) (println "Non-zero return hit, aborting"))))))) (defn <run-deploy [{:keys [:aws.lda/clean-script :aws.lda/package-script :aws.lda/package-dir :aws.lda/include-node-modules?]}] (<exit-on-non-zero [(when clean-script #(<run-and-report clean-script)) (when package-script #(<run-and-report package-script)) #_(when include-node-modules? #(<run-and-report ["rsync" "-a" "--stats" "./node_modules" package-dir])) #_(when package-dir #(zip-package lfn-config))])) (defn compile-command [{:keys [:aws.lda/deps]}] ["clj" "-Sdeps" (pr-str deps) "--main" "cljs.main" "--compile" "evry.sync-server-lambda" "--target" "node" "--output-to" "test-out.js"]) (comment (<run-deploy (merge {:aws.lda/function-id :evry/ddb-sync-test :aws.lda/runtime-name "nodejs8.10" :aws.lda/memory-mb 512 :aws.lda/timeout-seconds 30 :aws.lda/handler "run.handler" :aws.lda/role-arn "arn:aws:iam::753209818049:role/lambda-exec" :aws.lda/include-node-modules? true :aws.lda/clean-script ["lein" "with-profile" "prod" "clean"] :aws.lda/package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "evry-sync-server-lambda"] :aws.lda/package-dir "target/prod/canter/apiserver"} {:aws.creds/region "us-west-2" :aws.creds/access-key "AKIAIU3CQIP2EY643CTA" :aws.creds/secret-key "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"})) (<run-and-report (compile-command (merge {:aws.lda/function-id :evry/ddb-sync-test :aws.lda/runtime-name "nodejs8.10" :aws.lda/memory-mb 512 :aws.lda/timeout-seconds 30 :aws.lda/handler "run.handler" :aws.lda/role-arn "arn:aws:iam::753209818049:role/lambda-exec" :aws.lda/include-node-modules? true :aws.lda/clean-script ["lein" "with-profile" "prod" "clean"] :aws.lda/package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "evry-sync-server-lambda"] :aws.lda/package-dir "target/prod/canter/apiserver"} {:aws.creds/region "us-west-2" :aws.creds/access-key "AKIAIU3CQIP2EY643CTA" :aws.creds/secret-key "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"}))) (<run-and-report ["ls" "-aul"]) (prn "hello world") )
17248
(ns rx.node.awsdeploy (:require [rx.kitchen-sink :as ks] [rx.node.aws :as aws] [rx.specs :as specs] [cljs.spec.alpha :as s] [cljs.core.async :as async :refer [put! <! close! chan] :refer-macros [go]])) (s/def :aws.lda/function-id :rx.specs/non-empty-string) (s/def :aws.lda/runtime-name :rx.specs/non-empty-string) (s/def :aws.lda/memory-mb #(and (nat-int? %) (>= % 128) (<= % 3008) (= 0 (mod % 64)))) (s/def :aws.lda/timeout-seconds nat-int?) (s/def :aws.lda/handler :rx.specs/non-empty-string) (s/def :aws.lda/role-arn :rx.specs/non-empty-string) (s/def :aws.lda/include-node-modules? boolean?) (s/def :aws.lda/clean-script vector?) (s/def :aws.lda/package-script vector?) (s/def :aws.lda/package-dir :rx.specs/non-empty-string) (s/def :aws.creds/region :rx.specs/non-empty-string) (s/def :aws.creds/access-key :rx.specs/non-empty-string) (s/def :aws.creds/secret-key :rx.specs/non-empty-string) (s/def :aws.lda/deploy-spec (s/keys :req [:aws.lda/function-id :aws.lda/runtime-name :aws.lda/memory-mb :aws.lda/timeout-seconds :aws.lda/handler :aws.lda/role-arn] :opt [:aws.lda/include-node-modules? :aws.lda/clean-script :aws.lda/package-script :aws.lda/package-dir :aws.creds/regtion :aws.creds/access-key :aws.creds/secret-key])) (def CP (js/require "child_process")) (defn <run-and-report [ss & [opts]] (println " * Running" ss) (let [ch (chan) proc (.spawn CP (first ss) (clj->js (rest ss)) (if opts (clj->js opts) #js {}))] (.on (.-stdout proc) "data" (fn [s] (print (.toString s)))) (.on (.-stderr proc) "data" (fn [s] (print (.toString s)))) (.on proc "close" (fn [exit-code] (put! ch exit-code) (close! ch))) ch)) (defn <exit-on-non-zero [in-fs] (go (loop [fs (remove nil? in-fs)] (when-not (empty? fs) (let [f (first fs) res (<! (f))] (if (= 0 res) (recur (rest fs)) (println "Non-zero return hit, aborting"))))))) (defn <run-deploy [{:keys [:aws.lda/clean-script :aws.lda/package-script :aws.lda/package-dir :aws.lda/include-node-modules?]}] (<exit-on-non-zero [(when clean-script #(<run-and-report clean-script)) (when package-script #(<run-and-report package-script)) #_(when include-node-modules? #(<run-and-report ["rsync" "-a" "--stats" "./node_modules" package-dir])) #_(when package-dir #(zip-package lfn-config))])) (defn compile-command [{:keys [:aws.lda/deps]}] ["clj" "-Sdeps" (pr-str deps) "--main" "cljs.main" "--compile" "evry.sync-server-lambda" "--target" "node" "--output-to" "test-out.js"]) (comment (<run-deploy (merge {:aws.lda/function-id :evry/ddb-sync-test :aws.lda/runtime-name "nodejs8.10" :aws.lda/memory-mb 512 :aws.lda/timeout-seconds 30 :aws.lda/handler "run.handler" :aws.lda/role-arn "arn:aws:iam::753209818049:role/lambda-exec" :aws.lda/include-node-modules? true :aws.lda/clean-script ["lein" "with-profile" "prod" "clean"] :aws.lda/package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "evry-sync-server-lambda"] :aws.lda/package-dir "target/prod/canter/apiserver"} {:aws.creds/region "us-west-2" :aws.creds/access-key "<KEY>" :aws.creds/secret-key "<KEY>"})) (<run-and-report (compile-command (merge {:aws.lda/function-id :evry/ddb-sync-test :aws.lda/runtime-name "nodejs8.10" :aws.lda/memory-mb 512 :aws.lda/timeout-seconds 30 :aws.lda/handler "run.handler" :aws.lda/role-arn "arn:aws:iam::753209818049:role/lambda-exec" :aws.lda/include-node-modules? true :aws.lda/clean-script ["lein" "with-profile" "prod" "clean"] :aws.lda/package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "evry-sync-server-lambda"] :aws.lda/package-dir "target/prod/canter/apiserver"} {:aws.creds/region "us-west-2" :aws.creds/access-key "<KEY>" :aws.creds/secret-key "<KEY>"}))) (<run-and-report ["ls" "-aul"]) (prn "hello world") )
true
(ns rx.node.awsdeploy (:require [rx.kitchen-sink :as ks] [rx.node.aws :as aws] [rx.specs :as specs] [cljs.spec.alpha :as s] [cljs.core.async :as async :refer [put! <! close! chan] :refer-macros [go]])) (s/def :aws.lda/function-id :rx.specs/non-empty-string) (s/def :aws.lda/runtime-name :rx.specs/non-empty-string) (s/def :aws.lda/memory-mb #(and (nat-int? %) (>= % 128) (<= % 3008) (= 0 (mod % 64)))) (s/def :aws.lda/timeout-seconds nat-int?) (s/def :aws.lda/handler :rx.specs/non-empty-string) (s/def :aws.lda/role-arn :rx.specs/non-empty-string) (s/def :aws.lda/include-node-modules? boolean?) (s/def :aws.lda/clean-script vector?) (s/def :aws.lda/package-script vector?) (s/def :aws.lda/package-dir :rx.specs/non-empty-string) (s/def :aws.creds/region :rx.specs/non-empty-string) (s/def :aws.creds/access-key :rx.specs/non-empty-string) (s/def :aws.creds/secret-key :rx.specs/non-empty-string) (s/def :aws.lda/deploy-spec (s/keys :req [:aws.lda/function-id :aws.lda/runtime-name :aws.lda/memory-mb :aws.lda/timeout-seconds :aws.lda/handler :aws.lda/role-arn] :opt [:aws.lda/include-node-modules? :aws.lda/clean-script :aws.lda/package-script :aws.lda/package-dir :aws.creds/regtion :aws.creds/access-key :aws.creds/secret-key])) (def CP (js/require "child_process")) (defn <run-and-report [ss & [opts]] (println " * Running" ss) (let [ch (chan) proc (.spawn CP (first ss) (clj->js (rest ss)) (if opts (clj->js opts) #js {}))] (.on (.-stdout proc) "data" (fn [s] (print (.toString s)))) (.on (.-stderr proc) "data" (fn [s] (print (.toString s)))) (.on proc "close" (fn [exit-code] (put! ch exit-code) (close! ch))) ch)) (defn <exit-on-non-zero [in-fs] (go (loop [fs (remove nil? in-fs)] (when-not (empty? fs) (let [f (first fs) res (<! (f))] (if (= 0 res) (recur (rest fs)) (println "Non-zero return hit, aborting"))))))) (defn <run-deploy [{:keys [:aws.lda/clean-script :aws.lda/package-script :aws.lda/package-dir :aws.lda/include-node-modules?]}] (<exit-on-non-zero [(when clean-script #(<run-and-report clean-script)) (when package-script #(<run-and-report package-script)) #_(when include-node-modules? #(<run-and-report ["rsync" "-a" "--stats" "./node_modules" package-dir])) #_(when package-dir #(zip-package lfn-config))])) (defn compile-command [{:keys [:aws.lda/deps]}] ["clj" "-Sdeps" (pr-str deps) "--main" "cljs.main" "--compile" "evry.sync-server-lambda" "--target" "node" "--output-to" "test-out.js"]) (comment (<run-deploy (merge {:aws.lda/function-id :evry/ddb-sync-test :aws.lda/runtime-name "nodejs8.10" :aws.lda/memory-mb 512 :aws.lda/timeout-seconds 30 :aws.lda/handler "run.handler" :aws.lda/role-arn "arn:aws:iam::753209818049:role/lambda-exec" :aws.lda/include-node-modules? true :aws.lda/clean-script ["lein" "with-profile" "prod" "clean"] :aws.lda/package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "evry-sync-server-lambda"] :aws.lda/package-dir "target/prod/canter/apiserver"} {:aws.creds/region "us-west-2" :aws.creds/access-key "PI:KEY:<KEY>END_PI" :aws.creds/secret-key "PI:KEY:<KEY>END_PI"})) (<run-and-report (compile-command (merge {:aws.lda/function-id :evry/ddb-sync-test :aws.lda/runtime-name "nodejs8.10" :aws.lda/memory-mb 512 :aws.lda/timeout-seconds 30 :aws.lda/handler "run.handler" :aws.lda/role-arn "arn:aws:iam::753209818049:role/lambda-exec" :aws.lda/include-node-modules? true :aws.lda/clean-script ["lein" "with-profile" "prod" "clean"] :aws.lda/package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "evry-sync-server-lambda"] :aws.lda/package-dir "target/prod/canter/apiserver"} {:aws.creds/region "us-west-2" :aws.creds/access-key "PI:KEY:<KEY>END_PI" :aws.creds/secret-key "PI:KEY:<KEY>END_PI"}))) (<run-and-report ["ls" "-aul"]) (prn "hello world") )
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis", "end": 33, "score": 0.9998530149459839, "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.9998409748077393, "start": 35, "tag": "NAME", "value": "Rich Hickey" } ]
src/lucid/legacy/analyzer/passes/constant_lifter.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.constant-lifter (:require [lucid.legacy.analyzer :refer [-analyze]] [lucid.legacy.analyzer.utils :refer [const-val classify]])) (defmulti constant-lift "If the node represents a collection with no metadata, and every item of that collection is a literal, transform the node to an equivalent :const node." :op) (defmethod constant-lift :vector [{:keys [items form env] :as ast}] (if (and (every? :literal? items) (not (meta form))) (assoc (-analyze :const (mapv const-val items) env :vector) :form form) ast)) (defmethod constant-lift :map [{:keys [keys vals form env] :as ast}] (if (and (every? :literal? keys) (every? :literal? vals) (not (meta form))) (let [c (into (empty form) (zipmap (mapv const-val keys) (mapv const-val vals))) c (if (= (class c) (class form)) c (apply array-map (mapcat identity c)))] (assoc (-analyze :const c env :map) :form form)) ast)) (defmethod constant-lift :set [{:keys [items form env] :as ast}] (if (and (every? :literal? items) (not (meta form))) (assoc (-analyze :const (into (empty form) (set (mapv const-val items))) env :set) :form form) ast)) (defmethod constant-lift :default [ast] ast)
13788
;; 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.constant-lifter (:require [lucid.legacy.analyzer :refer [-analyze]] [lucid.legacy.analyzer.utils :refer [const-val classify]])) (defmulti constant-lift "If the node represents a collection with no metadata, and every item of that collection is a literal, transform the node to an equivalent :const node." :op) (defmethod constant-lift :vector [{:keys [items form env] :as ast}] (if (and (every? :literal? items) (not (meta form))) (assoc (-analyze :const (mapv const-val items) env :vector) :form form) ast)) (defmethod constant-lift :map [{:keys [keys vals form env] :as ast}] (if (and (every? :literal? keys) (every? :literal? vals) (not (meta form))) (let [c (into (empty form) (zipmap (mapv const-val keys) (mapv const-val vals))) c (if (= (class c) (class form)) c (apply array-map (mapcat identity c)))] (assoc (-analyze :const c env :map) :form form)) ast)) (defmethod constant-lift :set [{:keys [items form env] :as ast}] (if (and (every? :literal? items) (not (meta form))) (assoc (-analyze :const (into (empty form) (set (mapv const-val items))) env :set) :form form) ast)) (defmethod constant-lift :default [ast] 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.constant-lifter (:require [lucid.legacy.analyzer :refer [-analyze]] [lucid.legacy.analyzer.utils :refer [const-val classify]])) (defmulti constant-lift "If the node represents a collection with no metadata, and every item of that collection is a literal, transform the node to an equivalent :const node." :op) (defmethod constant-lift :vector [{:keys [items form env] :as ast}] (if (and (every? :literal? items) (not (meta form))) (assoc (-analyze :const (mapv const-val items) env :vector) :form form) ast)) (defmethod constant-lift :map [{:keys [keys vals form env] :as ast}] (if (and (every? :literal? keys) (every? :literal? vals) (not (meta form))) (let [c (into (empty form) (zipmap (mapv const-val keys) (mapv const-val vals))) c (if (= (class c) (class form)) c (apply array-map (mapcat identity c)))] (assoc (-analyze :const c env :map) :form form)) ast)) (defmethod constant-lift :set [{:keys [items form env] :as ast}] (if (and (every? :literal? items) (not (meta form))) (assoc (-analyze :const (into (empty form) (set (mapv const-val items))) env :set) :form form) ast)) (defmethod constant-lift :default [ast] ast)
[ { "context": "(ns\n ^{:author \"Jeff Sapp\"}\n somnium.congomongo.error\n (:require [somnium", "end": 26, "score": 0.9998849630355835, "start": 17, "tag": "NAME", "value": "Jeff Sapp" } ]
server/target/somnium/congomongo/error.clj
OctavioBR/healthcheck
0
(ns ^{:author "Jeff Sapp"} somnium.congomongo.error (:require [somnium.congomongo.config :refer [*mongo-config*]]) (:import [com.mongodb DB])) (defn get-last-error "Gets the error (if there is one) from the previous operation" [] (let [e (into {} (.getLastError ^DB (:db *mongo-config*)))] (when (e "err") e))) (defn get-previous-error "Returns the last error that occurred" [] (let [e (into {} (.getPreviousError ^DB (:db *mongo-config*)))] (when (e "err") e))) (defn reset-error! "Resets the error memory for the database" [] (into {} (.resetError ^DB (:db *mongo-config*)))) (defn force-error! "This method forces an error" [] (into {} (.forceError ^DB (:db *mongo-config*))))
33593
(ns ^{:author "<NAME>"} somnium.congomongo.error (:require [somnium.congomongo.config :refer [*mongo-config*]]) (:import [com.mongodb DB])) (defn get-last-error "Gets the error (if there is one) from the previous operation" [] (let [e (into {} (.getLastError ^DB (:db *mongo-config*)))] (when (e "err") e))) (defn get-previous-error "Returns the last error that occurred" [] (let [e (into {} (.getPreviousError ^DB (:db *mongo-config*)))] (when (e "err") e))) (defn reset-error! "Resets the error memory for the database" [] (into {} (.resetError ^DB (:db *mongo-config*)))) (defn force-error! "This method forces an error" [] (into {} (.forceError ^DB (:db *mongo-config*))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} somnium.congomongo.error (:require [somnium.congomongo.config :refer [*mongo-config*]]) (:import [com.mongodb DB])) (defn get-last-error "Gets the error (if there is one) from the previous operation" [] (let [e (into {} (.getLastError ^DB (:db *mongo-config*)))] (when (e "err") e))) (defn get-previous-error "Returns the last error that occurred" [] (let [e (into {} (.getPreviousError ^DB (:db *mongo-config*)))] (when (e "err") e))) (defn reset-error! "Resets the error memory for the database" [] (into {} (.resetError ^DB (:db *mongo-config*)))) (defn force-error! "This method forces an error" [] (into {} (.forceError ^DB (:db *mongo-config*))))
[ { "context": "; Copyright (c) 2021 Mikołaj Kuranowski\n; SPDX-License-Identifier: WTFPL\n(ns day4b\n (:re", "end": 39, "score": 0.9995522499084473, "start": 21, "tag": "NAME", "value": "Mikołaj Kuranowski" } ]
src/day04b.clj
MKuranowski/AdventOfCode2020
0
; Copyright (c) 2021 Mikołaj Kuranowski ; SPDX-License-Identifier: WTFPL (ns day4b (:require [core] [day4a :refer [passports]])) (def valid-regexes {"byr" #"^19[2-9][0-9]|200[0-2]$" "iyr" #"^201[0-9]|2020$" "eyr" #"^202[0-9]|2030$" "hgt" #"^(1[5-8][0-9]|19[0-3])cm|(59|6[0-9]|7[0-6])in$" "hcl" #"^#[0-9a-f]{6}$" "ecl" #"^amb|blu|brn|gry|grn|hzl|oth$" "pid" #"^[0-9]{9}$"}) (defn valid-field? [passport key regex] ((complement nil?) (re-matches regex (get passport key "")))) (defn valid-passport? [passport] (->> (map (fn [[key regex]] (valid-field? passport key regex)) valid-regexes) (every? true?))) (defn -main [filename] (->> filename (core/lines-from-file) (passports) (map valid-passport?) (filter true?) (count) (prn)))
9285
; Copyright (c) 2021 <NAME> ; SPDX-License-Identifier: WTFPL (ns day4b (:require [core] [day4a :refer [passports]])) (def valid-regexes {"byr" #"^19[2-9][0-9]|200[0-2]$" "iyr" #"^201[0-9]|2020$" "eyr" #"^202[0-9]|2030$" "hgt" #"^(1[5-8][0-9]|19[0-3])cm|(59|6[0-9]|7[0-6])in$" "hcl" #"^#[0-9a-f]{6}$" "ecl" #"^amb|blu|brn|gry|grn|hzl|oth$" "pid" #"^[0-9]{9}$"}) (defn valid-field? [passport key regex] ((complement nil?) (re-matches regex (get passport key "")))) (defn valid-passport? [passport] (->> (map (fn [[key regex]] (valid-field? passport key regex)) valid-regexes) (every? true?))) (defn -main [filename] (->> filename (core/lines-from-file) (passports) (map valid-passport?) (filter true?) (count) (prn)))
true
; Copyright (c) 2021 PI:NAME:<NAME>END_PI ; SPDX-License-Identifier: WTFPL (ns day4b (:require [core] [day4a :refer [passports]])) (def valid-regexes {"byr" #"^19[2-9][0-9]|200[0-2]$" "iyr" #"^201[0-9]|2020$" "eyr" #"^202[0-9]|2030$" "hgt" #"^(1[5-8][0-9]|19[0-3])cm|(59|6[0-9]|7[0-6])in$" "hcl" #"^#[0-9a-f]{6}$" "ecl" #"^amb|blu|brn|gry|grn|hzl|oth$" "pid" #"^[0-9]{9}$"}) (defn valid-field? [passport key regex] ((complement nil?) (re-matches regex (get passport key "")))) (defn valid-passport? [passport] (->> (map (fn [[key regex]] (valid-field? passport key regex)) valid-regexes) (every? true?))) (defn -main [filename] (->> filename (core/lines-from-file) (passports) (map valid-passport?) (filter true?) (count) (prn)))
[ { "context": "(def players #{\"Alice\", \"Bob\", \"Kelly\"})\n(println players)\n(def players", "end": 21, "score": 0.9998343586921692, "start": 16, "tag": "NAME", "value": "Alice" }, { "context": "(def players #{\"Alice\", \"Bob\", \"Kelly\"})\n(println players)\n(def players (conj ", "end": 28, "score": 0.9998319149017334, "start": 25, "tag": "NAME", "value": "Bob" }, { "context": "(def players #{\"Alice\", \"Bob\", \"Kelly\"})\n(println players)\n(def players (conj players \"", "end": 37, "score": 0.9998336434364319, "start": 32, "tag": "NAME", "value": "Kelly" }, { "context": "\"})\n(println players)\n(def players (conj players \"Molly\"))\n(println players)\n(def players (disj players \"", "end": 92, "score": 0.9997886419296265, "start": 87, "tag": "NAME", "value": "Molly" }, { "context": "\"))\n(println players)\n(def players (disj players \"Bob\" \"Sal\"))\n(println players)\n(println (contains? pl", "end": 145, "score": 0.9998084306716919, "start": 142, "tag": "NAME", "value": "Bob" }, { "context": "rintln players)\n(def players (disj players \"Bob\" \"Sal\"))\n(println players)\n(println (contains? players ", "end": 151, "score": 0.9997152090072632, "start": 148, "tag": "NAME", "value": "Sal" }, { "context": "))\n(println players)\n(println (contains? players \"Molly\"))\n(println (contains? players \"Bob\"))\n\n(def new-", "end": 207, "score": 0.9997801780700684, "start": 202, "tag": "NAME", "value": "Molly" }, { "context": "s? players \"Molly\"))\n(println (contains? players \"Bob\"))\n\n(def new-players [\"Tim\" \"Sue\" \"Joe\"])\n(def pl", "end": 243, "score": 0.999783992767334, "start": 240, "tag": "NAME", "value": "Bob" }, { "context": "ln (contains? players \"Bob\"))\n\n(def new-players [\"Tim\" \"Sue\" \"Joe\"])\n(def players (into players new-pla", "end": 270, "score": 0.9998103976249695, "start": 267, "tag": "NAME", "value": "Tim" }, { "context": "ntains? players \"Bob\"))\n\n(def new-players [\"Tim\" \"Sue\" \"Joe\"])\n(def players (into players new-players))", "end": 276, "score": 0.9997886419296265, "start": 273, "tag": "NAME", "value": "Sue" }, { "context": "? players \"Bob\"))\n\n(def new-players [\"Tim\" \"Sue\" \"Joe\"])\n(def players (into players new-players))\n(prin", "end": 282, "score": 0.9998066425323486, "start": 279, "tag": "NAME", "value": "Joe" }, { "context": "-players))\n(println players)\n\n(def new-players #{\"Tim\" \"Sue\" \"Joe\"})\n(def players (into players new-pla", "end": 369, "score": 0.9998118281364441, "start": 366, "tag": "NAME", "value": "Tim" }, { "context": "rs))\n(println players)\n\n(def new-players #{\"Tim\" \"Sue\" \"Joe\"})\n(def players (into players new-players))", "end": 375, "score": 0.9997718930244446, "start": 372, "tag": "NAME", "value": "Sue" }, { "context": "println players)\n\n(def new-players #{\"Tim\" \"Sue\" \"Joe\"})\n(def players (into players new-players))\n(prin", "end": 381, "score": 0.9998023509979248, "start": 378, "tag": "NAME", "value": "Joe" } ]
clojure/sets.clj
scorphus/sparring
2
(def players #{"Alice", "Bob", "Kelly"}) (println players) (def players (conj players "Molly")) (println players) (def players (disj players "Bob" "Sal")) (println players) (println (contains? players "Molly")) (println (contains? players "Bob")) (def new-players ["Tim" "Sue" "Joe"]) (def players (into players new-players)) (println players) (def new-players #{"Tim" "Sue" "Joe"}) (def players (into players new-players)) (println players) (def nato (conj (sorted-set) "Delta" "Bravo" "Tango" "Echo" "Alpha")) (println nato) (def new-code-words ["Charlie" "Sierra" "Romeo"]) (def nato (into nato new-code-words)) (println nato) (def new-code-words #{"Charlie" "Sierra" "Romeo"}) (def nato (into nato new-code-words)) (println nato)
31785
(def players #{"<NAME>", "<NAME>", "<NAME>"}) (println players) (def players (conj players "<NAME>")) (println players) (def players (disj players "<NAME>" "<NAME>")) (println players) (println (contains? players "<NAME>")) (println (contains? players "<NAME>")) (def new-players ["<NAME>" "<NAME>" "<NAME>"]) (def players (into players new-players)) (println players) (def new-players #{"<NAME>" "<NAME>" "<NAME>"}) (def players (into players new-players)) (println players) (def nato (conj (sorted-set) "Delta" "Bravo" "Tango" "Echo" "Alpha")) (println nato) (def new-code-words ["Charlie" "Sierra" "Romeo"]) (def nato (into nato new-code-words)) (println nato) (def new-code-words #{"Charlie" "Sierra" "Romeo"}) (def nato (into nato new-code-words)) (println nato)
true
(def players #{"PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"}) (println players) (def players (conj players "PI:NAME:<NAME>END_PI")) (println players) (def players (disj players "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")) (println players) (println (contains? players "PI:NAME:<NAME>END_PI")) (println (contains? players "PI:NAME:<NAME>END_PI")) (def new-players ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) (def players (into players new-players)) (println players) (def new-players #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"}) (def players (into players new-players)) (println players) (def nato (conj (sorted-set) "Delta" "Bravo" "Tango" "Echo" "Alpha")) (println nato) (def new-code-words ["Charlie" "Sierra" "Romeo"]) (def nato (into nato new-code-words)) (println nato) (def new-code-words #{"Charlie" "Sierra" "Romeo"}) (def nato (into nato new-code-words)) (println nato)
[ { "context": ";; Copyright (c) 2014-2015, Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi", "end": 41, "score": 0.9998800158500671, "start": 28, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2014-2015, Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 55, "score": 0.999932587146759, "start": 43, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/suricatta/dsl.clj
smaant-test3-rename/suricatta
0
;; Copyright (c) 2014-2015, Andrey Antukh <niwi@niwi.nz> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns suricatta.dsl "Sql building dsl" (:refer-clojure :exclude [val group-by and or not name set update]) (:require [suricatta.core :as core] [suricatta.impl :as impl] [suricatta.types :as types :refer [defer]]) (:import org.jooq.SQLDialect org.jooq.SelectJoinStep org.jooq.InsertReturningStep org.jooq.Row org.jooq.TableLike org.jooq.FieldLike org.jooq.Field org.jooq.Select org.jooq.impl.DSL org.jooq.impl.DefaultConfiguration org.jooq.impl.DefaultDataType org.jooq.impl.SQLDataType org.jooq.util.postgres.PostgresDataType org.jooq.util.mariadb.MariaDBDataType org.jooq.util.mysql.MySQLDataType suricatta.types.Context)) (def ^{:doc "Datatypes translation map" :dynamic true} *datatypes* {:pg/varchar PostgresDataType/VARCHAR :pg/any PostgresDataType/ANY :pg/bigint PostgresDataType/BIGINT :pg/bigserial PostgresDataType/BIGSERIAL :pg/boolean PostgresDataType/BOOLEAN :pg/date PostgresDataType/DATE :pg/decimal PostgresDataType/DECIMAL :pg/real PostgresDataType/REAL :pg/double PostgresDataType/DOUBLEPRECISION :pg/int4 PostgresDataType/INT4 :pg/int2 PostgresDataType/INT2 :pg/int8 PostgresDataType/INT8 :pg/integer PostgresDataType/INTEGER :pg/serial PostgresDataType/SERIAL :pg/serial4 PostgresDataType/SERIAL4 :pg/serial8 PostgresDataType/SERIAL8 :pg/smallint PostgresDataType/SMALLINT :pg/text PostgresDataType/TEXT :pg/time PostgresDataType/TIME :pg/timetz PostgresDataType/TIMETZ :pg/timestamp PostgresDataType/TIMESTAMP :pg/timestamptz PostgresDataType/TIMESTAMPTZ :pg/uuid PostgresDataType/UUID :pg/char PostgresDataType/CHAR :pg/bytea PostgresDataType/BYTEA :pg/numeric PostgresDataType/NUMERIC :pg/json PostgresDataType/JSON :maria/bigint MariaDBDataType/BIGINT :maria/ubigint MariaDBDataType/BIGINTUNSIGNED :maria/binary MariaDBDataType/BINARY :maria/blob MariaDBDataType/BLOB :maria/bool MariaDBDataType/BOOL :maria/boolean MariaDBDataType/BOOLEAN :maria/char MariaDBDataType/CHAR :maria/date MariaDBDataType/DATE :maria/datetime MariaDBDataType/DATETIME :maria/decimal MariaDBDataType/DECIMAL :maria/double MariaDBDataType/DOUBLE :maria/enum MariaDBDataType/ENUM :maria/float MariaDBDataType/FLOAT :maria/int MariaDBDataType/INT :maria/integer MariaDBDataType/INTEGER :maria/uint MariaDBDataType/INTEGERUNSIGNED :maria/longtext MariaDBDataType/LONGTEXT :maria/mediumint MariaDBDataType/MEDIUMINT :maria/real MariaDBDataType/REAL :maria/smallint MariaDBDataType/SMALLINT :maria/time MariaDBDataType/TIME :maria/timestamp MariaDBDataType/TIMESTAMP :maria/varchar MariaDBDataType/VARCHAR :mysql/bigint MySQLDataType/BIGINT :mysql/ubigint MySQLDataType/BIGINTUNSIGNED :mysql/binary MySQLDataType/BINARY :mysql/blob MySQLDataType/BLOB :mysql/bool MySQLDataType/BOOL :mysql/boolean MySQLDataType/BOOLEAN :mysql/char MySQLDataType/CHAR :mysql/date MySQLDataType/DATE :mysql/datetime MySQLDataType/DATETIME :mysql/decimal MySQLDataType/DECIMAL :mysql/double MySQLDataType/DOUBLE :mysql/enum MySQLDataType/ENUM :mysql/float MySQLDataType/FLOAT :mysql/int MySQLDataType/INT :mysql/integer MySQLDataType/INTEGER :mysql/uint MySQLDataType/INTEGERUNSIGNED :mysql/longtext MySQLDataType/LONGTEXT :mysql/mediumint MySQLDataType/MEDIUMINT :mysql/real MySQLDataType/REAL :mysql/smallint MySQLDataType/SMALLINT :mysql/time MySQLDataType/TIME :mysql/timestamp MySQLDataType/TIMESTAMP :mysql/varchar MySQLDataType/VARCHAR}) (defn- make-datatype [{:keys [type] :as opts}] (reduce (fn [dt [attname attvalue]] (case attname :length (.length dt attvalue) :null (.nullable dt attvalue) :precision (.precision dt attvalue) dt)) (clojure.core/or (get *datatypes* type) (DefaultDataType. SQLDialect/DEFAULT SQLDataType/OTHER (clojure.core/name type))) (into [] opts))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Protocols for constructors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol ISortField (-sort-field [_] "Sort field constructor")) (defprotocol ITable (-table [_] "Table constructor.")) (defprotocol IField (-field [_] "Field constructor.")) (defprotocol IName (-name [_] "Name constructor (mainly used with CTE)")) (defprotocol ICondition (-condition [_] "Condition constructor")) (defprotocol IVal (-val [_] "Val constructor")) (defprotocol IDeferred "Protocol mainly defined for uniform unwrapping deferred queries." (-unwrap [_] "Unwrap the object")) (defprotocol ITableCoerce (-as-table [_ params] "Table coersion.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Protocol Implementations ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (extend-protocol IField java.lang.String (-field [v] (DSL/field v)) clojure.lang.Keyword (-field [v] (DSL/field (clojure.core/name v))) clojure.lang.IPersistentList (-field [v] (let [[fname falias] v falias (clojure.core/name falias)] (-> (-field fname) (.as falias)))) clojure.lang.IPersistentVector (-field [v] (let [[fname & params] v fname (clojure.core/name fname) params (into-array Object params)] (DSL/field fname params))) org.jooq.FieldLike (-field [v] (.asField v)) org.jooq.Field (-field [v] v) org.jooq.impl.Val (-field [v] v) suricatta.types.Deferred (-field [t] (-field @t))) (extend-protocol ISortField java.lang.String (-sort-field ^org.jooq.SortField [s] (-> (DSL/field s) (.asc))) clojure.lang.Keyword (-sort-field ^org.jooq.SortField [kw] (-sort-field (clojure.core/name kw))) org.jooq.Field (-sort-field ^org.jooq.SortField [f] (.asc f)) org.jooq.SortField (-sort-field ^org.jooq.SortField [v] v) clojure.lang.PersistentVector (-sort-field ^org.jooq.SortField [v] (let [^org.jooq.Field field (-field (first v)) ^org.jooq.SortField field (case (second v) :asc (.asc field) :desc (.desc field))] (if (= (count v) 3) (case (first (drop 2 v)) :nulls-last (.nullsLast field) :nulls-first (.nullsFirst field)) field)))) (extend-protocol ITable java.lang.String (-table [s] (DSL/table s)) clojure.lang.IPersistentList (-table [pv] (let [[tname talias] pv talias (clojure.core/name talias)] (-> (-table tname) (.as talias)))) clojure.lang.Keyword (-table [kw] (-table (clojure.core/name kw))) org.jooq.Table (-table [t] t) org.jooq.TableLike (-table [t] (.asTable t)) suricatta.types.Deferred (-table [t] @t)) (extend-protocol IName java.lang.String (-name [s] (-> (into-array String [s]) (DSL/name))) clojure.lang.Keyword (-name [kw] (-name (clojure.core/name kw)))) (extend-protocol ICondition java.lang.String (-condition [s] (DSL/condition s)) org.jooq.Condition (-condition [c] c) clojure.lang.PersistentVector (-condition [v] (let [sql (first v) params (rest v)] (->> (map -unwrap params) (into-array Object) (DSL/condition sql)))) suricatta.types.Deferred (-condition [s] (-condition @s))) (extend-protocol IVal Object (-val [v] (DSL/val v))) (extend-protocol IDeferred nil (-unwrap [v] v) Object (-unwrap [self] (impl/wrap-if-need self)) suricatta.types.Deferred (-unwrap [self] (-unwrap @self))) (extend-protocol ITableCoerce org.jooq.Name (-as-table [v selectexp] (assert (instance? Select selectexp)) (.as v selectexp)) org.jooq.DerivedColumnList (-as-table [v selectexp] (assert (instance? Select selectexp)) (.as v selectexp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common DSL functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn field "Create a field instance." ([v] (-field v)) ([v alias] (-> (-field v) (.as (clojure.core/name alias))))) (defn table "Create a table instance." ([v] (-table v)) ([v alias] (-> (-table v) (.as (clojure.core/name alias))))) (defn to-table "Coerce querypart to table expression." [texp talias & params] (defer (let [texp (-unwrap texp) talias (-unwrap talias)] (cond (clojure.core/and (satisfies? ITableCoerce texp) (instance? Select talias)) (-as-table texp talias) (instance? TableLike texp) (let [talias (clojure.core/name (-unwrap talias)) params (into-array String (map clojure.core/name params))] (.asTable texp talias params)))))) (defn f "Create a field instance, specialized on create function like field instance." [v] (-field v)) (defn typed-field [data type] (let [f (clojure.core/name data) dt (get *datatypes* type)] (DSL/field f dt))) (defn val [v] (-val v)) (defn select "Start select statement." [& fields] (defer (let [fields (map -unwrap fields)] (cond (instance? org.jooq.WithStep (first fields)) (.select (first fields) (->> (map -field (rest fields)) (into-array org.jooq.Field))) :else (->> (map -field fields) (into-array org.jooq.Field) (DSL/select)))))) (defn select-distinct "Start select statement." [& fields] (defer (->> (map (comp field -unwrap) fields) (into-array org.jooq.Field) (DSL/selectDistinct)))) (defn select-from "Helper for create select * from <table> statement directly (without specify fields)" [t] (-> (-table t) (DSL/selectFrom))) (defn select-count [] (DSL/selectCount)) (defn select-one [] (defer (DSL/selectOne))) (defn select-zero [] (DSL/selectZero)) (defn from "Creates from clause." [f & tables] (defer (->> (map -table tables) (into-array org.jooq.TableLike) (.from @f)))) (defn join "Create join clause." [q t] (defer (let [q (-unwrap q) t (-table (-unwrap t))] (.join ^SelectJoinStep q t)))) (defn cross-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.crossJoin step t)))) (defn full-outer-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.fullOuterJoin step t)))) (defn left-outer-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.leftOuterJoin step t)))) (defn right-outer-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.rightOuterJoin step t)))) (defmulti on (comp class -unwrap first vector)) (defmethod on org.jooq.SelectOnStep [step & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.on (-unwrap step))))) (defmethod on org.jooq.TableOnStep [step & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.on (-unwrap step))))) (defn where "Create where clause with variable number of conditions (that are implicitly combined with `and` logical operator)." [q & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.where @q)))) (defn exists "Create an exists condition." [q] (defer (DSL/exists @q))) (defn not-exists "Create a not-exists condition." [q] (defer (DSL/notExists @q))) (defn group-by [q & fields] (defer (->> (map (comp -field -unwrap) fields) (into-array org.jooq.GroupField) (.groupBy @q)))) (defn having "Create having clause with variable number of conditions (that are implicitly combined with `and` logical operator)." [q & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.having @q)))) (defn order-by [q & clauses] (defer (->> (map -sort-field clauses) (into-array org.jooq.SortField) (.orderBy @q)))) (defn for-update [q & fields] (defer (let [q (.forUpdate @q)] (if (seq fields) (->> (map -field fields) (into-array org.jooq.Field) (.of q)) q)))) (defn limit "Creates limit clause." [q num] (defer (.limit @q num))) (defn offset "Creates offset clause." [q num] (defer (.offset @q num))) (defn union [& clauses] (defer (reduce (fn [acc v] (.union acc @v)) (-> clauses first deref) (-> clauses rest)))) (defn union-all [& clauses] (defer (reduce (fn [acc v] (.unionAll acc @v)) (-> clauses first deref) (-> clauses rest)))) (defn returning [t & fields] (defer (if (= (count fields) 0) (.returning @t) (.returning @t (->> (map -field fields) (into-array org.jooq.Field)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Logical operators (for conditions) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn and "Logican operator `and`." [& conditions] (let [conditions (map -condition conditions)] (reduce (fn [acc v] (.and acc v)) (first conditions) (rest conditions)))) (defn or "Logican operator `or`." [& conditions] (let [conditions (map -condition conditions)] (reduce (fn [acc v] (.or acc v)) (first conditions) (rest conditions)))) (defn not "Negate a condition." [c] (DSL/not c)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common Table Expresions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn name [v] (defer (-name v))) (defn with "Create a WITH clause" [& tables] (defer (->> (map -table tables) (into-array org.jooq.CommonTableExpression) (DSL/with)))) (defn with-fields "Add a list of fields to this name to make this name a DerivedColumnList." [n & fields] (defer (let [fields (->> (map clojure.core/name fields) (into-array String))] (.fields @n fields)))) (defmacro row [& values] `(DSL/row ~@(map (fn [x#] `(-unwrap ~x#)) values))) (defn values [& rows] (defer (-> (into-array org.jooq.RowN rows) (DSL/values)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Insert statement ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn insert-into [t] (defer (DSL/insertInto (-table t)))) (defn insert-values [t values] (defer (-> (fn [acc [k v]] (if (nil? v) acc (.set acc (-field k) (-unwrap v)))) (reduce (-unwrap t) values) (.newRecord)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Update statement ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn update "Returns empty UPDATE statement." [t] (defer (DSL/update (-table t)))) (defn set "Attach values to the UPDATE statement." ([t kv] {:pre [(map? kv)]} (defer (let [t (-unwrap t)] (reduce-kv (fn [acc k v] (let [k (-unwrap k) v (-unwrap v)] (.set acc (-field k) v))) t kv)))) ([t k v] (defer (let [v (-unwrap v) k (-unwrap k) t (-unwrap t)] (if (clojure.core/and (instance? org.jooq.Row k) (clojure.core/or (instance? org.jooq.Row v) (instance? org.jooq.Select v))) (.set t k v) (.set t (-field k) v)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Delete statement ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn delete [t] (defer (DSL/delete (-table t)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DDL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn truncate [t] (defer (DSL/truncate (-table t)))) (defn alter-table "Creates new and empty alter table expression." [name] (defer (-> (-unwrap name) (-table) (DSL/alterTable)))) (defn create-table [name] (defer (-> (-unwrap name) (-table) (DSL/createTable)))) (defn drop-table "Drop table statement constructor." [t] (defer (DSL/dropTable (-table t)))) ;; Columns functions (defmulti add-column (comp class -unwrap first vector)) (defmethod add-column org.jooq.AlterTableStep [step name & [{:keys [default] :as opts}]] (defer (let [step (-unwrap step) name (-field name) type (make-datatype opts) step (.add step name type)] (if default (.setDefault step (-field default)) step)))) (defmethod add-column org.jooq.CreateTableAsStep [step name & [{:keys [default] :as opts}]] (defer (let [step (-unwrap step) name (-field name) type (cond-> (make-datatype opts) default (.defaultValue default))] (.column step name type)))) (defn alter-column [step name & [{:keys [type default null length] :as opts}]] (defer (let [step (-> (-unwrap step) (.alter (-field name)))] (when (clojure.core/and (clojure.core/or null length) (clojure.core/not type)) (throw (IllegalArgumentException. "For change null or length you should specify type."))) (when type (.set step (make-datatype opts))) (when default (.defautValue step default)) step))) (defn drop-column "Drop column from alter table step." [step name & [type]] (defer (let [step (-> (-unwrap step) (.drop (-field name)))] (case type :cascade (.cascade step) :restrict (.restrict step) step)))) ;; Index functions (defmethod on org.jooq.CreateIndexStep [step table field & extrafields] (defer (let [fields (->> (concat [field] extrafields) (map (comp -field -unwrap)) (into-array org.jooq.Field))] (.on (-unwrap step) (-table table) fields)))) (defn create-index [indexname] (defer (let [indexname (clojure.core/name indexname)] (DSL/createIndex indexname)))) (defn drop-index [indexname] (defer (let [indexname (clojure.core/name indexname)] (DSL/dropIndex indexname)))) ;; Sequence functions (defn create-sequence [seqname] (defer (let [seqname (clojure.core/name seqname)] (DSL/createSequence seqname)))) (defn alter-sequence [seqname restart] (defer (let [seqname (clojure.core/name seqname) step (DSL/alterSequence seqname)] (if (true? restart) (.restart step) (.restartWith step restart))))) (defn drop-sequence ([seqname] (drop-sequence seqname false)) ([seqname ifexists] (defer (let [seqname (clojure.core/name seqname)] (if ifexists (DSL/dropSequenceIfExists seqname) (DSL/dropSequence seqname))))))
121516
;; Copyright (c) 2014-2015, <NAME> <<EMAIL>> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns suricatta.dsl "Sql building dsl" (:refer-clojure :exclude [val group-by and or not name set update]) (:require [suricatta.core :as core] [suricatta.impl :as impl] [suricatta.types :as types :refer [defer]]) (:import org.jooq.SQLDialect org.jooq.SelectJoinStep org.jooq.InsertReturningStep org.jooq.Row org.jooq.TableLike org.jooq.FieldLike org.jooq.Field org.jooq.Select org.jooq.impl.DSL org.jooq.impl.DefaultConfiguration org.jooq.impl.DefaultDataType org.jooq.impl.SQLDataType org.jooq.util.postgres.PostgresDataType org.jooq.util.mariadb.MariaDBDataType org.jooq.util.mysql.MySQLDataType suricatta.types.Context)) (def ^{:doc "Datatypes translation map" :dynamic true} *datatypes* {:pg/varchar PostgresDataType/VARCHAR :pg/any PostgresDataType/ANY :pg/bigint PostgresDataType/BIGINT :pg/bigserial PostgresDataType/BIGSERIAL :pg/boolean PostgresDataType/BOOLEAN :pg/date PostgresDataType/DATE :pg/decimal PostgresDataType/DECIMAL :pg/real PostgresDataType/REAL :pg/double PostgresDataType/DOUBLEPRECISION :pg/int4 PostgresDataType/INT4 :pg/int2 PostgresDataType/INT2 :pg/int8 PostgresDataType/INT8 :pg/integer PostgresDataType/INTEGER :pg/serial PostgresDataType/SERIAL :pg/serial4 PostgresDataType/SERIAL4 :pg/serial8 PostgresDataType/SERIAL8 :pg/smallint PostgresDataType/SMALLINT :pg/text PostgresDataType/TEXT :pg/time PostgresDataType/TIME :pg/timetz PostgresDataType/TIMETZ :pg/timestamp PostgresDataType/TIMESTAMP :pg/timestamptz PostgresDataType/TIMESTAMPTZ :pg/uuid PostgresDataType/UUID :pg/char PostgresDataType/CHAR :pg/bytea PostgresDataType/BYTEA :pg/numeric PostgresDataType/NUMERIC :pg/json PostgresDataType/JSON :maria/bigint MariaDBDataType/BIGINT :maria/ubigint MariaDBDataType/BIGINTUNSIGNED :maria/binary MariaDBDataType/BINARY :maria/blob MariaDBDataType/BLOB :maria/bool MariaDBDataType/BOOL :maria/boolean MariaDBDataType/BOOLEAN :maria/char MariaDBDataType/CHAR :maria/date MariaDBDataType/DATE :maria/datetime MariaDBDataType/DATETIME :maria/decimal MariaDBDataType/DECIMAL :maria/double MariaDBDataType/DOUBLE :maria/enum MariaDBDataType/ENUM :maria/float MariaDBDataType/FLOAT :maria/int MariaDBDataType/INT :maria/integer MariaDBDataType/INTEGER :maria/uint MariaDBDataType/INTEGERUNSIGNED :maria/longtext MariaDBDataType/LONGTEXT :maria/mediumint MariaDBDataType/MEDIUMINT :maria/real MariaDBDataType/REAL :maria/smallint MariaDBDataType/SMALLINT :maria/time MariaDBDataType/TIME :maria/timestamp MariaDBDataType/TIMESTAMP :maria/varchar MariaDBDataType/VARCHAR :mysql/bigint MySQLDataType/BIGINT :mysql/ubigint MySQLDataType/BIGINTUNSIGNED :mysql/binary MySQLDataType/BINARY :mysql/blob MySQLDataType/BLOB :mysql/bool MySQLDataType/BOOL :mysql/boolean MySQLDataType/BOOLEAN :mysql/char MySQLDataType/CHAR :mysql/date MySQLDataType/DATE :mysql/datetime MySQLDataType/DATETIME :mysql/decimal MySQLDataType/DECIMAL :mysql/double MySQLDataType/DOUBLE :mysql/enum MySQLDataType/ENUM :mysql/float MySQLDataType/FLOAT :mysql/int MySQLDataType/INT :mysql/integer MySQLDataType/INTEGER :mysql/uint MySQLDataType/INTEGERUNSIGNED :mysql/longtext MySQLDataType/LONGTEXT :mysql/mediumint MySQLDataType/MEDIUMINT :mysql/real MySQLDataType/REAL :mysql/smallint MySQLDataType/SMALLINT :mysql/time MySQLDataType/TIME :mysql/timestamp MySQLDataType/TIMESTAMP :mysql/varchar MySQLDataType/VARCHAR}) (defn- make-datatype [{:keys [type] :as opts}] (reduce (fn [dt [attname attvalue]] (case attname :length (.length dt attvalue) :null (.nullable dt attvalue) :precision (.precision dt attvalue) dt)) (clojure.core/or (get *datatypes* type) (DefaultDataType. SQLDialect/DEFAULT SQLDataType/OTHER (clojure.core/name type))) (into [] opts))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Protocols for constructors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol ISortField (-sort-field [_] "Sort field constructor")) (defprotocol ITable (-table [_] "Table constructor.")) (defprotocol IField (-field [_] "Field constructor.")) (defprotocol IName (-name [_] "Name constructor (mainly used with CTE)")) (defprotocol ICondition (-condition [_] "Condition constructor")) (defprotocol IVal (-val [_] "Val constructor")) (defprotocol IDeferred "Protocol mainly defined for uniform unwrapping deferred queries." (-unwrap [_] "Unwrap the object")) (defprotocol ITableCoerce (-as-table [_ params] "Table coersion.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Protocol Implementations ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (extend-protocol IField java.lang.String (-field [v] (DSL/field v)) clojure.lang.Keyword (-field [v] (DSL/field (clojure.core/name v))) clojure.lang.IPersistentList (-field [v] (let [[fname falias] v falias (clojure.core/name falias)] (-> (-field fname) (.as falias)))) clojure.lang.IPersistentVector (-field [v] (let [[fname & params] v fname (clojure.core/name fname) params (into-array Object params)] (DSL/field fname params))) org.jooq.FieldLike (-field [v] (.asField v)) org.jooq.Field (-field [v] v) org.jooq.impl.Val (-field [v] v) suricatta.types.Deferred (-field [t] (-field @t))) (extend-protocol ISortField java.lang.String (-sort-field ^org.jooq.SortField [s] (-> (DSL/field s) (.asc))) clojure.lang.Keyword (-sort-field ^org.jooq.SortField [kw] (-sort-field (clojure.core/name kw))) org.jooq.Field (-sort-field ^org.jooq.SortField [f] (.asc f)) org.jooq.SortField (-sort-field ^org.jooq.SortField [v] v) clojure.lang.PersistentVector (-sort-field ^org.jooq.SortField [v] (let [^org.jooq.Field field (-field (first v)) ^org.jooq.SortField field (case (second v) :asc (.asc field) :desc (.desc field))] (if (= (count v) 3) (case (first (drop 2 v)) :nulls-last (.nullsLast field) :nulls-first (.nullsFirst field)) field)))) (extend-protocol ITable java.lang.String (-table [s] (DSL/table s)) clojure.lang.IPersistentList (-table [pv] (let [[tname talias] pv talias (clojure.core/name talias)] (-> (-table tname) (.as talias)))) clojure.lang.Keyword (-table [kw] (-table (clojure.core/name kw))) org.jooq.Table (-table [t] t) org.jooq.TableLike (-table [t] (.asTable t)) suricatta.types.Deferred (-table [t] @t)) (extend-protocol IName java.lang.String (-name [s] (-> (into-array String [s]) (DSL/name))) clojure.lang.Keyword (-name [kw] (-name (clojure.core/name kw)))) (extend-protocol ICondition java.lang.String (-condition [s] (DSL/condition s)) org.jooq.Condition (-condition [c] c) clojure.lang.PersistentVector (-condition [v] (let [sql (first v) params (rest v)] (->> (map -unwrap params) (into-array Object) (DSL/condition sql)))) suricatta.types.Deferred (-condition [s] (-condition @s))) (extend-protocol IVal Object (-val [v] (DSL/val v))) (extend-protocol IDeferred nil (-unwrap [v] v) Object (-unwrap [self] (impl/wrap-if-need self)) suricatta.types.Deferred (-unwrap [self] (-unwrap @self))) (extend-protocol ITableCoerce org.jooq.Name (-as-table [v selectexp] (assert (instance? Select selectexp)) (.as v selectexp)) org.jooq.DerivedColumnList (-as-table [v selectexp] (assert (instance? Select selectexp)) (.as v selectexp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common DSL functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn field "Create a field instance." ([v] (-field v)) ([v alias] (-> (-field v) (.as (clojure.core/name alias))))) (defn table "Create a table instance." ([v] (-table v)) ([v alias] (-> (-table v) (.as (clojure.core/name alias))))) (defn to-table "Coerce querypart to table expression." [texp talias & params] (defer (let [texp (-unwrap texp) talias (-unwrap talias)] (cond (clojure.core/and (satisfies? ITableCoerce texp) (instance? Select talias)) (-as-table texp talias) (instance? TableLike texp) (let [talias (clojure.core/name (-unwrap talias)) params (into-array String (map clojure.core/name params))] (.asTable texp talias params)))))) (defn f "Create a field instance, specialized on create function like field instance." [v] (-field v)) (defn typed-field [data type] (let [f (clojure.core/name data) dt (get *datatypes* type)] (DSL/field f dt))) (defn val [v] (-val v)) (defn select "Start select statement." [& fields] (defer (let [fields (map -unwrap fields)] (cond (instance? org.jooq.WithStep (first fields)) (.select (first fields) (->> (map -field (rest fields)) (into-array org.jooq.Field))) :else (->> (map -field fields) (into-array org.jooq.Field) (DSL/select)))))) (defn select-distinct "Start select statement." [& fields] (defer (->> (map (comp field -unwrap) fields) (into-array org.jooq.Field) (DSL/selectDistinct)))) (defn select-from "Helper for create select * from <table> statement directly (without specify fields)" [t] (-> (-table t) (DSL/selectFrom))) (defn select-count [] (DSL/selectCount)) (defn select-one [] (defer (DSL/selectOne))) (defn select-zero [] (DSL/selectZero)) (defn from "Creates from clause." [f & tables] (defer (->> (map -table tables) (into-array org.jooq.TableLike) (.from @f)))) (defn join "Create join clause." [q t] (defer (let [q (-unwrap q) t (-table (-unwrap t))] (.join ^SelectJoinStep q t)))) (defn cross-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.crossJoin step t)))) (defn full-outer-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.fullOuterJoin step t)))) (defn left-outer-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.leftOuterJoin step t)))) (defn right-outer-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.rightOuterJoin step t)))) (defmulti on (comp class -unwrap first vector)) (defmethod on org.jooq.SelectOnStep [step & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.on (-unwrap step))))) (defmethod on org.jooq.TableOnStep [step & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.on (-unwrap step))))) (defn where "Create where clause with variable number of conditions (that are implicitly combined with `and` logical operator)." [q & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.where @q)))) (defn exists "Create an exists condition." [q] (defer (DSL/exists @q))) (defn not-exists "Create a not-exists condition." [q] (defer (DSL/notExists @q))) (defn group-by [q & fields] (defer (->> (map (comp -field -unwrap) fields) (into-array org.jooq.GroupField) (.groupBy @q)))) (defn having "Create having clause with variable number of conditions (that are implicitly combined with `and` logical operator)." [q & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.having @q)))) (defn order-by [q & clauses] (defer (->> (map -sort-field clauses) (into-array org.jooq.SortField) (.orderBy @q)))) (defn for-update [q & fields] (defer (let [q (.forUpdate @q)] (if (seq fields) (->> (map -field fields) (into-array org.jooq.Field) (.of q)) q)))) (defn limit "Creates limit clause." [q num] (defer (.limit @q num))) (defn offset "Creates offset clause." [q num] (defer (.offset @q num))) (defn union [& clauses] (defer (reduce (fn [acc v] (.union acc @v)) (-> clauses first deref) (-> clauses rest)))) (defn union-all [& clauses] (defer (reduce (fn [acc v] (.unionAll acc @v)) (-> clauses first deref) (-> clauses rest)))) (defn returning [t & fields] (defer (if (= (count fields) 0) (.returning @t) (.returning @t (->> (map -field fields) (into-array org.jooq.Field)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Logical operators (for conditions) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn and "Logican operator `and`." [& conditions] (let [conditions (map -condition conditions)] (reduce (fn [acc v] (.and acc v)) (first conditions) (rest conditions)))) (defn or "Logican operator `or`." [& conditions] (let [conditions (map -condition conditions)] (reduce (fn [acc v] (.or acc v)) (first conditions) (rest conditions)))) (defn not "Negate a condition." [c] (DSL/not c)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common Table Expresions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn name [v] (defer (-name v))) (defn with "Create a WITH clause" [& tables] (defer (->> (map -table tables) (into-array org.jooq.CommonTableExpression) (DSL/with)))) (defn with-fields "Add a list of fields to this name to make this name a DerivedColumnList." [n & fields] (defer (let [fields (->> (map clojure.core/name fields) (into-array String))] (.fields @n fields)))) (defmacro row [& values] `(DSL/row ~@(map (fn [x#] `(-unwrap ~x#)) values))) (defn values [& rows] (defer (-> (into-array org.jooq.RowN rows) (DSL/values)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Insert statement ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn insert-into [t] (defer (DSL/insertInto (-table t)))) (defn insert-values [t values] (defer (-> (fn [acc [k v]] (if (nil? v) acc (.set acc (-field k) (-unwrap v)))) (reduce (-unwrap t) values) (.newRecord)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Update statement ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn update "Returns empty UPDATE statement." [t] (defer (DSL/update (-table t)))) (defn set "Attach values to the UPDATE statement." ([t kv] {:pre [(map? kv)]} (defer (let [t (-unwrap t)] (reduce-kv (fn [acc k v] (let [k (-unwrap k) v (-unwrap v)] (.set acc (-field k) v))) t kv)))) ([t k v] (defer (let [v (-unwrap v) k (-unwrap k) t (-unwrap t)] (if (clojure.core/and (instance? org.jooq.Row k) (clojure.core/or (instance? org.jooq.Row v) (instance? org.jooq.Select v))) (.set t k v) (.set t (-field k) v)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Delete statement ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn delete [t] (defer (DSL/delete (-table t)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DDL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn truncate [t] (defer (DSL/truncate (-table t)))) (defn alter-table "Creates new and empty alter table expression." [name] (defer (-> (-unwrap name) (-table) (DSL/alterTable)))) (defn create-table [name] (defer (-> (-unwrap name) (-table) (DSL/createTable)))) (defn drop-table "Drop table statement constructor." [t] (defer (DSL/dropTable (-table t)))) ;; Columns functions (defmulti add-column (comp class -unwrap first vector)) (defmethod add-column org.jooq.AlterTableStep [step name & [{:keys [default] :as opts}]] (defer (let [step (-unwrap step) name (-field name) type (make-datatype opts) step (.add step name type)] (if default (.setDefault step (-field default)) step)))) (defmethod add-column org.jooq.CreateTableAsStep [step name & [{:keys [default] :as opts}]] (defer (let [step (-unwrap step) name (-field name) type (cond-> (make-datatype opts) default (.defaultValue default))] (.column step name type)))) (defn alter-column [step name & [{:keys [type default null length] :as opts}]] (defer (let [step (-> (-unwrap step) (.alter (-field name)))] (when (clojure.core/and (clojure.core/or null length) (clojure.core/not type)) (throw (IllegalArgumentException. "For change null or length you should specify type."))) (when type (.set step (make-datatype opts))) (when default (.defautValue step default)) step))) (defn drop-column "Drop column from alter table step." [step name & [type]] (defer (let [step (-> (-unwrap step) (.drop (-field name)))] (case type :cascade (.cascade step) :restrict (.restrict step) step)))) ;; Index functions (defmethod on org.jooq.CreateIndexStep [step table field & extrafields] (defer (let [fields (->> (concat [field] extrafields) (map (comp -field -unwrap)) (into-array org.jooq.Field))] (.on (-unwrap step) (-table table) fields)))) (defn create-index [indexname] (defer (let [indexname (clojure.core/name indexname)] (DSL/createIndex indexname)))) (defn drop-index [indexname] (defer (let [indexname (clojure.core/name indexname)] (DSL/dropIndex indexname)))) ;; Sequence functions (defn create-sequence [seqname] (defer (let [seqname (clojure.core/name seqname)] (DSL/createSequence seqname)))) (defn alter-sequence [seqname restart] (defer (let [seqname (clojure.core/name seqname) step (DSL/alterSequence seqname)] (if (true? restart) (.restart step) (.restartWith step restart))))) (defn drop-sequence ([seqname] (drop-sequence seqname false)) ([seqname ifexists] (defer (let [seqname (clojure.core/name seqname)] (if ifexists (DSL/dropSequenceIfExists seqname) (DSL/dropSequence seqname))))))
true
;; Copyright (c) 2014-2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns suricatta.dsl "Sql building dsl" (:refer-clojure :exclude [val group-by and or not name set update]) (:require [suricatta.core :as core] [suricatta.impl :as impl] [suricatta.types :as types :refer [defer]]) (:import org.jooq.SQLDialect org.jooq.SelectJoinStep org.jooq.InsertReturningStep org.jooq.Row org.jooq.TableLike org.jooq.FieldLike org.jooq.Field org.jooq.Select org.jooq.impl.DSL org.jooq.impl.DefaultConfiguration org.jooq.impl.DefaultDataType org.jooq.impl.SQLDataType org.jooq.util.postgres.PostgresDataType org.jooq.util.mariadb.MariaDBDataType org.jooq.util.mysql.MySQLDataType suricatta.types.Context)) (def ^{:doc "Datatypes translation map" :dynamic true} *datatypes* {:pg/varchar PostgresDataType/VARCHAR :pg/any PostgresDataType/ANY :pg/bigint PostgresDataType/BIGINT :pg/bigserial PostgresDataType/BIGSERIAL :pg/boolean PostgresDataType/BOOLEAN :pg/date PostgresDataType/DATE :pg/decimal PostgresDataType/DECIMAL :pg/real PostgresDataType/REAL :pg/double PostgresDataType/DOUBLEPRECISION :pg/int4 PostgresDataType/INT4 :pg/int2 PostgresDataType/INT2 :pg/int8 PostgresDataType/INT8 :pg/integer PostgresDataType/INTEGER :pg/serial PostgresDataType/SERIAL :pg/serial4 PostgresDataType/SERIAL4 :pg/serial8 PostgresDataType/SERIAL8 :pg/smallint PostgresDataType/SMALLINT :pg/text PostgresDataType/TEXT :pg/time PostgresDataType/TIME :pg/timetz PostgresDataType/TIMETZ :pg/timestamp PostgresDataType/TIMESTAMP :pg/timestamptz PostgresDataType/TIMESTAMPTZ :pg/uuid PostgresDataType/UUID :pg/char PostgresDataType/CHAR :pg/bytea PostgresDataType/BYTEA :pg/numeric PostgresDataType/NUMERIC :pg/json PostgresDataType/JSON :maria/bigint MariaDBDataType/BIGINT :maria/ubigint MariaDBDataType/BIGINTUNSIGNED :maria/binary MariaDBDataType/BINARY :maria/blob MariaDBDataType/BLOB :maria/bool MariaDBDataType/BOOL :maria/boolean MariaDBDataType/BOOLEAN :maria/char MariaDBDataType/CHAR :maria/date MariaDBDataType/DATE :maria/datetime MariaDBDataType/DATETIME :maria/decimal MariaDBDataType/DECIMAL :maria/double MariaDBDataType/DOUBLE :maria/enum MariaDBDataType/ENUM :maria/float MariaDBDataType/FLOAT :maria/int MariaDBDataType/INT :maria/integer MariaDBDataType/INTEGER :maria/uint MariaDBDataType/INTEGERUNSIGNED :maria/longtext MariaDBDataType/LONGTEXT :maria/mediumint MariaDBDataType/MEDIUMINT :maria/real MariaDBDataType/REAL :maria/smallint MariaDBDataType/SMALLINT :maria/time MariaDBDataType/TIME :maria/timestamp MariaDBDataType/TIMESTAMP :maria/varchar MariaDBDataType/VARCHAR :mysql/bigint MySQLDataType/BIGINT :mysql/ubigint MySQLDataType/BIGINTUNSIGNED :mysql/binary MySQLDataType/BINARY :mysql/blob MySQLDataType/BLOB :mysql/bool MySQLDataType/BOOL :mysql/boolean MySQLDataType/BOOLEAN :mysql/char MySQLDataType/CHAR :mysql/date MySQLDataType/DATE :mysql/datetime MySQLDataType/DATETIME :mysql/decimal MySQLDataType/DECIMAL :mysql/double MySQLDataType/DOUBLE :mysql/enum MySQLDataType/ENUM :mysql/float MySQLDataType/FLOAT :mysql/int MySQLDataType/INT :mysql/integer MySQLDataType/INTEGER :mysql/uint MySQLDataType/INTEGERUNSIGNED :mysql/longtext MySQLDataType/LONGTEXT :mysql/mediumint MySQLDataType/MEDIUMINT :mysql/real MySQLDataType/REAL :mysql/smallint MySQLDataType/SMALLINT :mysql/time MySQLDataType/TIME :mysql/timestamp MySQLDataType/TIMESTAMP :mysql/varchar MySQLDataType/VARCHAR}) (defn- make-datatype [{:keys [type] :as opts}] (reduce (fn [dt [attname attvalue]] (case attname :length (.length dt attvalue) :null (.nullable dt attvalue) :precision (.precision dt attvalue) dt)) (clojure.core/or (get *datatypes* type) (DefaultDataType. SQLDialect/DEFAULT SQLDataType/OTHER (clojure.core/name type))) (into [] opts))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Protocols for constructors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol ISortField (-sort-field [_] "Sort field constructor")) (defprotocol ITable (-table [_] "Table constructor.")) (defprotocol IField (-field [_] "Field constructor.")) (defprotocol IName (-name [_] "Name constructor (mainly used with CTE)")) (defprotocol ICondition (-condition [_] "Condition constructor")) (defprotocol IVal (-val [_] "Val constructor")) (defprotocol IDeferred "Protocol mainly defined for uniform unwrapping deferred queries." (-unwrap [_] "Unwrap the object")) (defprotocol ITableCoerce (-as-table [_ params] "Table coersion.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Protocol Implementations ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (extend-protocol IField java.lang.String (-field [v] (DSL/field v)) clojure.lang.Keyword (-field [v] (DSL/field (clojure.core/name v))) clojure.lang.IPersistentList (-field [v] (let [[fname falias] v falias (clojure.core/name falias)] (-> (-field fname) (.as falias)))) clojure.lang.IPersistentVector (-field [v] (let [[fname & params] v fname (clojure.core/name fname) params (into-array Object params)] (DSL/field fname params))) org.jooq.FieldLike (-field [v] (.asField v)) org.jooq.Field (-field [v] v) org.jooq.impl.Val (-field [v] v) suricatta.types.Deferred (-field [t] (-field @t))) (extend-protocol ISortField java.lang.String (-sort-field ^org.jooq.SortField [s] (-> (DSL/field s) (.asc))) clojure.lang.Keyword (-sort-field ^org.jooq.SortField [kw] (-sort-field (clojure.core/name kw))) org.jooq.Field (-sort-field ^org.jooq.SortField [f] (.asc f)) org.jooq.SortField (-sort-field ^org.jooq.SortField [v] v) clojure.lang.PersistentVector (-sort-field ^org.jooq.SortField [v] (let [^org.jooq.Field field (-field (first v)) ^org.jooq.SortField field (case (second v) :asc (.asc field) :desc (.desc field))] (if (= (count v) 3) (case (first (drop 2 v)) :nulls-last (.nullsLast field) :nulls-first (.nullsFirst field)) field)))) (extend-protocol ITable java.lang.String (-table [s] (DSL/table s)) clojure.lang.IPersistentList (-table [pv] (let [[tname talias] pv talias (clojure.core/name talias)] (-> (-table tname) (.as talias)))) clojure.lang.Keyword (-table [kw] (-table (clojure.core/name kw))) org.jooq.Table (-table [t] t) org.jooq.TableLike (-table [t] (.asTable t)) suricatta.types.Deferred (-table [t] @t)) (extend-protocol IName java.lang.String (-name [s] (-> (into-array String [s]) (DSL/name))) clojure.lang.Keyword (-name [kw] (-name (clojure.core/name kw)))) (extend-protocol ICondition java.lang.String (-condition [s] (DSL/condition s)) org.jooq.Condition (-condition [c] c) clojure.lang.PersistentVector (-condition [v] (let [sql (first v) params (rest v)] (->> (map -unwrap params) (into-array Object) (DSL/condition sql)))) suricatta.types.Deferred (-condition [s] (-condition @s))) (extend-protocol IVal Object (-val [v] (DSL/val v))) (extend-protocol IDeferred nil (-unwrap [v] v) Object (-unwrap [self] (impl/wrap-if-need self)) suricatta.types.Deferred (-unwrap [self] (-unwrap @self))) (extend-protocol ITableCoerce org.jooq.Name (-as-table [v selectexp] (assert (instance? Select selectexp)) (.as v selectexp)) org.jooq.DerivedColumnList (-as-table [v selectexp] (assert (instance? Select selectexp)) (.as v selectexp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common DSL functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn field "Create a field instance." ([v] (-field v)) ([v alias] (-> (-field v) (.as (clojure.core/name alias))))) (defn table "Create a table instance." ([v] (-table v)) ([v alias] (-> (-table v) (.as (clojure.core/name alias))))) (defn to-table "Coerce querypart to table expression." [texp talias & params] (defer (let [texp (-unwrap texp) talias (-unwrap talias)] (cond (clojure.core/and (satisfies? ITableCoerce texp) (instance? Select talias)) (-as-table texp talias) (instance? TableLike texp) (let [talias (clojure.core/name (-unwrap talias)) params (into-array String (map clojure.core/name params))] (.asTable texp talias params)))))) (defn f "Create a field instance, specialized on create function like field instance." [v] (-field v)) (defn typed-field [data type] (let [f (clojure.core/name data) dt (get *datatypes* type)] (DSL/field f dt))) (defn val [v] (-val v)) (defn select "Start select statement." [& fields] (defer (let [fields (map -unwrap fields)] (cond (instance? org.jooq.WithStep (first fields)) (.select (first fields) (->> (map -field (rest fields)) (into-array org.jooq.Field))) :else (->> (map -field fields) (into-array org.jooq.Field) (DSL/select)))))) (defn select-distinct "Start select statement." [& fields] (defer (->> (map (comp field -unwrap) fields) (into-array org.jooq.Field) (DSL/selectDistinct)))) (defn select-from "Helper for create select * from <table> statement directly (without specify fields)" [t] (-> (-table t) (DSL/selectFrom))) (defn select-count [] (DSL/selectCount)) (defn select-one [] (defer (DSL/selectOne))) (defn select-zero [] (DSL/selectZero)) (defn from "Creates from clause." [f & tables] (defer (->> (map -table tables) (into-array org.jooq.TableLike) (.from @f)))) (defn join "Create join clause." [q t] (defer (let [q (-unwrap q) t (-table (-unwrap t))] (.join ^SelectJoinStep q t)))) (defn cross-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.crossJoin step t)))) (defn full-outer-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.fullOuterJoin step t)))) (defn left-outer-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.leftOuterJoin step t)))) (defn right-outer-join [step tlike] (defer (let [t (-table (-unwrap tlike)) step (-unwrap step)] (.rightOuterJoin step t)))) (defmulti on (comp class -unwrap first vector)) (defmethod on org.jooq.SelectOnStep [step & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.on (-unwrap step))))) (defmethod on org.jooq.TableOnStep [step & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.on (-unwrap step))))) (defn where "Create where clause with variable number of conditions (that are implicitly combined with `and` logical operator)." [q & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.where @q)))) (defn exists "Create an exists condition." [q] (defer (DSL/exists @q))) (defn not-exists "Create a not-exists condition." [q] (defer (DSL/notExists @q))) (defn group-by [q & fields] (defer (->> (map (comp -field -unwrap) fields) (into-array org.jooq.GroupField) (.groupBy @q)))) (defn having "Create having clause with variable number of conditions (that are implicitly combined with `and` logical operator)." [q & clauses] (defer (->> (map -condition clauses) (into-array org.jooq.Condition) (.having @q)))) (defn order-by [q & clauses] (defer (->> (map -sort-field clauses) (into-array org.jooq.SortField) (.orderBy @q)))) (defn for-update [q & fields] (defer (let [q (.forUpdate @q)] (if (seq fields) (->> (map -field fields) (into-array org.jooq.Field) (.of q)) q)))) (defn limit "Creates limit clause." [q num] (defer (.limit @q num))) (defn offset "Creates offset clause." [q num] (defer (.offset @q num))) (defn union [& clauses] (defer (reduce (fn [acc v] (.union acc @v)) (-> clauses first deref) (-> clauses rest)))) (defn union-all [& clauses] (defer (reduce (fn [acc v] (.unionAll acc @v)) (-> clauses first deref) (-> clauses rest)))) (defn returning [t & fields] (defer (if (= (count fields) 0) (.returning @t) (.returning @t (->> (map -field fields) (into-array org.jooq.Field)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Logical operators (for conditions) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn and "Logican operator `and`." [& conditions] (let [conditions (map -condition conditions)] (reduce (fn [acc v] (.and acc v)) (first conditions) (rest conditions)))) (defn or "Logican operator `or`." [& conditions] (let [conditions (map -condition conditions)] (reduce (fn [acc v] (.or acc v)) (first conditions) (rest conditions)))) (defn not "Negate a condition." [c] (DSL/not c)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common Table Expresions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn name [v] (defer (-name v))) (defn with "Create a WITH clause" [& tables] (defer (->> (map -table tables) (into-array org.jooq.CommonTableExpression) (DSL/with)))) (defn with-fields "Add a list of fields to this name to make this name a DerivedColumnList." [n & fields] (defer (let [fields (->> (map clojure.core/name fields) (into-array String))] (.fields @n fields)))) (defmacro row [& values] `(DSL/row ~@(map (fn [x#] `(-unwrap ~x#)) values))) (defn values [& rows] (defer (-> (into-array org.jooq.RowN rows) (DSL/values)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Insert statement ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn insert-into [t] (defer (DSL/insertInto (-table t)))) (defn insert-values [t values] (defer (-> (fn [acc [k v]] (if (nil? v) acc (.set acc (-field k) (-unwrap v)))) (reduce (-unwrap t) values) (.newRecord)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Update statement ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn update "Returns empty UPDATE statement." [t] (defer (DSL/update (-table t)))) (defn set "Attach values to the UPDATE statement." ([t kv] {:pre [(map? kv)]} (defer (let [t (-unwrap t)] (reduce-kv (fn [acc k v] (let [k (-unwrap k) v (-unwrap v)] (.set acc (-field k) v))) t kv)))) ([t k v] (defer (let [v (-unwrap v) k (-unwrap k) t (-unwrap t)] (if (clojure.core/and (instance? org.jooq.Row k) (clojure.core/or (instance? org.jooq.Row v) (instance? org.jooq.Select v))) (.set t k v) (.set t (-field k) v)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Delete statement ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn delete [t] (defer (DSL/delete (-table t)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DDL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn truncate [t] (defer (DSL/truncate (-table t)))) (defn alter-table "Creates new and empty alter table expression." [name] (defer (-> (-unwrap name) (-table) (DSL/alterTable)))) (defn create-table [name] (defer (-> (-unwrap name) (-table) (DSL/createTable)))) (defn drop-table "Drop table statement constructor." [t] (defer (DSL/dropTable (-table t)))) ;; Columns functions (defmulti add-column (comp class -unwrap first vector)) (defmethod add-column org.jooq.AlterTableStep [step name & [{:keys [default] :as opts}]] (defer (let [step (-unwrap step) name (-field name) type (make-datatype opts) step (.add step name type)] (if default (.setDefault step (-field default)) step)))) (defmethod add-column org.jooq.CreateTableAsStep [step name & [{:keys [default] :as opts}]] (defer (let [step (-unwrap step) name (-field name) type (cond-> (make-datatype opts) default (.defaultValue default))] (.column step name type)))) (defn alter-column [step name & [{:keys [type default null length] :as opts}]] (defer (let [step (-> (-unwrap step) (.alter (-field name)))] (when (clojure.core/and (clojure.core/or null length) (clojure.core/not type)) (throw (IllegalArgumentException. "For change null or length you should specify type."))) (when type (.set step (make-datatype opts))) (when default (.defautValue step default)) step))) (defn drop-column "Drop column from alter table step." [step name & [type]] (defer (let [step (-> (-unwrap step) (.drop (-field name)))] (case type :cascade (.cascade step) :restrict (.restrict step) step)))) ;; Index functions (defmethod on org.jooq.CreateIndexStep [step table field & extrafields] (defer (let [fields (->> (concat [field] extrafields) (map (comp -field -unwrap)) (into-array org.jooq.Field))] (.on (-unwrap step) (-table table) fields)))) (defn create-index [indexname] (defer (let [indexname (clojure.core/name indexname)] (DSL/createIndex indexname)))) (defn drop-index [indexname] (defer (let [indexname (clojure.core/name indexname)] (DSL/dropIndex indexname)))) ;; Sequence functions (defn create-sequence [seqname] (defer (let [seqname (clojure.core/name seqname)] (DSL/createSequence seqname)))) (defn alter-sequence [seqname restart] (defer (let [seqname (clojure.core/name seqname) step (DSL/alterSequence seqname)] (if (true? restart) (.restart step) (.restartWith step restart))))) (defn drop-sequence ([seqname] (drop-sequence seqname false)) ([seqname ifexists] (defer (let [seqname (clojure.core/name seqname)] (if ifexists (DSL/dropSequenceIfExists seqname) (DSL/dropSequence seqname))))))
[ { "context": "(ns ^{:author \"James McClain <jwm@daystrom-data-concepts.com>\"}\n sr33.reconst", "end": 28, "score": 0.9998607039451599, "start": 15, "tag": "NAME", "value": "James McClain" }, { "context": "(ns ^{:author \"James McClain <jwm@daystrom-data-concepts.com>\"}\n sr33.reconstruct\n (:require [clojure.set :a", "end": 60, "score": 0.999933660030365, "start": 30, "tag": "EMAIL", "value": "jwm@daystrom-data-concepts.com" } ]
src/sr33/reconstruct.clj
jamesmcclain/sr33
1
(ns ^{:author "James McClain <jwm@daystrom-data-concepts.com>"} sr33.reconstruct (:require [clojure.set :as set] [clojure.core.memoize :as memo] [clojure.core.reducers :as r] [sr33.kdtree :as kdtree] [sr33.graph_theory :as theory])) (set! *warn-on-reflection* true) (set! *unchecked-math* true) ;; Compute an adjacency list (a hash map) from a collection of edges. (defn- compute-adjlist [edges] (letfn [(staple ([] {}) ([a b] (merge-with set/union a b))) (edge-to-map [uv] (let [u (first uv) v (second uv)] {u #{v} v #{u}})) (add-edge [adjlist edge] (merge-with set/union adjlist (edge-to-map edge)))] (r/fold staple add-edge edges))) ;; Generate a list of unique, non-trivial cycles that meet the point ;; with index u. In order to avoid duplicates from other local lists, ;; only cycles where all of the indices are smaller than u are ;; allowed. ;; ;; The ``graph'' parameter is the adjacency list in which cycles are ;; searched-for. The ``metric'' parameter is the adjacency list of ;; the graph in which distances are defined for purposes of finding ;; isometric cycles. These two might seemingly always be the same, ;; but they need to be distinct when looking for non-convex holes. (defn- cycles-at-u [graph metric hood u & extra] (let [hood (or hood (set (keys metric))) extra (set extra) compute-dist (memo/fifo (fn [s] (first (theory/Dijkstra metric hood s)))) eligible (set (filter #(< (long %) (long u)) hood)) compute-pi (memo/fifo (fn [s] (second (theory/Dijkstra graph eligible s))))] (letfn [(trace-path [a b pi] ; trace a path from a to be using the previous set pi (loop [current b path (list)] (cond (== (long current) (long a)) (conj path current) (== (long current) -1) nil :else (recur (get pi current -1) (conj path current))))) (isometric? [cycle] ; determine if cycle is isometric (let [n (dec (count cycle)) n-1 (dec n)] (loop [i 0 j 1] (cond (> i n-1) true ; no shortcuts found (> j n-1) (recur (+ i 1) (+ i 2)) ; next iteration of i :else ; check for shortcut (let [s (long (nth cycle i)) t (long (nth cycle j)) dist-cycle (long (min (- j i) (+ (- i j) n))) dist-metric (long (get (compute-dist (min s t)) (max s t)))] (if (< dist-metric dist-cycle) false ; not isometric (recur i (inc j))))))))] (let [neighbors (set/intersection eligible (get graph u #{})) candidate-cycles (for [a neighbors b neighbors :when (< (long a) (long b))] ; enforcing a < b ensures only one copy of each cycle (let [pi (compute-pi a) path (trace-path a b pi)] (if (not (nil? path)) (concat (list u) path (list u)) nil))) candidate-cycles (remove nil? candidate-cycles)] (if (contains? extra :no-isometry-test) candidate-cycles (filter isometric? candidate-cycles)))))) ;; Return the set of edges which bound the cycle. (defn- compute-boundary [cycle] (loop [cycle cycle edges (list)] (if (< (count cycle) 2) edges (recur (rest cycle) (conj edges #{(first cycle) (second cycle)}))))) ;; Turn a cycle into a cycle+boundary pair. (defn- cycle-to-complex [cycle] (hash-map :cycle cycle :boundary (compute-boundary cycle))) ;; Triangulate a (non-triangular) cycle by connecting the nearest pair ;; that is not already connected. (defn- triangulate-cycle [points cycle] (if (== 4 (count cycle)) ; triangle: report it, otherwise: split it (list cycle) (let [n (dec (count cycle)) dist-cycle (fn [i j] (let [i (long (second i)) j (long (second j))] (min (- j i) (+ (- i j) n)))) dist-euclidean (fn [u v] (let [u (first u) v (first v)] (theory/distance points u v)))] (let [cycle+ (map list cycle (range)) uv ; the following sexp returns the best edge at which to split (vec (loop [U (rest cycle+) V (rest (rest cycle+)) best nil best-dist Double/POSITIVE_INFINITY] (let [u (first U) v (first V)] (cond (nil? u) best ; done (nil? v) (recur (rest U) (rest (rest U)) best best-dist) ; increment (and (> (long (dist-cycle u v)) 1) (< (double (dist-euclidean u v)) best-dist)) (recur U (rest V) (list u v) (double (dist-euclidean u v))) ; uv is a better edge :else (recur U (rest V) best best-dist))))) [[_ i] [_ j]] uv cycle-1 (concat (take (+ 1 (long i)) cycle) (drop j cycle)) cycle-2 (concat (drop i (take (+ 1 (long j)) cycle)) (list (nth cycle i)))] (into (triangulate-cycle points cycle-1) (triangulate-cycle points cycle-2)))))) ;; Find holes in the surface. (defn- find-holes [surface neighborhood-of & extra] (let [edge-counts (frequencies (r/mapcat :boundary surface)) half-graph-E (r/map first (filter #(== 1 (long (val %))) edge-counts)) ; half-edges half-graph (compute-adjlist half-graph-E) ; half-edge graph half-graph-V (into [] (r/foldcat (r/flatten (r/map seq half-graph-E)))) ; half-edge graph vertices extra (apply hash-map extra) metric (get extra :metric false) isometry (if (not metric) :no-isometry-test nil) compute-holes (fn [u] (cycles-at-u half-graph (or metric half-graph) (neighborhood-of u) u isometry))] (r/foldcat (r/map cycle-to-complex (r/mapcat compute-holes half-graph-V))))) ;; Remove faces that are (likely to be) inside of the model (assuming ;; that it is closed). (defn- remove-inner-faces [surface] (let [edge-counts (frequencies (r/mapcat :boundary surface))] (letfn [(inner? [complex] (let [boundary (get complex :boundary) sum (double (reduce + (map edge-counts boundary))) avg-double (- (/ sum (count boundary)) 0.0001) avg-int (Math/round avg-double)] (> avg-int 2)))] (r/foldcat (r/remove inner? surface))))) (defmacro remove-x-triangles [surface predicate quantifier] `(let [edge-counts# (frequencies (r/mapcat :boundary ~surface)) edges# (into #{} (r/foldcat (r/map first (filter ~predicate edge-counts#)))) x?# (fn [complex#] (~quantifier edges# (get complex# :boundary)))] (r/foldcat (r/remove x?# ~surface)))) (defn- remove-suspicious-triangles [surface] (remove-x-triangles surface #(> (long (val %)) 2) #'some)) ;; Recover a surface from an organized collection of point samples by ;; computing a subset of the Delaunay Triangulation (assuming the ;; sample conditions hold) then triangulating the resulting cycles. (defn compute-surface [points k] (let [kdtree (kdtree/build points) n (count points) k-hood-of (memo/fifo (fn [u] (set (map :index (kdtree/query (nth points u) kdtree k)))) :fifo/threshold (inc n)) triangulate-surface (fn [surface] (r/foldcat (r/map cycle-to-complex (r/mapcat #(triangulate-cycle points %) (r/map :cycle surface))))) tri-to-set (fn [face] (set (take 3 face)))] (let [_ (println (java.util.Date.) "\t edges") edges (theory/RNG points n k-hood-of) ; relative neighborhood graph _ (println (java.util.Date.) "\t isometric cycles") graph (compute-adjlist edges) ; adjacency list of the same compute-cycles (fn [u] (cycles-at-u graph graph (k-hood-of u) u)) surface (r/foldcat (r/mapcat compute-cycles (into [] (range n)))) ; isometric cycles surface (r/map cycle-to-complex surface) ; cycles + boundaries surface (remove-inner-faces surface) ; remove inner faces _ (println (java.util.Date.) "\t triangulation") surface (triangulate-surface surface) ; triangulate graph (compute-adjlist (r/foldcat (r/mapcat :boundary surface))) surface (remove-suspicious-triangles surface) ; remove bad triangles _ (println (java.util.Date.) "\t convex holes") graph (compute-adjlist (r/foldcat (r/mapcat :boundary surface))) convex-holes (find-holes surface k-hood-of :metric graph) surface (r/cat surface (triangulate-surface convex-holes)) ; add convex holes _ (println (java.util.Date.) "\t non-convex holes") graph (compute-adjlist (r/foldcat (r/mapcat :boundary surface))) holes (find-holes surface k-hood-of) surface (r/cat surface (triangulate-surface holes))] (println (java.util.Date.) "\t done") (into #{} (r/foldcat (r/map (comp tri-to-set :cycle) surface))))))
106949
(ns ^{:author "<NAME> <<EMAIL>>"} sr33.reconstruct (:require [clojure.set :as set] [clojure.core.memoize :as memo] [clojure.core.reducers :as r] [sr33.kdtree :as kdtree] [sr33.graph_theory :as theory])) (set! *warn-on-reflection* true) (set! *unchecked-math* true) ;; Compute an adjacency list (a hash map) from a collection of edges. (defn- compute-adjlist [edges] (letfn [(staple ([] {}) ([a b] (merge-with set/union a b))) (edge-to-map [uv] (let [u (first uv) v (second uv)] {u #{v} v #{u}})) (add-edge [adjlist edge] (merge-with set/union adjlist (edge-to-map edge)))] (r/fold staple add-edge edges))) ;; Generate a list of unique, non-trivial cycles that meet the point ;; with index u. In order to avoid duplicates from other local lists, ;; only cycles where all of the indices are smaller than u are ;; allowed. ;; ;; The ``graph'' parameter is the adjacency list in which cycles are ;; searched-for. The ``metric'' parameter is the adjacency list of ;; the graph in which distances are defined for purposes of finding ;; isometric cycles. These two might seemingly always be the same, ;; but they need to be distinct when looking for non-convex holes. (defn- cycles-at-u [graph metric hood u & extra] (let [hood (or hood (set (keys metric))) extra (set extra) compute-dist (memo/fifo (fn [s] (first (theory/Dijkstra metric hood s)))) eligible (set (filter #(< (long %) (long u)) hood)) compute-pi (memo/fifo (fn [s] (second (theory/Dijkstra graph eligible s))))] (letfn [(trace-path [a b pi] ; trace a path from a to be using the previous set pi (loop [current b path (list)] (cond (== (long current) (long a)) (conj path current) (== (long current) -1) nil :else (recur (get pi current -1) (conj path current))))) (isometric? [cycle] ; determine if cycle is isometric (let [n (dec (count cycle)) n-1 (dec n)] (loop [i 0 j 1] (cond (> i n-1) true ; no shortcuts found (> j n-1) (recur (+ i 1) (+ i 2)) ; next iteration of i :else ; check for shortcut (let [s (long (nth cycle i)) t (long (nth cycle j)) dist-cycle (long (min (- j i) (+ (- i j) n))) dist-metric (long (get (compute-dist (min s t)) (max s t)))] (if (< dist-metric dist-cycle) false ; not isometric (recur i (inc j))))))))] (let [neighbors (set/intersection eligible (get graph u #{})) candidate-cycles (for [a neighbors b neighbors :when (< (long a) (long b))] ; enforcing a < b ensures only one copy of each cycle (let [pi (compute-pi a) path (trace-path a b pi)] (if (not (nil? path)) (concat (list u) path (list u)) nil))) candidate-cycles (remove nil? candidate-cycles)] (if (contains? extra :no-isometry-test) candidate-cycles (filter isometric? candidate-cycles)))))) ;; Return the set of edges which bound the cycle. (defn- compute-boundary [cycle] (loop [cycle cycle edges (list)] (if (< (count cycle) 2) edges (recur (rest cycle) (conj edges #{(first cycle) (second cycle)}))))) ;; Turn a cycle into a cycle+boundary pair. (defn- cycle-to-complex [cycle] (hash-map :cycle cycle :boundary (compute-boundary cycle))) ;; Triangulate a (non-triangular) cycle by connecting the nearest pair ;; that is not already connected. (defn- triangulate-cycle [points cycle] (if (== 4 (count cycle)) ; triangle: report it, otherwise: split it (list cycle) (let [n (dec (count cycle)) dist-cycle (fn [i j] (let [i (long (second i)) j (long (second j))] (min (- j i) (+ (- i j) n)))) dist-euclidean (fn [u v] (let [u (first u) v (first v)] (theory/distance points u v)))] (let [cycle+ (map list cycle (range)) uv ; the following sexp returns the best edge at which to split (vec (loop [U (rest cycle+) V (rest (rest cycle+)) best nil best-dist Double/POSITIVE_INFINITY] (let [u (first U) v (first V)] (cond (nil? u) best ; done (nil? v) (recur (rest U) (rest (rest U)) best best-dist) ; increment (and (> (long (dist-cycle u v)) 1) (< (double (dist-euclidean u v)) best-dist)) (recur U (rest V) (list u v) (double (dist-euclidean u v))) ; uv is a better edge :else (recur U (rest V) best best-dist))))) [[_ i] [_ j]] uv cycle-1 (concat (take (+ 1 (long i)) cycle) (drop j cycle)) cycle-2 (concat (drop i (take (+ 1 (long j)) cycle)) (list (nth cycle i)))] (into (triangulate-cycle points cycle-1) (triangulate-cycle points cycle-2)))))) ;; Find holes in the surface. (defn- find-holes [surface neighborhood-of & extra] (let [edge-counts (frequencies (r/mapcat :boundary surface)) half-graph-E (r/map first (filter #(== 1 (long (val %))) edge-counts)) ; half-edges half-graph (compute-adjlist half-graph-E) ; half-edge graph half-graph-V (into [] (r/foldcat (r/flatten (r/map seq half-graph-E)))) ; half-edge graph vertices extra (apply hash-map extra) metric (get extra :metric false) isometry (if (not metric) :no-isometry-test nil) compute-holes (fn [u] (cycles-at-u half-graph (or metric half-graph) (neighborhood-of u) u isometry))] (r/foldcat (r/map cycle-to-complex (r/mapcat compute-holes half-graph-V))))) ;; Remove faces that are (likely to be) inside of the model (assuming ;; that it is closed). (defn- remove-inner-faces [surface] (let [edge-counts (frequencies (r/mapcat :boundary surface))] (letfn [(inner? [complex] (let [boundary (get complex :boundary) sum (double (reduce + (map edge-counts boundary))) avg-double (- (/ sum (count boundary)) 0.0001) avg-int (Math/round avg-double)] (> avg-int 2)))] (r/foldcat (r/remove inner? surface))))) (defmacro remove-x-triangles [surface predicate quantifier] `(let [edge-counts# (frequencies (r/mapcat :boundary ~surface)) edges# (into #{} (r/foldcat (r/map first (filter ~predicate edge-counts#)))) x?# (fn [complex#] (~quantifier edges# (get complex# :boundary)))] (r/foldcat (r/remove x?# ~surface)))) (defn- remove-suspicious-triangles [surface] (remove-x-triangles surface #(> (long (val %)) 2) #'some)) ;; Recover a surface from an organized collection of point samples by ;; computing a subset of the Delaunay Triangulation (assuming the ;; sample conditions hold) then triangulating the resulting cycles. (defn compute-surface [points k] (let [kdtree (kdtree/build points) n (count points) k-hood-of (memo/fifo (fn [u] (set (map :index (kdtree/query (nth points u) kdtree k)))) :fifo/threshold (inc n)) triangulate-surface (fn [surface] (r/foldcat (r/map cycle-to-complex (r/mapcat #(triangulate-cycle points %) (r/map :cycle surface))))) tri-to-set (fn [face] (set (take 3 face)))] (let [_ (println (java.util.Date.) "\t edges") edges (theory/RNG points n k-hood-of) ; relative neighborhood graph _ (println (java.util.Date.) "\t isometric cycles") graph (compute-adjlist edges) ; adjacency list of the same compute-cycles (fn [u] (cycles-at-u graph graph (k-hood-of u) u)) surface (r/foldcat (r/mapcat compute-cycles (into [] (range n)))) ; isometric cycles surface (r/map cycle-to-complex surface) ; cycles + boundaries surface (remove-inner-faces surface) ; remove inner faces _ (println (java.util.Date.) "\t triangulation") surface (triangulate-surface surface) ; triangulate graph (compute-adjlist (r/foldcat (r/mapcat :boundary surface))) surface (remove-suspicious-triangles surface) ; remove bad triangles _ (println (java.util.Date.) "\t convex holes") graph (compute-adjlist (r/foldcat (r/mapcat :boundary surface))) convex-holes (find-holes surface k-hood-of :metric graph) surface (r/cat surface (triangulate-surface convex-holes)) ; add convex holes _ (println (java.util.Date.) "\t non-convex holes") graph (compute-adjlist (r/foldcat (r/mapcat :boundary surface))) holes (find-holes surface k-hood-of) surface (r/cat surface (triangulate-surface holes))] (println (java.util.Date.) "\t done") (into #{} (r/foldcat (r/map (comp tri-to-set :cycle) surface))))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"} sr33.reconstruct (:require [clojure.set :as set] [clojure.core.memoize :as memo] [clojure.core.reducers :as r] [sr33.kdtree :as kdtree] [sr33.graph_theory :as theory])) (set! *warn-on-reflection* true) (set! *unchecked-math* true) ;; Compute an adjacency list (a hash map) from a collection of edges. (defn- compute-adjlist [edges] (letfn [(staple ([] {}) ([a b] (merge-with set/union a b))) (edge-to-map [uv] (let [u (first uv) v (second uv)] {u #{v} v #{u}})) (add-edge [adjlist edge] (merge-with set/union adjlist (edge-to-map edge)))] (r/fold staple add-edge edges))) ;; Generate a list of unique, non-trivial cycles that meet the point ;; with index u. In order to avoid duplicates from other local lists, ;; only cycles where all of the indices are smaller than u are ;; allowed. ;; ;; The ``graph'' parameter is the adjacency list in which cycles are ;; searched-for. The ``metric'' parameter is the adjacency list of ;; the graph in which distances are defined for purposes of finding ;; isometric cycles. These two might seemingly always be the same, ;; but they need to be distinct when looking for non-convex holes. (defn- cycles-at-u [graph metric hood u & extra] (let [hood (or hood (set (keys metric))) extra (set extra) compute-dist (memo/fifo (fn [s] (first (theory/Dijkstra metric hood s)))) eligible (set (filter #(< (long %) (long u)) hood)) compute-pi (memo/fifo (fn [s] (second (theory/Dijkstra graph eligible s))))] (letfn [(trace-path [a b pi] ; trace a path from a to be using the previous set pi (loop [current b path (list)] (cond (== (long current) (long a)) (conj path current) (== (long current) -1) nil :else (recur (get pi current -1) (conj path current))))) (isometric? [cycle] ; determine if cycle is isometric (let [n (dec (count cycle)) n-1 (dec n)] (loop [i 0 j 1] (cond (> i n-1) true ; no shortcuts found (> j n-1) (recur (+ i 1) (+ i 2)) ; next iteration of i :else ; check for shortcut (let [s (long (nth cycle i)) t (long (nth cycle j)) dist-cycle (long (min (- j i) (+ (- i j) n))) dist-metric (long (get (compute-dist (min s t)) (max s t)))] (if (< dist-metric dist-cycle) false ; not isometric (recur i (inc j))))))))] (let [neighbors (set/intersection eligible (get graph u #{})) candidate-cycles (for [a neighbors b neighbors :when (< (long a) (long b))] ; enforcing a < b ensures only one copy of each cycle (let [pi (compute-pi a) path (trace-path a b pi)] (if (not (nil? path)) (concat (list u) path (list u)) nil))) candidate-cycles (remove nil? candidate-cycles)] (if (contains? extra :no-isometry-test) candidate-cycles (filter isometric? candidate-cycles)))))) ;; Return the set of edges which bound the cycle. (defn- compute-boundary [cycle] (loop [cycle cycle edges (list)] (if (< (count cycle) 2) edges (recur (rest cycle) (conj edges #{(first cycle) (second cycle)}))))) ;; Turn a cycle into a cycle+boundary pair. (defn- cycle-to-complex [cycle] (hash-map :cycle cycle :boundary (compute-boundary cycle))) ;; Triangulate a (non-triangular) cycle by connecting the nearest pair ;; that is not already connected. (defn- triangulate-cycle [points cycle] (if (== 4 (count cycle)) ; triangle: report it, otherwise: split it (list cycle) (let [n (dec (count cycle)) dist-cycle (fn [i j] (let [i (long (second i)) j (long (second j))] (min (- j i) (+ (- i j) n)))) dist-euclidean (fn [u v] (let [u (first u) v (first v)] (theory/distance points u v)))] (let [cycle+ (map list cycle (range)) uv ; the following sexp returns the best edge at which to split (vec (loop [U (rest cycle+) V (rest (rest cycle+)) best nil best-dist Double/POSITIVE_INFINITY] (let [u (first U) v (first V)] (cond (nil? u) best ; done (nil? v) (recur (rest U) (rest (rest U)) best best-dist) ; increment (and (> (long (dist-cycle u v)) 1) (< (double (dist-euclidean u v)) best-dist)) (recur U (rest V) (list u v) (double (dist-euclidean u v))) ; uv is a better edge :else (recur U (rest V) best best-dist))))) [[_ i] [_ j]] uv cycle-1 (concat (take (+ 1 (long i)) cycle) (drop j cycle)) cycle-2 (concat (drop i (take (+ 1 (long j)) cycle)) (list (nth cycle i)))] (into (triangulate-cycle points cycle-1) (triangulate-cycle points cycle-2)))))) ;; Find holes in the surface. (defn- find-holes [surface neighborhood-of & extra] (let [edge-counts (frequencies (r/mapcat :boundary surface)) half-graph-E (r/map first (filter #(== 1 (long (val %))) edge-counts)) ; half-edges half-graph (compute-adjlist half-graph-E) ; half-edge graph half-graph-V (into [] (r/foldcat (r/flatten (r/map seq half-graph-E)))) ; half-edge graph vertices extra (apply hash-map extra) metric (get extra :metric false) isometry (if (not metric) :no-isometry-test nil) compute-holes (fn [u] (cycles-at-u half-graph (or metric half-graph) (neighborhood-of u) u isometry))] (r/foldcat (r/map cycle-to-complex (r/mapcat compute-holes half-graph-V))))) ;; Remove faces that are (likely to be) inside of the model (assuming ;; that it is closed). (defn- remove-inner-faces [surface] (let [edge-counts (frequencies (r/mapcat :boundary surface))] (letfn [(inner? [complex] (let [boundary (get complex :boundary) sum (double (reduce + (map edge-counts boundary))) avg-double (- (/ sum (count boundary)) 0.0001) avg-int (Math/round avg-double)] (> avg-int 2)))] (r/foldcat (r/remove inner? surface))))) (defmacro remove-x-triangles [surface predicate quantifier] `(let [edge-counts# (frequencies (r/mapcat :boundary ~surface)) edges# (into #{} (r/foldcat (r/map first (filter ~predicate edge-counts#)))) x?# (fn [complex#] (~quantifier edges# (get complex# :boundary)))] (r/foldcat (r/remove x?# ~surface)))) (defn- remove-suspicious-triangles [surface] (remove-x-triangles surface #(> (long (val %)) 2) #'some)) ;; Recover a surface from an organized collection of point samples by ;; computing a subset of the Delaunay Triangulation (assuming the ;; sample conditions hold) then triangulating the resulting cycles. (defn compute-surface [points k] (let [kdtree (kdtree/build points) n (count points) k-hood-of (memo/fifo (fn [u] (set (map :index (kdtree/query (nth points u) kdtree k)))) :fifo/threshold (inc n)) triangulate-surface (fn [surface] (r/foldcat (r/map cycle-to-complex (r/mapcat #(triangulate-cycle points %) (r/map :cycle surface))))) tri-to-set (fn [face] (set (take 3 face)))] (let [_ (println (java.util.Date.) "\t edges") edges (theory/RNG points n k-hood-of) ; relative neighborhood graph _ (println (java.util.Date.) "\t isometric cycles") graph (compute-adjlist edges) ; adjacency list of the same compute-cycles (fn [u] (cycles-at-u graph graph (k-hood-of u) u)) surface (r/foldcat (r/mapcat compute-cycles (into [] (range n)))) ; isometric cycles surface (r/map cycle-to-complex surface) ; cycles + boundaries surface (remove-inner-faces surface) ; remove inner faces _ (println (java.util.Date.) "\t triangulation") surface (triangulate-surface surface) ; triangulate graph (compute-adjlist (r/foldcat (r/mapcat :boundary surface))) surface (remove-suspicious-triangles surface) ; remove bad triangles _ (println (java.util.Date.) "\t convex holes") graph (compute-adjlist (r/foldcat (r/mapcat :boundary surface))) convex-holes (find-holes surface k-hood-of :metric graph) surface (r/cat surface (triangulate-surface convex-holes)) ; add convex holes _ (println (java.util.Date.) "\t non-convex holes") graph (compute-adjlist (r/foldcat (r/mapcat :boundary surface))) holes (find-holes surface k-hood-of) surface (r/cat surface (triangulate-surface holes))] (println (java.util.Date.) "\t done") (into #{} (r/foldcat (r/map (comp tri-to-set :cycle) surface))))))
[ { "context": "ke a pucks program that does anything\n;; Student : Nirman Dave\n\n;; Program information\n;; ---\n;; Name : Pucksea ", "end": 187, "score": 0.9998847842216492, "start": 176, "tag": "NAME", "value": "Nirman Dave" } ]
puckseaworld.clj
nddave/Pucksea
0
;; This is my canvas. This is my art. ;; Assignment information ;; --- ;; Class : Artificial Intelligence ;; Assignment : Make a pucks program that does anything ;; Student : Nirman Dave ;; Program information ;; --- ;; Name : Pucksea : The world file ;; Version : 1.0 ;; Description : An AI pucks program that has a user puck which avoids zappers (loss of energy) ;; and navigates towards vents (to gain energy). When faced with another fellow ;; user puck, it moves away. Because they are too shy. ;; This file is the Pucksea file, which is the "world" the "pucks" will live in. ;; Language : Clojure ;; Importing default liberaries, name space and defining file(s) that contain ;; global variables that will be used throughout the program. (ns pucks.worlds.ai.puckseaworld (:use [pucks core globals] [pucks.agents stone vent zapper user])) ;; The agents are the things you will see when the world starts up. ;; This is a set of different pucks floating in the Pucksea world. (defn agents [] (concat [ ;; The following define the zapper puck and thier relative position ;; in the Pucksea world. (merge (zapper) {:position [200 600]}) (merge (zapper) {:position [200 200]}) (merge (zapper) {:position [600 200]}) ;; The following define the vent puck and its relative position ;; in the Pucksea world. (merge (vent) {:position [600 600]}) ;; There are two sets of user pucks in this world. ;; The user pucks are mobile (unlike zapper and vent). ;; == User pucks : First Set == ;; The first set contains a set of user pucks from one single location ;; facing in one single direction. (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) ;; == User pucks : Second Set == ;; The first set contains a set of user pucks from random locations ;; facing in one single direction. ;; -- ;; To unlock this set, uncomment the lines below. ;; and comment the first set. ;; -- ; (merge (user) {:position [20 400] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [230 300] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [90 80] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [50 70] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [170 150] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [100 30] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [0 0] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [32 16] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [413 567] :rotation (/ Math/PI 2)}) ])) ;; User settings below define what happens with the main frame when it loads up. (defn settings [] ;; Pauses the game play when it starts. So the user has to trigger the spacebar ;; to resume the game play. {:pause-on-start true}) ;; For wierd people who use night code instead of sublime text or other IDES. ;; Please uncomment the code below to make this run properly. ;(run-pucks (agents) (settings))
99430
;; This is my canvas. This is my art. ;; Assignment information ;; --- ;; Class : Artificial Intelligence ;; Assignment : Make a pucks program that does anything ;; Student : <NAME> ;; Program information ;; --- ;; Name : Pucksea : The world file ;; Version : 1.0 ;; Description : An AI pucks program that has a user puck which avoids zappers (loss of energy) ;; and navigates towards vents (to gain energy). When faced with another fellow ;; user puck, it moves away. Because they are too shy. ;; This file is the Pucksea file, which is the "world" the "pucks" will live in. ;; Language : Clojure ;; Importing default liberaries, name space and defining file(s) that contain ;; global variables that will be used throughout the program. (ns pucks.worlds.ai.puckseaworld (:use [pucks core globals] [pucks.agents stone vent zapper user])) ;; The agents are the things you will see when the world starts up. ;; This is a set of different pucks floating in the Pucksea world. (defn agents [] (concat [ ;; The following define the zapper puck and thier relative position ;; in the Pucksea world. (merge (zapper) {:position [200 600]}) (merge (zapper) {:position [200 200]}) (merge (zapper) {:position [600 200]}) ;; The following define the vent puck and its relative position ;; in the Pucksea world. (merge (vent) {:position [600 600]}) ;; There are two sets of user pucks in this world. ;; The user pucks are mobile (unlike zapper and vent). ;; == User pucks : First Set == ;; The first set contains a set of user pucks from one single location ;; facing in one single direction. (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) ;; == User pucks : Second Set == ;; The first set contains a set of user pucks from random locations ;; facing in one single direction. ;; -- ;; To unlock this set, uncomment the lines below. ;; and comment the first set. ;; -- ; (merge (user) {:position [20 400] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [230 300] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [90 80] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [50 70] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [170 150] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [100 30] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [0 0] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [32 16] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [413 567] :rotation (/ Math/PI 2)}) ])) ;; User settings below define what happens with the main frame when it loads up. (defn settings [] ;; Pauses the game play when it starts. So the user has to trigger the spacebar ;; to resume the game play. {:pause-on-start true}) ;; For wierd people who use night code instead of sublime text or other IDES. ;; Please uncomment the code below to make this run properly. ;(run-pucks (agents) (settings))
true
;; This is my canvas. This is my art. ;; Assignment information ;; --- ;; Class : Artificial Intelligence ;; Assignment : Make a pucks program that does anything ;; Student : PI:NAME:<NAME>END_PI ;; Program information ;; --- ;; Name : Pucksea : The world file ;; Version : 1.0 ;; Description : An AI pucks program that has a user puck which avoids zappers (loss of energy) ;; and navigates towards vents (to gain energy). When faced with another fellow ;; user puck, it moves away. Because they are too shy. ;; This file is the Pucksea file, which is the "world" the "pucks" will live in. ;; Language : Clojure ;; Importing default liberaries, name space and defining file(s) that contain ;; global variables that will be used throughout the program. (ns pucks.worlds.ai.puckseaworld (:use [pucks core globals] [pucks.agents stone vent zapper user])) ;; The agents are the things you will see when the world starts up. ;; This is a set of different pucks floating in the Pucksea world. (defn agents [] (concat [ ;; The following define the zapper puck and thier relative position ;; in the Pucksea world. (merge (zapper) {:position [200 600]}) (merge (zapper) {:position [200 200]}) (merge (zapper) {:position [600 200]}) ;; The following define the vent puck and its relative position ;; in the Pucksea world. (merge (vent) {:position [600 600]}) ;; There are two sets of user pucks in this world. ;; The user pucks are mobile (unlike zapper and vent). ;; == User pucks : First Set == ;; The first set contains a set of user pucks from one single location ;; facing in one single direction. (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) (merge (user) {:position [1 1] :rotation (/ Math/PI 2)}) ;; == User pucks : Second Set == ;; The first set contains a set of user pucks from random locations ;; facing in one single direction. ;; -- ;; To unlock this set, uncomment the lines below. ;; and comment the first set. ;; -- ; (merge (user) {:position [20 400] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [230 300] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [90 80] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [50 70] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [170 150] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [100 30] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [0 0] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [32 16] :rotation (/ Math/PI 2)}) ; (merge (user) {:position [413 567] :rotation (/ Math/PI 2)}) ])) ;; User settings below define what happens with the main frame when it loads up. (defn settings [] ;; Pauses the game play when it starts. So the user has to trigger the spacebar ;; to resume the game play. {:pause-on-start true}) ;; For wierd people who use night code instead of sublime text or other IDES. ;; Please uncomment the code below to make this run properly. ;(run-pucks (agents) (settings))
[ { "context": "; Copyright © 2013 - 2016 Dr. Thomas Schank <Thomas.Schank@AlgoCon.ch>\n; Licensed under the t", "end": 43, "score": 0.999816358089447, "start": 30, "tag": "NAME", "value": "Thomas Schank" }, { "context": "; Copyright © 2013 - 2016 Dr. Thomas Schank <Thomas.Schank@AlgoCon.ch>\n; Licensed under the terms of the GNU Affero Gen", "end": 69, "score": 0.999893844127655, "start": 45, "tag": "EMAIL", "value": "Thomas.Schank@AlgoCon.ch" } ]
data/test/clojure/55c9ee0295907ba0f57fb9cece455a378991725dtimeout_sweeper.clj
harshp8l/deep-learning-lang-detection
84
; Copyright © 2013 - 2016 Dr. Thomas Schank <Thomas.Schank@AlgoCon.ch> ; Licensed under the terms of the GNU Affero General Public License v3. ; See the "LICENSE.txt" file provided with this software. (ns cider-ci.dispatcher.dispatch.timeout-sweeper (:require [cider-ci.dispatcher.trials :as trials] [cider-ci.utils.config :as config :refer [get-config]] [cider-ci.utils.daemon :as daemon :refer [defdaemon]] [cider-ci.utils.rdbms :as rdbms :refer [get-ds]] [clojure.java.jdbc :as jdbc] [honeysql.sql :refer :all] [clojure.tools.logging :as logging] [logbug.catcher :as catcher] [logbug.debug :as debug] )) (defn ^:private dispatch-timeout-query [] (when-let [trial_dispatch_timeout (:trial_dispatch_timeout (get-config))] (-> (sql-select :id) (sql-from :trials) (sql-merge-where [:= :state "pending"]) (sql-merge-where (sql-raw (str "(created_at < (now() - interval '" trial_dispatch_timeout "'))"))) (sql-format)))) (defn ^:private sweep-in-dispatch-timeout [] (catcher/snatch {} (jdbc/with-db-transaction [tx (rdbms/get-ds)] (doseq [id (->> (dispatch-timeout-query) (jdbc/query tx) (map :id))] (catcher/snatch {} (jdbc/update! tx :trials {:state "aborted"} ["id = ? " id]) (jdbc/insert! tx :trial_issues {:trial_id id :title "Aborted due to Dispatch Timeout" :description (str "This trail has been aborted because it " " could not have been dispatched within the" " configured `trial_dispatch_timeout`.")})))))) (defdaemon "sweep-in-dispatch-timeout" 1 (sweep-in-dispatch-timeout)) (defn initialize [] (start-sweep-in-dispatch-timeout)) ;#### debug ################################################################### ;(debug/debug-ns *ns*) ;(logging-config/set-logger! :level :debug) ;(logging-config/set-logger! :level :info)
96784
; Copyright © 2013 - 2016 Dr. <NAME> <<EMAIL>> ; Licensed under the terms of the GNU Affero General Public License v3. ; See the "LICENSE.txt" file provided with this software. (ns cider-ci.dispatcher.dispatch.timeout-sweeper (:require [cider-ci.dispatcher.trials :as trials] [cider-ci.utils.config :as config :refer [get-config]] [cider-ci.utils.daemon :as daemon :refer [defdaemon]] [cider-ci.utils.rdbms :as rdbms :refer [get-ds]] [clojure.java.jdbc :as jdbc] [honeysql.sql :refer :all] [clojure.tools.logging :as logging] [logbug.catcher :as catcher] [logbug.debug :as debug] )) (defn ^:private dispatch-timeout-query [] (when-let [trial_dispatch_timeout (:trial_dispatch_timeout (get-config))] (-> (sql-select :id) (sql-from :trials) (sql-merge-where [:= :state "pending"]) (sql-merge-where (sql-raw (str "(created_at < (now() - interval '" trial_dispatch_timeout "'))"))) (sql-format)))) (defn ^:private sweep-in-dispatch-timeout [] (catcher/snatch {} (jdbc/with-db-transaction [tx (rdbms/get-ds)] (doseq [id (->> (dispatch-timeout-query) (jdbc/query tx) (map :id))] (catcher/snatch {} (jdbc/update! tx :trials {:state "aborted"} ["id = ? " id]) (jdbc/insert! tx :trial_issues {:trial_id id :title "Aborted due to Dispatch Timeout" :description (str "This trail has been aborted because it " " could not have been dispatched within the" " configured `trial_dispatch_timeout`.")})))))) (defdaemon "sweep-in-dispatch-timeout" 1 (sweep-in-dispatch-timeout)) (defn initialize [] (start-sweep-in-dispatch-timeout)) ;#### debug ################################################################### ;(debug/debug-ns *ns*) ;(logging-config/set-logger! :level :debug) ;(logging-config/set-logger! :level :info)
true
; Copyright © 2013 - 2016 Dr. PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ; Licensed under the terms of the GNU Affero General Public License v3. ; See the "LICENSE.txt" file provided with this software. (ns cider-ci.dispatcher.dispatch.timeout-sweeper (:require [cider-ci.dispatcher.trials :as trials] [cider-ci.utils.config :as config :refer [get-config]] [cider-ci.utils.daemon :as daemon :refer [defdaemon]] [cider-ci.utils.rdbms :as rdbms :refer [get-ds]] [clojure.java.jdbc :as jdbc] [honeysql.sql :refer :all] [clojure.tools.logging :as logging] [logbug.catcher :as catcher] [logbug.debug :as debug] )) (defn ^:private dispatch-timeout-query [] (when-let [trial_dispatch_timeout (:trial_dispatch_timeout (get-config))] (-> (sql-select :id) (sql-from :trials) (sql-merge-where [:= :state "pending"]) (sql-merge-where (sql-raw (str "(created_at < (now() - interval '" trial_dispatch_timeout "'))"))) (sql-format)))) (defn ^:private sweep-in-dispatch-timeout [] (catcher/snatch {} (jdbc/with-db-transaction [tx (rdbms/get-ds)] (doseq [id (->> (dispatch-timeout-query) (jdbc/query tx) (map :id))] (catcher/snatch {} (jdbc/update! tx :trials {:state "aborted"} ["id = ? " id]) (jdbc/insert! tx :trial_issues {:trial_id id :title "Aborted due to Dispatch Timeout" :description (str "This trail has been aborted because it " " could not have been dispatched within the" " configured `trial_dispatch_timeout`.")})))))) (defdaemon "sweep-in-dispatch-timeout" 1 (sweep-in-dispatch-timeout)) (defn initialize [] (start-sweep-in-dispatch-timeout)) ;#### debug ################################################################### ;(debug/debug-ns *ns*) ;(logging-config/set-logger! :level :debug) ;(logging-config/set-logger! :level :info)
[ { "context": " \n {:doc \"compute a file checksum.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2018-01-03\"}\n \n (:require [clojur", "end": 269, "score": 0.8297030925750732, "start": 233, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/curate/scripts/checksum.clj
palisades-lakes/curate
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.scripts.checksum {:doc "compute a file checksum." :author "palisades dot lakes at gmail dot com" :version "2018-01-03"} (:require [clojure.java.io :as io]) (:use [clojure.set :only [difference]]) (:gen-class)) ;;---------------------------------------------------------------- (defn checksum [file] (let [input (java.io.FileInputStream. file) digest (java.security.MessageDigest/getInstance "MD5") stream (java.security.DigestInputStream. input digest) bufsize (* 1024 1024) buf (byte-array bufsize)] (while (not= -1 (.read stream buf 0 bufsize))) (apply str (map (partial format "%02x") (.digest digest))))) (defn list-dir [dir] (remove #(.isDirectory %) (file-seq (java.io.File. dir)))) (defn find-dupes [root] (let [files (list-dir root)] (let [summed (zipmap (pmap #(checksum %) files) files)] (difference (into #{} files) (into #{} (vals summed)))))) (defn remove-dupes [files] (prn "Duplicates files to be removed:") (doseq [f files] (prn (.toString f))) (prn "Delete files? [y/n]:") (if-let [choice (= (read-line) "y")] (doseq [f files] (println (.getName ^java.io.File f)) #_(.delete f)))) (defn -main [& args] (if (empty? args) (println "Enter a root directory") (remove-dupes (find-dupes (first args)))) (System/exit 0)) ;;----------------------------------------------------------------
33177
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.scripts.checksum {:doc "compute a file checksum." :author "<EMAIL>" :version "2018-01-03"} (:require [clojure.java.io :as io]) (:use [clojure.set :only [difference]]) (:gen-class)) ;;---------------------------------------------------------------- (defn checksum [file] (let [input (java.io.FileInputStream. file) digest (java.security.MessageDigest/getInstance "MD5") stream (java.security.DigestInputStream. input digest) bufsize (* 1024 1024) buf (byte-array bufsize)] (while (not= -1 (.read stream buf 0 bufsize))) (apply str (map (partial format "%02x") (.digest digest))))) (defn list-dir [dir] (remove #(.isDirectory %) (file-seq (java.io.File. dir)))) (defn find-dupes [root] (let [files (list-dir root)] (let [summed (zipmap (pmap #(checksum %) files) files)] (difference (into #{} files) (into #{} (vals summed)))))) (defn remove-dupes [files] (prn "Duplicates files to be removed:") (doseq [f files] (prn (.toString f))) (prn "Delete files? [y/n]:") (if-let [choice (= (read-line) "y")] (doseq [f files] (println (.getName ^java.io.File f)) #_(.delete f)))) (defn -main [& args] (if (empty? args) (println "Enter a root directory") (remove-dupes (find-dupes (first args)))) (System/exit 0)) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.scripts.checksum {:doc "compute a file checksum." :author "PI:EMAIL:<EMAIL>END_PI" :version "2018-01-03"} (:require [clojure.java.io :as io]) (:use [clojure.set :only [difference]]) (:gen-class)) ;;---------------------------------------------------------------- (defn checksum [file] (let [input (java.io.FileInputStream. file) digest (java.security.MessageDigest/getInstance "MD5") stream (java.security.DigestInputStream. input digest) bufsize (* 1024 1024) buf (byte-array bufsize)] (while (not= -1 (.read stream buf 0 bufsize))) (apply str (map (partial format "%02x") (.digest digest))))) (defn list-dir [dir] (remove #(.isDirectory %) (file-seq (java.io.File. dir)))) (defn find-dupes [root] (let [files (list-dir root)] (let [summed (zipmap (pmap #(checksum %) files) files)] (difference (into #{} files) (into #{} (vals summed)))))) (defn remove-dupes [files] (prn "Duplicates files to be removed:") (doseq [f files] (prn (.toString f))) (prn "Delete files? [y/n]:") (if-let [choice (= (read-line) "y")] (doseq [f files] (println (.getName ^java.io.File f)) #_(.delete f)))) (defn -main [& args] (if (empty? args) (println "Enter a root directory") (remove-dupes (find-dupes (first args)))) (System/exit 0)) ;;----------------------------------------------------------------
[ { "context": "l password :as request] (update request {:username username :email email :password password}))\n (DELETE (:", "end": 5032, "score": 0.9901266098022461, "start": 5024, "tag": "USERNAME", "value": "username" }, { "context": "request {:username username :email email :password password}))\n (DELETE (:show route-map) [username] (del", "end": 5064, "score": 0.9945870637893677, "start": 5056, "tag": "PASSWORD", "value": "password" } ]
src/quackers/users.clj
innoq/quackers
13
(ns quackers.users (:require [compojure.core :refer :all] [quackers.helpers :refer [->int] :as h] [clojure.tools.logging :as log] [quackers.database :as db] [ring.util.response :refer [redirect]] [bouncer.core :as b] [bouncer.validators :as v] [buddy.auth :refer [authenticated?]] [buddy.hashers :as hashers])) (def route-map (let [basepath "/users" show (str basepath "/:username")] {:index basepath :new (str basepath "/new") :show show :edit (str show "/edit")})) (defn create-user! [usermap] (let [password (:password usermap) digest (hashers/encrypt password) newmap (assoc usermap :password digest)] (db/add-user! newmap) newmap)) (defn update-password! [usermap] (let [password (:password usermap) digest (hashers/encrypt password) newmap (assoc usermap :password digest)] (db/update-user-password!) newmap)) (defn update-password! [usermap] (when-let [password (:password usermap)] (let [digest (hashers/encrypt password) newmap (assoc usermap :password digest)] (db/update-user-password! newmap) newmap))) (defn valid-username? [username] (b/valid? {:username username} :username [v/required v/string])) (defn validate-user-create [usermap] (b/validate usermap :username [v/required v/string] :email [v/string [v/matches h/email-regex :message "invalid email"]] :password [v/required v/string])) (defn validate-user-update [usermap] (b/validate usermap :username [v/required v/string] :email [v/string [v/matches h/email-regex :message "invalid email"]] :password v/string)) (defn create-form [request user] (h/render request "templates/users/create.html" user)) (defn create-user [request user] (log/info :create (dissoc user :password)) (let [[errors validated] (validate-user-create user)] (if errors (create-form request (assoc user :errors errors)) (if (first (db/get-user user)) (create-form request (assoc user :errors {:username ["already exists"]})) (let [new-user (create-user! user)] (redirect (:index route-map))))))) (defn index [request] (let [users (db/get-users)] (h/render request "templates/users/index.html" {:users users}))) (defn show [request username] (log/info :show username) (when (valid-username? username) (let [user (first (db/get-user {:username username}))] (when user (let [limit (->int (get-in request [:query-params "limit"] "10")) offset (->int (get-in request [:query-params "offset"] "0")) quacks (db/get-quacks-for-user {:limit limit :offset offset :username username})] (h/render request "templates/users/show.html" (assoc user :quacks quacks :limit limit :offset offset :back (- offset limit) :forward? (>= (count quacks) limit)))))))) (defn delete [username] (log/info :delete username) (when (valid-username? username) (let [_ (db/delete-user! {:username username})] (redirect (:index route-map))))) (defn edit-form [request user] (h/render request "templates/users/edit.html" user)) (defn edit [request username] (log/info :edit username) (when (valid-username? username) (let [user (first (db/get-user {:username username}))] (if user (edit-form request (dissoc user :password)))))) (defn update [request user] (log/info :update (dissoc user :password)) (let [to-validate (if (empty? (:password user)) (dissoc user :password) user)] (let [[errors validated] (validate-user-update to-validate)] (if errors (edit-form request (assoc to-validate :errors errors)) (let [_ (update-password! to-validate) _ (db/update-user-email! to-validate)] (redirect (:index route-map))))))) (defn is-user? [request] (when-let [{user :user} (:identity request)] (= user (get-in request [:match-params :username])))) (def user-auth-rules [{:uri (:index route-map) :handler authenticated? :request-method :get} {:uri (:edit route-map) :handler is-user?} {:uri (:show route-map) :handler is-user? :request-method #{:put :delete :post}}]) (defn user-routes [] (routes (GET (:index route-map) request (index request)) (GET (:new route-map) request (create-form request {})) (POST (:index route-map) {params :params :as request} (create-user request params)) (GET (:show route-map) [username :as request] (show request username)) (GET (:edit route-map) [username :as request] (edit request username)) (PUT (:show route-map) [username email password :as request] (update request {:username username :email email :password password})) (DELETE (:show route-map) [username] (delete username))))
64399
(ns quackers.users (:require [compojure.core :refer :all] [quackers.helpers :refer [->int] :as h] [clojure.tools.logging :as log] [quackers.database :as db] [ring.util.response :refer [redirect]] [bouncer.core :as b] [bouncer.validators :as v] [buddy.auth :refer [authenticated?]] [buddy.hashers :as hashers])) (def route-map (let [basepath "/users" show (str basepath "/:username")] {:index basepath :new (str basepath "/new") :show show :edit (str show "/edit")})) (defn create-user! [usermap] (let [password (:password usermap) digest (hashers/encrypt password) newmap (assoc usermap :password digest)] (db/add-user! newmap) newmap)) (defn update-password! [usermap] (let [password (:password usermap) digest (hashers/encrypt password) newmap (assoc usermap :password digest)] (db/update-user-password!) newmap)) (defn update-password! [usermap] (when-let [password (:password usermap)] (let [digest (hashers/encrypt password) newmap (assoc usermap :password digest)] (db/update-user-password! newmap) newmap))) (defn valid-username? [username] (b/valid? {:username username} :username [v/required v/string])) (defn validate-user-create [usermap] (b/validate usermap :username [v/required v/string] :email [v/string [v/matches h/email-regex :message "invalid email"]] :password [v/required v/string])) (defn validate-user-update [usermap] (b/validate usermap :username [v/required v/string] :email [v/string [v/matches h/email-regex :message "invalid email"]] :password v/string)) (defn create-form [request user] (h/render request "templates/users/create.html" user)) (defn create-user [request user] (log/info :create (dissoc user :password)) (let [[errors validated] (validate-user-create user)] (if errors (create-form request (assoc user :errors errors)) (if (first (db/get-user user)) (create-form request (assoc user :errors {:username ["already exists"]})) (let [new-user (create-user! user)] (redirect (:index route-map))))))) (defn index [request] (let [users (db/get-users)] (h/render request "templates/users/index.html" {:users users}))) (defn show [request username] (log/info :show username) (when (valid-username? username) (let [user (first (db/get-user {:username username}))] (when user (let [limit (->int (get-in request [:query-params "limit"] "10")) offset (->int (get-in request [:query-params "offset"] "0")) quacks (db/get-quacks-for-user {:limit limit :offset offset :username username})] (h/render request "templates/users/show.html" (assoc user :quacks quacks :limit limit :offset offset :back (- offset limit) :forward? (>= (count quacks) limit)))))))) (defn delete [username] (log/info :delete username) (when (valid-username? username) (let [_ (db/delete-user! {:username username})] (redirect (:index route-map))))) (defn edit-form [request user] (h/render request "templates/users/edit.html" user)) (defn edit [request username] (log/info :edit username) (when (valid-username? username) (let [user (first (db/get-user {:username username}))] (if user (edit-form request (dissoc user :password)))))) (defn update [request user] (log/info :update (dissoc user :password)) (let [to-validate (if (empty? (:password user)) (dissoc user :password) user)] (let [[errors validated] (validate-user-update to-validate)] (if errors (edit-form request (assoc to-validate :errors errors)) (let [_ (update-password! to-validate) _ (db/update-user-email! to-validate)] (redirect (:index route-map))))))) (defn is-user? [request] (when-let [{user :user} (:identity request)] (= user (get-in request [:match-params :username])))) (def user-auth-rules [{:uri (:index route-map) :handler authenticated? :request-method :get} {:uri (:edit route-map) :handler is-user?} {:uri (:show route-map) :handler is-user? :request-method #{:put :delete :post}}]) (defn user-routes [] (routes (GET (:index route-map) request (index request)) (GET (:new route-map) request (create-form request {})) (POST (:index route-map) {params :params :as request} (create-user request params)) (GET (:show route-map) [username :as request] (show request username)) (GET (:edit route-map) [username :as request] (edit request username)) (PUT (:show route-map) [username email password :as request] (update request {:username username :email email :password <PASSWORD>})) (DELETE (:show route-map) [username] (delete username))))
true
(ns quackers.users (:require [compojure.core :refer :all] [quackers.helpers :refer [->int] :as h] [clojure.tools.logging :as log] [quackers.database :as db] [ring.util.response :refer [redirect]] [bouncer.core :as b] [bouncer.validators :as v] [buddy.auth :refer [authenticated?]] [buddy.hashers :as hashers])) (def route-map (let [basepath "/users" show (str basepath "/:username")] {:index basepath :new (str basepath "/new") :show show :edit (str show "/edit")})) (defn create-user! [usermap] (let [password (:password usermap) digest (hashers/encrypt password) newmap (assoc usermap :password digest)] (db/add-user! newmap) newmap)) (defn update-password! [usermap] (let [password (:password usermap) digest (hashers/encrypt password) newmap (assoc usermap :password digest)] (db/update-user-password!) newmap)) (defn update-password! [usermap] (when-let [password (:password usermap)] (let [digest (hashers/encrypt password) newmap (assoc usermap :password digest)] (db/update-user-password! newmap) newmap))) (defn valid-username? [username] (b/valid? {:username username} :username [v/required v/string])) (defn validate-user-create [usermap] (b/validate usermap :username [v/required v/string] :email [v/string [v/matches h/email-regex :message "invalid email"]] :password [v/required v/string])) (defn validate-user-update [usermap] (b/validate usermap :username [v/required v/string] :email [v/string [v/matches h/email-regex :message "invalid email"]] :password v/string)) (defn create-form [request user] (h/render request "templates/users/create.html" user)) (defn create-user [request user] (log/info :create (dissoc user :password)) (let [[errors validated] (validate-user-create user)] (if errors (create-form request (assoc user :errors errors)) (if (first (db/get-user user)) (create-form request (assoc user :errors {:username ["already exists"]})) (let [new-user (create-user! user)] (redirect (:index route-map))))))) (defn index [request] (let [users (db/get-users)] (h/render request "templates/users/index.html" {:users users}))) (defn show [request username] (log/info :show username) (when (valid-username? username) (let [user (first (db/get-user {:username username}))] (when user (let [limit (->int (get-in request [:query-params "limit"] "10")) offset (->int (get-in request [:query-params "offset"] "0")) quacks (db/get-quacks-for-user {:limit limit :offset offset :username username})] (h/render request "templates/users/show.html" (assoc user :quacks quacks :limit limit :offset offset :back (- offset limit) :forward? (>= (count quacks) limit)))))))) (defn delete [username] (log/info :delete username) (when (valid-username? username) (let [_ (db/delete-user! {:username username})] (redirect (:index route-map))))) (defn edit-form [request user] (h/render request "templates/users/edit.html" user)) (defn edit [request username] (log/info :edit username) (when (valid-username? username) (let [user (first (db/get-user {:username username}))] (if user (edit-form request (dissoc user :password)))))) (defn update [request user] (log/info :update (dissoc user :password)) (let [to-validate (if (empty? (:password user)) (dissoc user :password) user)] (let [[errors validated] (validate-user-update to-validate)] (if errors (edit-form request (assoc to-validate :errors errors)) (let [_ (update-password! to-validate) _ (db/update-user-email! to-validate)] (redirect (:index route-map))))))) (defn is-user? [request] (when-let [{user :user} (:identity request)] (= user (get-in request [:match-params :username])))) (def user-auth-rules [{:uri (:index route-map) :handler authenticated? :request-method :get} {:uri (:edit route-map) :handler is-user?} {:uri (:show route-map) :handler is-user? :request-method #{:put :delete :post}}]) (defn user-routes [] (routes (GET (:index route-map) request (index request)) (GET (:new route-map) request (create-form request {})) (POST (:index route-map) {params :params :as request} (create-user request params)) (GET (:show route-map) [username :as request] (show request username)) (GET (:edit route-map) [username :as request] (edit request username)) (PUT (:show route-map) [username email password :as request] (update request {:username username :email email :password PI:PASSWORD:<PASSWORD>END_PI})) (DELETE (:show route-map) [username] (delete username))))
[ { "context": ";; Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; ", "end": 31, "score": 0.9998756647109985, "start": 19, "tag": "NAME", "value": "Di Sera Luca" }, { "context": " Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; https://github.com/diseraluc", "end": 74, "score": 0.9999313354492188, "start": 53, "tag": "EMAIL", "value": "disera.luca@gmail.com" }, { "context": "gmail.com\n;; https://github.com/diseraluca\n;; https://www.linkedin.com/in/", "end": 125, "score": 0.9996578693389893, "start": 115, "tag": "USERNAME", "value": "diseraluca" }, { "context": "\n;; https://www.linkedin.com/in/luca-di-sera-200023167\n;;\n;; This code is licensed under the MIT License", "end": 197, "score": 0.9995183348655701, "start": 175, "tag": "USERNAME", "value": "luca-di-sera-200023167" } ]
pmal/src/pmal/server/routes/core.clj
diseraluca/pmal
0
;; Copyright 2020, Di Sera Luca ;; Contacts: disera.luca@gmail.com ;; https://github.com/diseraluca ;; https://www.linkedin.com/in/luca-di-sera-200023167 ;; ;; This code is licensed under the MIT License. ;; More information can be found in the LICENSE file in the root of this repository (ns pmal.server.routes.core (:require [pmal.server.routes.api :as api])) (def routes [api/routes])
101447
;; Copyright 2020, <NAME> ;; Contacts: <EMAIL> ;; https://github.com/diseraluca ;; https://www.linkedin.com/in/luca-di-sera-200023167 ;; ;; This code is licensed under the MIT License. ;; More information can be found in the LICENSE file in the root of this repository (ns pmal.server.routes.core (:require [pmal.server.routes.api :as api])) (def routes [api/routes])
true
;; Copyright 2020, PI:NAME:<NAME>END_PI ;; Contacts: PI:EMAIL:<EMAIL>END_PI ;; https://github.com/diseraluca ;; https://www.linkedin.com/in/luca-di-sera-200023167 ;; ;; This code is licensed under the MIT License. ;; More information can be found in the LICENSE file in the root of this repository (ns pmal.server.routes.core (:require [pmal.server.routes.api :as api])) (def routes [api/routes])
[ { "context": "file is part of esri-api.\n;;;;\n;;;; Copyright 2020 Alexander Dorn\n;;;;\n;;;; Licensed under the Apache License, Vers", "end": 75, "score": 0.9998596906661987, "start": 61, "tag": "NAME", "value": "Alexander Dorn" } ]
test/esri_api/view/properties.clj
e-user/esri-api
0
;;;; This file is part of esri-api. ;;;; ;;;; Copyright 2020 Alexander Dorn ;;;; ;;;; 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 esri_api.view.properties (:require [esri_api.view :as view] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.properties :as prop] [clojure.string :as string] [clojure.set :as set] [java-time :refer [with-zone local-date-time instant]] [java-time.format]) (:import [java.time LocalDateTime ZoneId])) (def date-formatter (with-zone (java-time.format/formatter "yyyy-MM-dd'T'HH:mm:ss") "UTC")) (def iso-date (gen/fmap #(LocalDateTime/ofInstant (instant %) (ZoneId/of "UTC")) (gen/large-integer* {:min 1000}))) (def csv-data (gen/let [n gen/nat ks (gen/vector gen/keyword n)] (gen/vector (gen/fmap (fn [[d v]] (zipmap (conj ks :STR_DATUM) (conj v d))) (gen/tuple iso-date (gen/vector (gen/not-empty gen/string-alphanumeric) n)))))) (defspec counting-by-years-maps-years-to-buildings (prop/for-all [v csv-data] (let [csv (view/by-year v)] (for [k (keys csv)] (Long/parseLong k)) (for [vs (vals csv)] (or (empty? vs) (= (count (dedupe (map keys vs))) 1))))))
47923
;;;; This file is part of esri-api. ;;;; ;;;; 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 esri_api.view.properties (:require [esri_api.view :as view] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.properties :as prop] [clojure.string :as string] [clojure.set :as set] [java-time :refer [with-zone local-date-time instant]] [java-time.format]) (:import [java.time LocalDateTime ZoneId])) (def date-formatter (with-zone (java-time.format/formatter "yyyy-MM-dd'T'HH:mm:ss") "UTC")) (def iso-date (gen/fmap #(LocalDateTime/ofInstant (instant %) (ZoneId/of "UTC")) (gen/large-integer* {:min 1000}))) (def csv-data (gen/let [n gen/nat ks (gen/vector gen/keyword n)] (gen/vector (gen/fmap (fn [[d v]] (zipmap (conj ks :STR_DATUM) (conj v d))) (gen/tuple iso-date (gen/vector (gen/not-empty gen/string-alphanumeric) n)))))) (defspec counting-by-years-maps-years-to-buildings (prop/for-all [v csv-data] (let [csv (view/by-year v)] (for [k (keys csv)] (Long/parseLong k)) (for [vs (vals csv)] (or (empty? vs) (= (count (dedupe (map keys vs))) 1))))))
true
;;;; This file is part of esri-api. ;;;; ;;;; 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 esri_api.view.properties (:require [esri_api.view :as view] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.properties :as prop] [clojure.string :as string] [clojure.set :as set] [java-time :refer [with-zone local-date-time instant]] [java-time.format]) (:import [java.time LocalDateTime ZoneId])) (def date-formatter (with-zone (java-time.format/formatter "yyyy-MM-dd'T'HH:mm:ss") "UTC")) (def iso-date (gen/fmap #(LocalDateTime/ofInstant (instant %) (ZoneId/of "UTC")) (gen/large-integer* {:min 1000}))) (def csv-data (gen/let [n gen/nat ks (gen/vector gen/keyword n)] (gen/vector (gen/fmap (fn [[d v]] (zipmap (conj ks :STR_DATUM) (conj v d))) (gen/tuple iso-date (gen/vector (gen/not-empty gen/string-alphanumeric) n)))))) (defspec counting-by-years-maps-years-to-buildings (prop/for-all [v csv-data] (let [csv (view/by-year v)] (for [k (keys csv)] (Long/parseLong k)) (for [vs (vals csv)] (or (empty? vs) (= (count (dedupe (map keys vs))) 1))))))
[ { "context": "ody\n [:strong (get video :title)]\n [:p \"Jannine Weigel\"]]])\n\n(defn deep-end []\n [:div.window\n ", "end": 1047, "score": 0.9998540878295898, "start": 1033, "tag": "NAME", "value": "Jannine Weigel" } ]
src/deep_end_reagent/core.cljs
wk-j/deep-end-reagent
0
(ns deep-end-reagent.core (:require [reagent.core :as r])) ;; ------------------------- ;; Views (def videos [{:source "https://www.youtube.com/embed/NCXfKyfpBKI?ecver=1&autoplay=1&controls=0&showinfo=0&rel=0&modestbranding=1" :title "Deep End"} {:source "https://www.youtube.com/embed/lBN9VDFDvOk?ecver=1&autoplay=1&controls=0&showinfo=0&rel=0&modestbranding=1" :title "Heart Stop"} {:source "https://www.youtube.com/embed/zeP7bqMySmE?ecver=1&autoplay=1&controls=0&showinfo=0&rel=0&modestbranding=1" :title "Strangled Love"}]) (def current-video (r/atom (get videos 0))) (defn play [video] #(swap! current-video (fn [] video))) (defn item [video] [:li {:key (get video :source) :on-click (play video) :class (if (= (get video :source) (get @current-video :source)) "list-group-item active" "list-group-item")} [:img.img-circle.media-object.pull-left {:src "images/large-round.png" :width 32 :height 32}] [:div.media-body [:strong (get video :title)] [:p "Jannine Weigel"]]]) (defn deep-end [] [:div.window [:header.toolbar.toolbar-header [:div.toolbar-actions [:button.btn.btn-default.pull-right [:span.icon.icon-facebook]]]] [:div.window-content [:div.pane {:style {:overflow-y "visible" :border-left "none"}} [:ul.list-group (map item videos)]] [:div.pane [:iframe {:style {:border 0} :title "video" :width 560 :height 315 :src (get @current-video :source)}]]] [:footer.toolbar.toolbar-footer [:h1.title]]]) (defn home-page [] [:div [deep-end]]) ;; ------------------------- ;; Initialize app (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (mount-root))
27518
(ns deep-end-reagent.core (:require [reagent.core :as r])) ;; ------------------------- ;; Views (def videos [{:source "https://www.youtube.com/embed/NCXfKyfpBKI?ecver=1&autoplay=1&controls=0&showinfo=0&rel=0&modestbranding=1" :title "Deep End"} {:source "https://www.youtube.com/embed/lBN9VDFDvOk?ecver=1&autoplay=1&controls=0&showinfo=0&rel=0&modestbranding=1" :title "Heart Stop"} {:source "https://www.youtube.com/embed/zeP7bqMySmE?ecver=1&autoplay=1&controls=0&showinfo=0&rel=0&modestbranding=1" :title "Strangled Love"}]) (def current-video (r/atom (get videos 0))) (defn play [video] #(swap! current-video (fn [] video))) (defn item [video] [:li {:key (get video :source) :on-click (play video) :class (if (= (get video :source) (get @current-video :source)) "list-group-item active" "list-group-item")} [:img.img-circle.media-object.pull-left {:src "images/large-round.png" :width 32 :height 32}] [:div.media-body [:strong (get video :title)] [:p "<NAME>"]]]) (defn deep-end [] [:div.window [:header.toolbar.toolbar-header [:div.toolbar-actions [:button.btn.btn-default.pull-right [:span.icon.icon-facebook]]]] [:div.window-content [:div.pane {:style {:overflow-y "visible" :border-left "none"}} [:ul.list-group (map item videos)]] [:div.pane [:iframe {:style {:border 0} :title "video" :width 560 :height 315 :src (get @current-video :source)}]]] [:footer.toolbar.toolbar-footer [:h1.title]]]) (defn home-page [] [:div [deep-end]]) ;; ------------------------- ;; Initialize app (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (mount-root))
true
(ns deep-end-reagent.core (:require [reagent.core :as r])) ;; ------------------------- ;; Views (def videos [{:source "https://www.youtube.com/embed/NCXfKyfpBKI?ecver=1&autoplay=1&controls=0&showinfo=0&rel=0&modestbranding=1" :title "Deep End"} {:source "https://www.youtube.com/embed/lBN9VDFDvOk?ecver=1&autoplay=1&controls=0&showinfo=0&rel=0&modestbranding=1" :title "Heart Stop"} {:source "https://www.youtube.com/embed/zeP7bqMySmE?ecver=1&autoplay=1&controls=0&showinfo=0&rel=0&modestbranding=1" :title "Strangled Love"}]) (def current-video (r/atom (get videos 0))) (defn play [video] #(swap! current-video (fn [] video))) (defn item [video] [:li {:key (get video :source) :on-click (play video) :class (if (= (get video :source) (get @current-video :source)) "list-group-item active" "list-group-item")} [:img.img-circle.media-object.pull-left {:src "images/large-round.png" :width 32 :height 32}] [:div.media-body [:strong (get video :title)] [:p "PI:NAME:<NAME>END_PI"]]]) (defn deep-end [] [:div.window [:header.toolbar.toolbar-header [:div.toolbar-actions [:button.btn.btn-default.pull-right [:span.icon.icon-facebook]]]] [:div.window-content [:div.pane {:style {:overflow-y "visible" :border-left "none"}} [:ul.list-group (map item videos)]] [:div.pane [:iframe {:style {:border 0} :title "video" :width 560 :height 315 :src (get @current-video :source)}]]] [:footer.toolbar.toolbar-footer [:h1.title]]]) (defn home-page [] [:div [deep-end]]) ;; ------------------------- ;; Initialize app (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (mount-root))
[ { "context": " ivan {:xt/id eid, :name \"Ivan\"}\n res (mapv (fn [[va", "end": 20202, "score": 0.9987601041793823, "start": 20198, "tag": "NAME", "value": "Ivan" }, { "context": "down-bitemp-144\n (let [ivan {:xt/id :ivan :name \"Ivan\"}\n start-valid-time #inst \"2019\"\n n", "end": 24265, "score": 0.9990905523300171, "start": 24261, "tag": "NAME", "value": "Ivan" }, { "context": "-read-kv-tx-log\n (let [ivan {:xt/id :ivan :name \"Ivan\"}\n\n tx1-ivan (assoc ivan :version 1)\n ", "end": 25762, "score": 0.9996644854545593, "start": 25758, "tag": "NAME", "value": "Ivan" }, { "context": ":version 2)\n tx2-petr {:xt/id :petr :name \"Petr\"}\n tx2-valid-time #inst \"2018-11-27\"\n ", "end": 26062, "score": 0.9997886419296265, "start": 26058, "tag": "NAME", "value": "Petr" }, { "context": "ize eval)]\n (let [v1-ivan {:xt/id :ivan :name \"Ivan\" :age 40}\n v4-ivan (assoc v1-ivan :name ", "end": 28287, "score": 0.9991858601570129, "start": 28283, "tag": "NAME", "value": "Ivan" }, { "context": " :age 40}\n v4-ivan (assoc v1-ivan :name \"IVAN\")\n update-attribute-fn {:xt/id :update-a", "end": 28342, "score": 0.9905503988265991, "start": 28338, "tag": "NAME", "value": "IVAN" }, { "context": " '[:find age :where [e :name \"Ivan\"] [e :age age]]))))\n\n (t/testing \"exceptio", "end": 29272, "score": 0.9928522109985352, "start": 29268, "tag": "NAME", "value": "Ivan" }, { "context": " (= [[[::xt/put\n {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ", "end": 37394, "score": 0.5361731052398682, "start": 37393, "tag": "KEY", "value": "6" }, { "context": "[[[::xt/put\n {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ", "end": 37398, "score": 0.6968494653701782, "start": 37397, "tag": "KEY", "value": "9" }, { "context": "[::xt/put\n {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted", "end": 37415, "score": 0.619930624961853, "start": 37399, "tag": "KEY", "value": "6510aa2263737167" }, { "context": " {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted? t", "end": 37418, "score": 0.6788585782051086, "start": 37416, "tag": "KEY", "value": "12" }, { "context": " {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted? true}]", "end": 37423, "score": 0.6271386742591858, "start": 37419, "tag": "KEY", "value": "2522" }, { "context": " #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted? true}]]\n ", "end": 37433, "score": 0.5364426374435425, "start": 37432, "tag": "KEY", "value": "0" }, { "context": " [[::xt/cas\n {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ", "end": 37539, "score": 0.5139102339744568, "start": 37538, "tag": "KEY", "value": "9" }, { "context": "cas\n {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/", "end": 37549, "score": 0.5996828079223633, "start": 37546, "tag": "KEY", "value": "226" }, { "context": " {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted", "end": 37556, "score": 0.5407849550247192, "start": 37554, "tag": "KEY", "value": "67" }, { "context": " {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted? t", "end": 37559, "score": 0.5937178134918213, "start": 37557, "tag": "KEY", "value": "12" }, { "context": " {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted? true", "end": 37562, "score": 0.5675431489944458, "start": 37560, "tag": "KEY", "value": "25" }, { "context": " {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted? true}\n ", "end": 37566, "score": 0.5370720028877258, "start": 37565, "tag": "KEY", "value": "5" }, { "context": "/evicted? true}\n {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ", "end": 37649, "score": 0.520821750164032, "start": 37648, "tag": "KEY", "value": "6" }, { "context": "cted? true}\n {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ", "end": 37653, "score": 0.514180600643158, "start": 37652, "tag": "KEY", "value": "9" }, { "context": "ue}\n {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/", "end": 37663, "score": 0.6646202206611633, "start": 37660, "tag": "KEY", "value": "226" }, { "context": " {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted? t", "end": 37673, "score": 0.5253101587295532, "start": 37671, "tag": "KEY", "value": "12" }, { "context": " {:xt/id #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\",\n ::xt/evicted? true}]", "end": 37678, "score": 0.5464003682136536, "start": 37674, "tag": "KEY", "value": "2522" }, { "context": " [[::xt/evict\n #xtdb/id \"6abe906510aa2263737167c12c252245bdcf6fb0\"]]]\n (->> (iterator-seq log-iterator)", "end": 37823, "score": 0.8699163794517517, "start": 37783, "tag": "KEY", "value": "6abe906510aa2263737167c12c252245bdcf6fb0" }, { "context": " (t/testing \"URI\"\n (doto (URI/create \"mailto:hello@xtdb.com\")\n (test-id) (test-value)))\n\n (t/testin", "end": 41945, "score": 0.9999246001243591, "start": 41931, "tag": "EMAIL", "value": "hello@xtdb.com" }, { "context": "sting \"URL\"\n (doto (URL. \"https://github.com/xtdb/xtdb\")\n (test-id) (test-value)))\n\n (t/t", "end": 42045, "score": 0.9990158081054688, "start": 42041, "tag": "USERNAME", "value": "xtdb" }, { "context": " (fix/submit+await-tx [[::xt/fn :put-ivan {:name \"Ivan\"}]])\n\n (t/is (= {:xt/id :ivan, :name \"Ivan\"}\n ", "end": 50659, "score": 0.9942003488540649, "start": 50655, "tag": "NAME", "value": "Ivan" }, { "context": "me \"Ivan\"}]])\n\n (t/is (= {:xt/id :ivan, :name \"Ivan\"}\n (xt/entity (xt/db *api*) :ivan)))\n", "end": 50705, "score": 0.9983210563659668, "start": 50701, "tag": "NAME", "value": "Ivan" }, { "context": "c/new-id :ivan) (c/hash-doc {:xt/id :ivan, :name \"Ivan\"})]]}\n (-> (db/fetch-docs (:documen", "end": 51027, "score": 0.9962392449378967, "start": 51023, "tag": "NAME", "value": "Ivan" }, { "context": "bmit+await-tx [[::xt/fn :put-bob-and-ivan {:name \"Bob\"} {:name \"Ivan2\"}]])\n\n (t/is (= {:xt/id :ivan,", "end": 52445, "score": 0.998286247253418, "start": 52442, "tag": "NAME", "value": "Bob" }, { "context": "[[::xt/fn :put-bob-and-ivan {:name \"Bob\"} {:name \"Ivan2\"}]])\n\n (t/is (= {:xt/id :ivan, :name \"Ivan2\"}\n", "end": 52461, "score": 0.9871678948402405, "start": 52456, "tag": "NAME", "value": "Ivan2" }, { "context": "e \"Ivan2\"}]])\n\n (t/is (= {:xt/id :ivan, :name \"Ivan2\"}\n (xt/entity (xt/db *api*) :ivan)))\n", "end": 52508, "score": 0.9974520206451416, "start": 52503, "tag": "NAME", "value": "Ivan2" }, { "context": "api*) :ivan)))\n\n (t/is (= {:xt/id :bob, :name \"Bob\"}\n (xt/entity (xt/db *api*) :bob)))\n\n", "end": 52596, "score": 0.999092698097229, "start": 52593, "tag": "NAME", "value": "Bob" }, { "context": " (c/new-id :bob) (c/hash-doc {:xt/id :bob, :name \"Bob\"})]\n [:crux", "end": 53347, "score": 0.9954366683959961, "start": 53344, "tag": "NAME", "value": "Bob" }, { "context": "(c/new-id :ivan) (c/hash-doc {:xt/id :ivan :name \"Ivan2\"})]]}\n sub-arg-doc))))\n\n (t/testin", "end": 53621, "score": 0.9985997676849365, "start": 53616, "tag": "NAME", "value": "Ivan2" }, { "context": " [sergei {:xt/id :sergei\n :name \"Sergei\"}\n arg-doc {:xt/id :args\n ", "end": 53780, "score": 0.9993441700935364, "start": 53774, "tag": "NAME", "value": "Sergei" }, { "context": " (fix/submit+await-tx [[::xt/fn :put-petr {:name \"Petr\"}]])\n\n (t/is (nil? (xt/entity (xt/db *api*) :p", "end": 54331, "score": 0.9932519197463989, "start": 54327, "tag": "NAME", "value": "Petr" }, { "context": "mit+await-tx node [[::xt/put {:xt/id :ivan :name \"Ivan\"}]])\n\n (t/is (= [{::xt/tx-id 0\n ", "end": 68096, "score": 0.9995636343955994, "start": 68092, "tag": "NAME", "value": "Ivan" }, { "context": " ::xt/tx-ops [[::xt/put {:xt/id :ivan, :name \"Ivan\"}]]}]\n (->> @!txs\n ", "end": 68211, "score": 0.9995130300521851, "start": 68207, "tag": "NAME", "value": "Ivan" } ]
test/test/xtdb/tx_test.clj
juxt/ding
0
(ns xtdb.tx-test (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.test :as t] [clojure.tools.logging.impl :as log-impl] [xtdb.api :as xt] [xtdb.bus :as bus] [xtdb.codec :as c] [xtdb.db :as db] [xtdb.fixtures :as fix :refer [*api*]] [xtdb.rdf :as rdf] [xtdb.system :as sys] [xtdb.tx :as tx] [xtdb.tx.event :as txe]) (:import [clojure.lang ExceptionInfo Keyword PersistentArrayMap] [java.net URI URL] java.time.Duration [java.util Collections Date HashMap HashSet UUID])) (t/use-fixtures :each fix/with-node fix/with-silent-test-check (fn [f] (f) (#'tx/reset-tx-fn-error))) (def picasso-id (keyword "http://dbpedia.org/resource/Pablo_Picasso")) (def picasso-eid (c/new-id picasso-id)) (def picasso (-> "xtdb/Pablo_Picasso.ntriples" (rdf/ntriples) (rdf/->default-language) (rdf/->maps-by-id) (get picasso-id))) ;; TODO: This is a large, useful, test that exercises many parts, but ;; might be better split up. (t/deftest test-can-index-tx-ops-acceptance-test (let [content-hash (c/hash-doc picasso) valid-time #inst "2018-05-21" {::xt/keys [tx-time tx-id]} (fix/submit+await-tx [[::xt/put picasso valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/testing "can see entity at transact and valid time" (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash content-hash :vt valid-time :tt tx-time :tx-id tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") tx-time tx-id)))) (t/testing "cannot see entity before valid or transact time" (t/is (nil? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") #inst "2018-05-20" tx-id))) (t/is (nil? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") tx-time -1)))) (t/testing "can see entity after valid or transact time" (t/is (some? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") #inst "2018-05-22" tx-id))) (t/is (some? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") tx-time tx-id)))) (t/testing "can see entity history" (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash content-hash :vt valid-time :tt tx-time :tx-id tx-id})] (db/entity-history index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") :desc {}))))) (t/testing "add new version of entity in the past" (let [new-picasso (assoc picasso :foo :bar) new-content-hash (c/hash-doc new-picasso) new-valid-time #inst "2018-05-20" {new-tx-time ::xt/tx-time new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put new-picasso new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash new-content-hash :vt new-valid-time :tt new-tx-time :tx-id new-tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id))) (t/is (nil? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") #inst "2018-05-20" -1)))))) (t/testing "add new version of entity in the future" (let [new-picasso (assoc picasso :baz :boz) new-content-hash (c/hash-doc new-picasso) new-valid-time #inst "2018-05-22" {new-tx-time ::xt/tx-time new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put new-picasso new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash new-content-hash :vt new-valid-time :tt new-tx-time :tx-id new-tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id))) (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash content-hash :vt valid-time :tt tx-time :tx-id tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time tx-id)))) (t/testing "can correct entity at earlier valid time" (let [new-picasso (assoc picasso :bar :foo) new-content-hash (c/hash-doc new-picasso) prev-tx-time new-tx-time prev-tx-id new-tx-id new-valid-time #inst "2018-05-22" {new-tx-time ::xt/tx-time new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put new-picasso new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash new-content-hash :vt new-valid-time :tt new-tx-time :tx-id new-tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id))) (t/is (= prev-tx-id (:tx-id (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") prev-tx-time prev-tx-id))))))) (t/testing "can delete entity" (let [new-valid-time #inst "2018-05-23" {new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/delete (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (nil? (.content-hash (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id)))) (t/testing "first version of entity is still visible in the past" (t/is (= tx-id (:tx-id (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") valid-time new-tx-id)))))))))) (t/testing "can retrieve history of entity" (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= 5 (count (db/entity-history index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") :desc {:with-corrections? true})))))))) (t/deftest test-can-cas-entity (let [{picasso-tx-time ::xt/tx-time, picasso-tx-id ::xt/tx-id} (xt/submit-tx *api* [[::xt/put picasso]])] (t/testing "compare and set does nothing with wrong content hash" (let [wrong-picasso (assoc picasso :baz :boz) cas-failure-tx (xt/submit-tx *api* [[::xt/cas wrong-picasso (assoc picasso :foo :bar)]])] (xt/await-tx *api* cas-failure-tx (Duration/ofMillis 1000)) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {})))))) (t/testing "compare and set updates with correct content hash" (let [new-picasso (assoc picasso :new? true) {new-tx-time ::xt/tx-time, new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/cas picasso new-picasso]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc new-picasso) :vt new-tx-time :tt new-tx-time :tx-id new-tx-id}) (c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {}))))))) (t/testing "compare and set can update non existing nil entity" (let [ivan {:xt/id :ivan, :value 12} {ivan-tx-time ::xt/tx-time, ivan-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/cas nil ivan]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid (c/new-id :ivan) :content-hash (c/hash-doc ivan) :vt ivan-tx-time :tt ivan-tx-time :tx-id ivan-tx-id})] (db/entity-history index-snapshot :ivan :desc {}))))))) (t/deftest test-match-ops (let [{picasso-tx-time ::xt/tx-time, picasso-tx-id ::xt/tx-id} (xt/submit-tx *api* [[::xt/put picasso]])] (t/testing "match does nothing with wrong content hash" (let [wrong-picasso (assoc picasso :baz :boz) match-failure-tx (xt/submit-tx *api* [[::xt/match picasso-id wrong-picasso]])] (xt/await-tx *api* match-failure-tx (Duration/ofMillis 1000)) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {})))))) (t/testing "match continues with correct content hash" (let [new-picasso (assoc picasso :new? true) {new-tx-time ::xt/tx-time, new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/match picasso-id picasso] [::xt/put new-picasso]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc new-picasso) :vt new-tx-time :tt new-tx-time :tx-id new-tx-id}) (c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {}))))))) (t/testing "match can check non existing entity" (let [ivan {:xt/id :ivan, :value 12} {ivan-tx-time ::xt/tx-time, ivan-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/match :ivan nil] [::xt/put ivan]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid (c/new-id :ivan) :content-hash (c/hash-doc ivan) :vt ivan-tx-time :tt ivan-tx-time :tx-id ivan-tx-id})] (db/entity-history index-snapshot :ivan :desc {}))))))) (t/deftest test-can-evict-entity (t/testing "removes all traces of entity from indices" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :value 0}]]) (fix/submit+await-tx [[::xt/put {:xt/id :foo, :value 1}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [history (db/entity-history index-snapshot :foo :desc {})] (t/testing "eviction removes tx history" (t/is (empty? history))) (t/testing "eviction removes docs" (t/is (empty? (->> (db/fetch-docs (:document-store *api*) (keep :content-hash history)) vals (remove c/evicted-doc?)))))))) (t/testing "clears entity history for valid-time ranges" (fix/submit+await-tx [[::xt/put {:xt/id :bar, :value 0} #inst "2012" #inst "2018"]]) (fix/submit+await-tx [[::xt/evict :bar]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [history (db/entity-history index-snapshot :bar :desc {})] (t/testing "eviction removes tx history" (t/is (empty? history))))))) (defn index-tx [tx tx-events docs] (let [{:keys [xtdb/tx-indexer]} @(:!system *api*) in-flight-tx (db/begin-tx tx-indexer tx nil)] (db/index-tx-events in-flight-tx tx-events docs) (db/commit in-flight-tx))) (t/deftest test-handles-legacy-evict-events (let [{put-tx-time ::xt/tx-time, put-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put picasso #inst "2018-05-21"]]) evict-tx-time #inst "2018-05-22" evict-tx-id (inc put-tx-id) index-evict! (fn [] (index-tx {::xt/tx-time evict-tx-time ::xt/tx-id evict-tx-id} [[:crux.tx/evict picasso-id #inst "2018-05-23"]] {}))] ;; we have to index these manually because the new evict API won't allow docs ;; with the legacy valid-time range (t/testing "eviction throws if legacy params and no explicit override" (t/is (thrown-with-msg? IllegalArgumentException #"^Evict no longer supports time-range parameters." (index-evict!)))) (t/testing "no docs evicted yet" (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (seq (->> (db/fetch-docs (:document-store *api*) (->> (db/entity-history index-snapshot picasso-id :desc {}) (keep :content-hash))) vals (remove c/evicted-doc?)))))) (binding [tx/*evict-all-on-legacy-time-ranges?* true] (let [{:keys [docs]} (index-evict!)] (db/submit-docs (:document-store *api*) docs) (t/testing "eviction removes docs" (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (->> (db/fetch-docs (:document-store *api*) (->> (db/entity-history index-snapshot picasso-id :desc {}) (keep :content-hash))) vals (remove c/evicted-doc?)))))))))) (t/deftest test-multiple-txs-in-same-ms-441 (let [ivan {:crux.db/id :ivan} ivan1 (assoc ivan :value 1) ivan2 (assoc ivan :value 2) t #inst "2019-11-29" docs {(c/hash-doc ivan1) ivan1 (c/hash-doc ivan2) ivan2}] (db/submit-docs (:document-store *api*) docs) (index-tx {::xt/tx-time t, ::xt/tx-id 1} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan1))]] docs) (index-tx {::xt/tx-time t, ::xt/tx-id 2} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan2))]] docs) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 2 (c/hash-doc ivan2)) (c/->EntityTx (c/new-id :ivan) t t 1 (c/hash-doc ivan1))] (db/entity-history index-snapshot :ivan :desc {:with-corrections? true}))) (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 2 (c/hash-doc ivan2))] (db/entity-history index-snapshot :ivan :desc {:start-valid-time t :start-tx {::xt/tx-id 2}}))) (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 1 (c/hash-doc ivan1))] (db/entity-history index-snapshot :ivan :desc {:start-valid-time t :start-tx {::xt/tx-id 1}}))) (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 2 (c/hash-doc ivan2))] (db/entity-history index-snapshot :ivan :asc {:start-valid-time t})))))) (t/deftest test-entity-history-seq-corner-cases (let [ivan {:crux.db/id :ivan} ivan1 (assoc ivan :value 1) ivan2 (assoc ivan :value 2) t1 #inst "2020-05-01" t2 #inst "2020-05-02" docs {(c/hash-doc ivan1) ivan1 (c/hash-doc ivan2) ivan2}] (db/submit-docs (:document-store *api*) docs) (index-tx {::xt/tx-time t1, ::xt/tx-id 1} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan1)) t1]] docs) (index-tx {::xt/tx-time t2, ::xt/tx-id 2} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan2)) t1] [:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan2))]] docs) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [etx-v1-t1 (c/->EntityTx (c/new-id :ivan) t1 t1 1 (c/hash-doc ivan1)) etx-v1-t2 (c/->EntityTx (c/new-id :ivan) t1 t2 2 (c/hash-doc ivan2)) etx-v2-t2 (c/->EntityTx (c/new-id :ivan) t2 t2 2 (c/hash-doc ivan2))] (letfn [(history-asc [opts] (vec (db/entity-history index-snapshot :ivan :asc opts))) (history-desc [opts] (vec (db/entity-history index-snapshot :ivan :desc opts)))] (t/testing "start is inclusive" (t/is (= [etx-v2-t2 etx-v1-t2] (history-desc {:start-tx {::xt/tx-id 2} :start-valid-time t2}))) (t/is (= [etx-v1-t2] (history-desc {:start-valid-time t1}))) (t/is (= [etx-v1-t2 etx-v2-t2] (history-asc {:start-tx {::xt/tx-id 2}}))) (t/is (= [etx-v1-t1 etx-v1-t2 etx-v2-t2] (history-asc {:start-tx {::xt/tx-id 1} :start-valid-time t1 :with-corrections? true})))) (t/testing "end is exclusive" (t/is (= [etx-v2-t2] (history-desc {:start-valid-time t2, :start-tx {::xt/tx-id 2} :end-valid-time t1, :end-tx {::xt/tx-id 1}}))) (t/is (= [] (history-desc {:end-valid-time t2}))) (t/is (= [etx-v1-t1] (history-asc {:end-tx {::xt/tx-id 2}}))) (t/is (= [] (history-asc {:start-valid-time t1, :end-tx {::xt/tx-id 1}}))))))))) (t/deftest test-put-delete-range-semantics (t/are [txs history] (let [eid (keyword (gensym "ivan")) ivan {:xt/id eid, :name "Ivan"} res (mapv (fn [[value & vts]] (xt/submit-tx *api* [(into (if value [::xt/put (assoc ivan :value value)] [::xt/delete eid]) vts)])) txs) last-tx (last res)] (xt/await-tx *api* last-tx nil) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (for [[vt tx-idx value] history] [vt (get-in res [tx-idx ::xt/tx-id]) (c/hash-doc (when value (assoc ivan :value value)))]) (->> (db/entity-history index-snapshot eid :asc {}) (map (juxt :vt :tx-id :content-hash))))))) ;; pairs ;; [[value vt ?end-vt] ...] ;; [[vt tx-idx value] ...] [[26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-26" 0 26] [#inst "2019-11-29" 0 nil]] ;; re-instates the previous value at the end of the range [[25 #inst "2019-11-25"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 26] [#inst "2019-11-29" 0 25]] ;; delete a range [[25 #inst "2019-11-25"] [nil #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 nil] [#inst "2019-11-29" 0 25]] ;; override a range [[25 #inst "2019-11-25" #inst "2019-11-27"] [nil #inst "2019-11-25" #inst "2019-11-27"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 1 nil] [#inst "2019-11-26" 2 26] [#inst "2019-11-27" 2 26] [#inst "2019-11-29" 0 nil]] ;; merge a range [[25 #inst "2019-11-25" #inst "2019-11-27"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 26] [#inst "2019-11-27" 1 26] [#inst "2019-11-29" 0 nil]] ;; shouldn't override the value at end-vt if there's one there [[25 #inst "2019-11-25"] [29 #inst "2019-11-29"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 2 26] [#inst "2019-11-29" 1 29]] ;; should re-instate 28 at the end of the range [[25 #inst "2019-11-25"] [28 #inst "2019-11-28"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 2 26] [#inst "2019-11-28" 2 26] [#inst "2019-11-29" 1 28]] ;; 26.1 should overwrite the full range [[28 #inst "2019-11-28"] [26 #inst "2019-11-26" #inst "2019-11-29"] [26.1 #inst "2019-11-26"]] [[#inst "2019-11-26" 2 26.1] [#inst "2019-11-28" 2 26.1] [#inst "2019-11-29" 0 28]] ;; 27 should override the latter half of the range [[25 #inst "2019-11-25"] [26 #inst "2019-11-26" #inst "2019-11-29"] [27 #inst "2019-11-27"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 26] [#inst "2019-11-27" 2 27] [#inst "2019-11-29" 0 25]] ;; 27 should still override the latter half of the range [[25 #inst "2019-11-25"] [28 #inst "2019-11-28"] [26 #inst "2019-11-26" #inst "2019-11-29"] [27 #inst "2019-11-27"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 2 26] [#inst "2019-11-27" 3 27] [#inst "2019-11-28" 3 27] [#inst "2019-11-29" 1 28]])) ;; TODO: This test just shows that this is an issue, if we fix the ;; underlying issue this test should start failing. We can then change ;; the second assertion if we want to keep it around to ensure it ;; keeps working. (t/deftest test-corrections-in-the-past-slowes-down-bitemp-144 (let [ivan {:xt/id :ivan :name "Ivan"} start-valid-time #inst "2019" number-of-versions 1000 tx (fix/submit+await-tx (for [n (range number-of-versions)] [::xt/put (assoc ivan :version n) (Date. (+ (.getTime start-valid-time) (inc (long n))))]))] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [baseline-time (let [start-time (System/nanoTime) valid-time (Date. (+ (.getTime start-valid-time) number-of-versions))] (t/testing "last version of entity is visible at now" (t/is (= valid-time (:vt (db/entity-as-of index-snapshot :ivan valid-time (::xt/tx-id tx)))))) (- (System/nanoTime) start-time))] (let [start-time (System/nanoTime) valid-time (Date. (+ (.getTime start-valid-time) number-of-versions))] (t/testing "no version is visible before transactions" (t/is (nil? (db/entity-as-of index-snapshot :ivan valid-time -1))) (let [corrections-time (- (System/nanoTime) start-time)] ;; TODO: This can be a bit flaky. This assertion was ;; mainly there to prove the opposite, but it has been ;; fixed. Can be added back to sanity check when ;; changing indexes. #_(t/is (>= baseline-time corrections-time))))))))) (t/deftest test-can-read-kv-tx-log (let [ivan {:xt/id :ivan :name "Ivan"} tx1-ivan (assoc ivan :version 1) tx1-valid-time #inst "2018-11-26" {tx1-id ::xt/tx-id tx1-tx-time ::xt/tx-time} (fix/submit+await-tx [[::xt/put tx1-ivan tx1-valid-time]]) tx2-ivan (assoc ivan :version 2) tx2-petr {:xt/id :petr :name "Petr"} tx2-valid-time #inst "2018-11-27" {tx2-id ::xt/tx-id tx2-tx-time ::xt/tx-time} (fix/submit+await-tx [[::xt/put tx2-ivan tx2-valid-time] [::xt/put tx2-petr tx2-valid-time]])] (with-open [log-iterator (db/open-tx-log (:tx-log *api*) nil)] (let [log (iterator-seq log-iterator)] (t/is (not (realized? log))) (t/is (= [{::xt/tx-id tx1-id ::xt/tx-time tx1-tx-time :xtdb.tx.event/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc tx1-ivan) tx1-valid-time]] ::xt/submit-tx-opts {}} {::xt/tx-id tx2-id ::xt/tx-time tx2-tx-time :xtdb.tx.event/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc tx2-ivan) tx2-valid-time] [:crux.tx/put (c/new-id :petr) (c/hash-doc tx2-petr) tx2-valid-time]] ::xt/submit-tx-opts {}}] log)))))) (t/deftest migrates-unhashed-tx-log-eids (let [doc {:crux.db/id :foo} doc-id (c/hash-doc doc)] (db/submit-docs (:document-store *api*) {doc-id doc}) (doto @(db/submit-tx (:tx-log *api*) [[:crux.tx/match :foo (c/new-id c/nil-id-buffer)] [:crux.tx/put :foo doc-id]]) (->> (xt/await-tx *api*))) (t/is (= {:xt/id :foo} (xt/entity (xt/db *api*) :foo))) (with-open [log-iterator (xt/open-tx-log *api* nil nil)] (let [evts (::xt/tx-events (first (iterator-seq log-iterator)))] ;; have to check not= too because Id's `equals` conforms its input to Id (t/is (not= [::xt/match :foo (c/new-id c/nil-id-buffer)] (first evts))) (t/is (not= [::xt/put :foo doc-id] (second evts))) (t/is (= [[::xt/match (c/new-id :foo) (c/new-id c/nil-id-buffer)] [::xt/put (c/new-id :foo) doc-id]] evts)))) (fix/submit+await-tx [[::xt/delete :foo]]) (t/is (nil? (xt/entity (xt/db *api*) :foo))))) (t/deftest test-can-apply-transaction-fn (with-redefs [tx/tx-fn-eval-cache (memoize eval)] (let [v1-ivan {:xt/id :ivan :name "Ivan" :age 40} v4-ivan (assoc v1-ivan :name "IVAN") update-attribute-fn {:xt/id :update-attribute-fn :xt/fn '(fn [ctx eid k f] [[::xt/put (update (xtdb.api/entity (xtdb.api/db ctx) eid) k (eval f))]])}] (fix/submit+await-tx [[::xt/put v1-ivan] [::xt/put update-attribute-fn]]) (t/is (= v1-ivan (xt/entity (xt/db *api*) :ivan))) (t/is (= update-attribute-fn (xt/entity (xt/db *api*) :update-attribute-fn))) (some-> (#'tx/reset-tx-fn-error) throw) (let [v2-ivan (assoc v1-ivan :age 41)] (fix/submit+await-tx [[::xt/fn :update-attribute-fn :ivan :age `inc]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v2-ivan (xt/entity (xt/db *api*) :ivan))) (t/testing "resulting documents are indexed" (t/is (= #{[41]} (xt/q (xt/db *api*) '[:find age :where [e :name "Ivan"] [e :age age]])))) (t/testing "exceptions" (t/testing "non existing tx fn" (let [tx (fix/submit+await-tx '[[::xt/fn :non-existing-fn]])] (t/is (= v2-ivan (xt/entity (xt/db *api*) :ivan))) (t/is (false? (xt/tx-committed? *api* tx))))) (t/testing "invalid arguments" (fix/submit+await-tx '[[::xt/fn :update-attribute-fn :ivan :age foo]]) (t/is (thrown? clojure.lang.Compiler$CompilerException (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "invalid results" (fix/submit+await-tx [[::xt/put {:xt/id :invalid-fn :xt/fn '(fn [ctx] [[::xt/foo]])}]]) (fix/submit+await-tx '[[::xt/fn :invalid-fn]]) (t/is (thrown-with-msg? IllegalArgumentException #"Invalid tx op" (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "no ::xt/fn" (fix/submit+await-tx [[::xt/put {:xt/id :no-fn}]]) (let [tx (fix/submit+await-tx '[[::xt/fn :no-fn]])] (t/is (false? (xt/tx-committed? *api* tx))))) (t/testing "not a fn" (fix/submit+await-tx [[::xt/put {:xt/id :not-a-fn :xt/fn 0}]]) (fix/submit+await-tx '[[::xt/fn :not-a-fn]]) (t/is (thrown? ClassCastException (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "compilation errors" (fix/submit+await-tx [[::xt/put {:xt/id :compilation-error-fn :xt/fn '(fn [ctx] unknown-symbol)}]]) (fix/submit+await-tx '[[::xt/fn :compilation-error-fn]]) (t/is (thrown-with-msg? Exception #"Syntax error compiling" (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "exception thrown" (fix/submit+await-tx [[::xt/put {:xt/id :exception-fn :xt/fn '(fn [ctx] (throw (RuntimeException. "foo")))}]]) (fix/submit+await-tx '[[::xt/fn :exception-fn]]) (t/is (thrown-with-msg? RuntimeException #"foo" (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "still working after errors" (let [v3-ivan (assoc v1-ivan :age 40)] (fix/submit+await-tx [[::xt/fn :update-attribute-fn :ivan :age `dec]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v3-ivan (xt/entity (xt/db *api*) :ivan)))))) (t/testing "sees in-transaction version of entities (including itself)" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 1}]]) (let [tx (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 2}] [::xt/put {:xt/id :doubling-fn :xt/fn '(fn [ctx] [[::xt/put (-> (xtdb.api/entity (xtdb.api/db ctx) :foo) (update :foo * 2))]])}] [::xt/fn :doubling-fn]])] (t/is (xt/tx-committed? *api* tx)) (t/is (= {:xt/id :foo, :foo 4} (xt/entity (xt/db *api*) :foo))))) (t/testing "function ops can return other function ops" (let [returns-fn {:xt/id :returns-fn :xt/fn '(fn [ctx] [[::xt/fn :update-attribute-fn :ivan :name `string/upper-case]])}] (fix/submit+await-tx [[::xt/put returns-fn]]) (fix/submit+await-tx [[::xt/fn :returns-fn]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v4-ivan (xt/entity (xt/db *api*) :ivan))))) (t/testing "repeated 'merge' operation behaves correctly" (let [v5-ivan (merge v4-ivan {:height 180 :hair-style "short" :mass 60}) merge-fn {:xt/id :merge-fn :xt/fn `(fn [ctx# eid# m#] [[::xt/put (merge (xt/entity (xt/db ctx#) eid#) m#)]])}] (fix/submit+await-tx [[::xt/put merge-fn]]) (fix/submit+await-tx [[::xt/fn :merge-fn :ivan {:mass 60, :hair-style "short"}]]) (fix/submit+await-tx [[::xt/fn :merge-fn :ivan {:height 180}]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v5-ivan (xt/entity (xt/db *api*) :ivan))))) (t/testing "function ops can return other function ops that also the forked ctx" (let [returns-fn {:xt/id :returns-fn :xt/fn '(fn [ctx] [[::xt/put {:xt/id :ivan :name "modified ivan"}] [::xt/fn :update-attribute-fn :ivan :name `string/upper-case]])}] (fix/submit+await-tx [[::xt/put returns-fn]]) (fix/submit+await-tx [[::xt/fn :returns-fn]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= {:xt/id :ivan :name "MODIFIED IVAN"} (xt/entity (xt/db *api*) :ivan))))) (t/testing "can access current transaction on tx-fn context" (fix/submit+await-tx [[::xt/put {:xt/id :tx-metadata-fn :xt/fn `(fn [ctx#] [[::xt/put {:xt/id :tx-metadata ::xt/current-tx (xt/indexing-tx ctx#)}]])}]]) (let [submitted-tx (fix/submit+await-tx '[[::xt/fn :tx-metadata-fn]])] (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= {:xt/id :tx-metadata ::xt/current-tx submitted-tx} (xt/entity (xt/db *api*) :tx-metadata))))))))) (t/deftest tx-fn-sees-in-tx-query-results (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 1}]]) (let [tx (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 2}] [::xt/put {:xt/id :put :xt/fn '(fn [ctx doc] [[::xt/put doc]])}] [::xt/fn :put {:xt/id :bar, :ref :foo}] [::xt/put {:xt/id :doubling-fn :xt/fn '(fn [ctx] (let [db (xtdb.api/db ctx)] [[::xt/put {:xt/id :prn-out :e (xtdb.api/entity db :bar) :q (first (xtdb.api/q db {:find '[e v] :where '[[e :xt/id :bar] [e :ref v]]}))}] [::xt/put (-> (xtdb.api/entity db :foo) (update :foo * 2))]]))}] [::xt/fn :doubling-fn]])] (t/is (xt/tx-committed? *api* tx)) (t/is (= {:xt/id :foo, :foo 4} (xt/entity (xt/db *api*) :foo))) (t/is (= {:xt/id :prn-out :e {:xt/id :bar :ref :foo} :q [:bar :foo]} (xt/entity (xt/db *api*) :prn-out))))) (t/deftest tx-log-evict-454 [] (fix/submit+await-tx [[::xt/put {:xt/id :to-evict}]]) (fix/submit+await-tx [[::xt/cas {:xt/id :to-evict} {:xt/id :to-evict :test "test"}]]) (fix/submit+await-tx [[::xt/evict :to-evict]]) (with-open [log-iterator (xt/open-tx-log *api* nil true)] (t/is (= [[[::xt/put {:xt/id #xtdb/id "6abe906510aa2263737167c12c252245bdcf6fb0", ::xt/evicted? true}]] [[::xt/cas {:xt/id #xtdb/id "6abe906510aa2263737167c12c252245bdcf6fb0", ::xt/evicted? true} {:xt/id #xtdb/id "6abe906510aa2263737167c12c252245bdcf6fb0", ::xt/evicted? true}]] [[::xt/evict #xtdb/id "6abe906510aa2263737167c12c252245bdcf6fb0"]]] (->> (iterator-seq log-iterator) (map ::xt/tx-ops)))))) (t/deftest transaction-fn-return-values-457 (with-redefs [tx/tx-fn-eval-cache (memoize eval)] (let [nil-fn {:xt/id :nil-fn :xt/fn '(fn [ctx] nil)} false-fn {:xt/id :false-fn :xt/fn '(fn [ctx] false)}] (fix/submit+await-tx [[::xt/put nil-fn] [::xt/put false-fn]]) (fix/submit+await-tx [[::xt/fn :nil-fn] [::xt/put {:xt/id :foo :foo? true}]]) (t/is (= {:xt/id :foo, :foo? true} (xt/entity (xt/db *api*) :foo))) (fix/submit+await-tx [[::xt/fn :false-fn] [::xt/put {:xt/id :bar :bar? true}]]) (t/is (nil? (xt/entity (xt/db *api*) :bar)))))) (t/deftest map-ordering-362 (t/testing "cas is independent of map ordering" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo :bar}]]) (fix/submit+await-tx [[::xt/cas {:foo :bar, :xt/id :foo} {:xt/id :foo, :foo :baz}]]) (t/is (= {:xt/id :foo, :foo :baz} (xt/entity (xt/db *api*) :foo)))) (t/testing "entities with map keys can be retrieved regardless of ordering" (let [doc {:xt/id {:foo 1, :bar 2}}] (fix/submit+await-tx [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db *api*) {:foo 1, :bar 2}))) (t/is (= doc (xt/entity (xt/db *api*) {:bar 2, :foo 1}))))) (t/testing "entities with map values can be joined regardless of ordering" (let [doc {:xt/id {:foo 2, :bar 4}}] (fix/submit+await-tx [[::xt/put doc] [::xt/put {:xt/id :baz, :joins {:bar 4, :foo 2}}] [::xt/put {:xt/id :quux, :joins {:foo 2, :bar 4}}]]) (t/is (= #{[{:foo 2, :bar 4} :baz] [{:foo 2, :bar 4} :quux]} (xt/q (xt/db *api*) '{:find [parent child] :where [[parent :xt/id _] [child :joins parent]]})))))) (t/deftest incomparable-colls-1001 (t/testing "can store and retrieve incomparable colls (#1001)" (let [foo {:xt/id :foo :foo {:bar #{7 "hello"}}}] (fix/submit+await-tx [[::xt/put foo]]) (t/is (= #{[foo]} (xt/q (xt/db *api*) '{:find [(pull ?e [*])] :where [[?e :foo {:bar #{"hello" 7}}]]})))) (let [foo {:xt/id :foo :foo {{:foo 1} :foo1 {:foo 2} :foo2}}] (fix/submit+await-tx [[::xt/put foo]]) (t/is (= #{[foo]} (xt/q (xt/db *api*) '{:find [(pull ?e [*])] :where [[?e :foo {{:foo 2} :foo2, {:foo 1} :foo1}]]})))))) (t/deftest test-java-ids-and-values-1398 (letfn [(test-id [id] (t/testing "As ID" (with-open [node (xt/start-node {})] (let [doc {:xt/id id}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) id))) (t/is #{[id]} (xt/q (xt/db node) '{:find [?id] :where [[?id :xt/id]]})))))) (test-value [value] (t/testing "As Value" (with-open [node (xt/start-node {})] (let [doc {:xt/id :foo :bar value}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) :foo))) (t/is #{[value]} (xt/q (xt/db node) '{:find [?val] :where [[?id :bar ?val]]}))))))] (t/testing "Keyword" (doto (Keyword/intern "foo") (test-id) (test-value))) (t/testing "String" (doto "foo" (test-id) (test-value))) (t/testing "Long" (doto 100 (test-id) (test-value))) (t/testing "UUID" (doto (UUID/randomUUID) (test-id) (test-value))) (t/testing "URI" (doto (URI/create "mailto:hello@xtdb.com") (test-id) (test-value))) (t/testing "URL" (doto (URL. "https://github.com/xtdb/xtdb") (test-id) (test-value))) (t/testing "IPersistentMap" (doto (-> (PersistentArrayMap/EMPTY) (.assoc "foo" "bar")) (test-id) (test-value))) (t/testing "Set" (doto (HashSet.) (.add "foo") (.add "bar") (test-value))) (t/testing "Singleton Map" (doto (Collections/singletonMap "foo" "bar") (test-id) (test-value))) (t/testing "HashMap with single entry" (doto (HashMap.) (.put "foo" "bar") (test-id) (test-value))) (t/testing "HashMap with multiple entries" (doto (HashMap.) (.put "foo" "bar") (.put "baz" "waka") (test-id) (test-value))) (t/testing "HashMap with entries added in different order" (let [val1 (doto (HashMap.) (.put "foo" "bar") (.put "baz" "waka")) val2 (doto (HashMap.) (.put "baz" "waka") (.put "foo" "bar"))] (t/is (= val1 val2)) (t/testing "As ID" (with-open [node (xt/start-node {})] (let [doc {:xt/id val1}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) val2))) (let [result (xt/q (xt/db node) '{:find [?id] :where [[?id :xt/id]]})] (t/is #{[val1]} result) (t/is #{[val2]} result))))) (t/testing "As Value" (with-open [node (xt/start-node {})] (let [doc {:xt/id :foo :bar val1}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) :foo))) (let [result (xt/q (xt/db node) '{:find [?val] :where [[?id :bar ?val]]})] (t/is #{[val1]} result) (t/is #{[val2]} result))))))))) (t/deftest overlapping-valid-time-ranges-434 (let [_ (fix/submit+await-tx [[::xt/put {:xt/id :foo, :v 10} #inst "2019-01-01"] [::xt/put {:xt/id :foo, :v 10} #inst "2020-01-10"] [::xt/put {:xt/id :bar, :v 5} #inst "2020-01-05"] [::xt/put {:xt/id :bar, :v 10} #inst "2020-01-10"] [::xt/put {:xt/id :baz, :v 10} #inst "2020-01-10"]]) last-tx (fix/submit+await-tx [[::xt/put {:xt/id :foo, :v 10} #inst "2019-01-01"] [::xt/put {:xt/id :bar, :v 7} #inst "2020-01-07"] ;; mixing foo and bar shouldn't matter [::xt/put {:xt/id :foo, :v 8} #inst "2020-01-08" #inst "2020-01-12"] ; reverts to 10 afterwards [::xt/put {:xt/id :foo, :v 9} #inst "2020-01-09" #inst "2020-01-11"] ; reverts to 8 afterwards, then 10 [::xt/put {:xt/id :bar, :v 8} #inst "2020-01-08" #inst "2020-01-09"] ; reverts to 7 afterwards [::xt/put {:xt/id :bar, :v 11} #inst "2020-01-11" #inst "2020-01-12"] ; reverts to 10 afterwards ]) db (xt/db *api*)] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [eid->history (fn [eid] (let [history (db/entity-history index-snapshot (c/new-id eid) :asc {:start-valid-time #inst "2020-01-01"}) docs (db/fetch-docs (:document-store *api*) (map :content-hash history))] (->> history (mapv (fn [{:keys [content-hash vt]}] [vt (:v (get docs content-hash))])))))] ;; transaction functions, asserts both still apply at the start of the transaction (t/is (= [[#inst "2020-01-08" 8] [#inst "2020-01-09" 9] [#inst "2020-01-10" 9] [#inst "2020-01-11" 8] [#inst "2020-01-12" 10]] (eid->history :foo))) (t/is (= [[#inst "2020-01-05" 5] [#inst "2020-01-07" 7] [#inst "2020-01-08" 8] [#inst "2020-01-09" 7] [#inst "2020-01-10" 10] [#inst "2020-01-11" 11] [#inst "2020-01-12" 10]] (eid->history :bar))))))) (t/deftest cas-docs-not-evicting-371 (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo :bar}] [::xt/put {:xt/id :frob :foo :bar}]]) (fix/submit+await-tx [[::xt/cas {:xt/id :foo, :foo :baz} {:xt/id :foo, :foo :quux}] [::xt/put {:xt/id :frob :foo :baz}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (let [docs (db/fetch-docs (:document-store *api*) #{(c/hash-doc {:xt/id :foo, :foo :bar}) (c/hash-doc {:xt/id :foo, :foo :baz}) (c/hash-doc {:xt/id :foo, :foo :quux})})] (t/is (= 3 (count docs))) (t/is (every? (comp c/evicted-doc? val) docs))) (t/testing "even though the CaS was unrelated, the whole transaction fails - we should still evict those docs" (fix/submit+await-tx [[::xt/evict :frob]]) (let [docs (db/fetch-docs (:document-store *api*) #{(c/hash-doc {:xt/id :frob, :foo :bar}) (c/hash-doc {:xt/id :frob, :foo :baz})})] (t/is (= 2 (count docs))) (t/is (every? (comp c/evicted-doc? val) docs))))) (t/deftest raises-tx-events-422 (let [!events (atom []) !latch (promise)] (bus/listen (:bus *api*) {::xt/event-types #{::tx/indexing-tx ::tx/indexed-tx}} (fn [evt] (swap! !events conj evt) (when (= ::tx/indexed-tx (::xt/event-type evt)) (deliver !latch @!events)))) (let [doc-1 {:xt/id :foo, :value 1} doc-2 {:xt/id :bar, :value 2} doc-ids #{(c/hash-doc doc-1) (c/hash-doc doc-2)} submitted-tx (fix/submit+await-tx [[::xt/put doc-1] [::xt/put doc-2]])] (when (= ::timeout (deref !latch 500 ::timeout)) (t/is false)) (t/is (= [{::xt/event-type ::tx/indexing-tx, :submitted-tx submitted-tx} {::xt/event-type ::tx/indexed-tx, :submitted-tx submitted-tx, :committed? true :doc-ids doc-ids :av-count 4 ::txe/tx-events [[:crux.tx/put #xtdb/id "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33" #xtdb/id "974e28e6484fb6c66e5ca6444ec616207800d815"] [:crux.tx/put #xtdb/id "62cdb7020ff920e5aa642c3d4066950dd1f01f4d" #xtdb/id "f2cb628efd5123743c30137b08282b9dee82104a"]]}] (-> (vec @!events) (update 1 dissoc :bytes-indexed))))))) (t/deftest await-fails-quickly-738 (with-redefs [tx/index-tx-event (fn [_ _ _] (Thread/sleep 100) (throw (ex-info "test error for await-fails-quickly-738" {})))] (let [last-tx (xt/submit-tx *api* [[::xt/put {:xt/id :foo}]])] (t/testing "Testing fail while we are awaiting an event" (t/is (thrown-with-msg? Exception #"Transaction ingester aborted" (xt/await-tx *api* last-tx (Duration/ofMillis 1000))))) (t/testing "Testing fail before we await an event" (t/is (thrown-with-msg? Exception #"Transaction ingester aborted" (xt/await-tx *api* last-tx (Duration/ofMillis 1000)))))))) (t/deftest test-evict-documents-with-common-attributes (fix/submit+await-tx [[::xt/put {:xt/id :foo, :count 1}] [::xt/put {:xt/id :bar, :count 1}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (t/is (= #{[:bar]} (xt/q (xt/db *api*) '{:find [?e] :where [[?e :count 1]]})))) (t/deftest replaces-tx-fn-arg-docs (fix/submit+await-tx [[::xt/put {:xt/id :put-ivan :xt/fn '(fn [ctx doc] [[::xt/put (assoc doc :xt/id :ivan)]])}]]) (t/testing "replaces args doc with resulting ops" (fix/submit+await-tx [[::xt/fn :put-ivan {:name "Ivan"}]]) (t/is (= {:xt/id :ivan, :name "Ivan"} (xt/entity (xt/db *api*) :ivan))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) last ::txe/tx-events first last))] (t/is (= {:crux.db.fn/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc {:xt/id :ivan, :name "Ivan"})]]} (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt) (dissoc :xt/id)))))) (t/testing "replaces fn with no args" (fix/submit+await-tx [[::xt/put {:xt/id :no-args :xt/fn '(fn [ctx] [[::xt/put {:xt/id :no-fn-args-doc}]])}]]) (fix/submit+await-tx [[::xt/fn :no-args]]) (t/is (= {:xt/id :no-fn-args-doc} (xt/entity (xt/db *api*) :no-fn-args-doc))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) last ::txe/tx-events first last))] (t/is (= {:crux.db.fn/tx-events [[:crux.tx/put (c/new-id :no-fn-args-doc) (c/hash-doc {:xt/id :no-fn-args-doc})]]} (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt) (dissoc :xt/id)))))) (t/testing "nested tx-fn" (fix/submit+await-tx [[::xt/put {:xt/id :put-bob-and-ivan :xt/fn '(fn [ctx bob ivan] [[::xt/put (assoc bob :xt/id :bob)] [::xt/fn :put-ivan ivan]])}]]) (fix/submit+await-tx [[::xt/fn :put-bob-and-ivan {:name "Bob"} {:name "Ivan2"}]]) (t/is (= {:xt/id :ivan, :name "Ivan2"} (xt/entity (xt/db *api*) :ivan))) (t/is (= {:xt/id :bob, :name "Bob"} (xt/entity (xt/db *api*) :bob))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) 1)] (-> (iterator-seq tx-log) last ::txe/tx-events first last)) arg-doc (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt)) sub-arg-doc-id (-> arg-doc :crux.db.fn/tx-events second last) sub-arg-doc (-> (db/fetch-docs (:document-store *api*) #{sub-arg-doc-id}) (get sub-arg-doc-id) (c/crux->xt))] (t/is (= {:xt/id (:xt/id arg-doc) :crux.db.fn/tx-events [[:crux.tx/put (c/new-id :bob) (c/hash-doc {:xt/id :bob, :name "Bob"})] [:crux.tx/fn (c/new-id :put-ivan) sub-arg-doc-id]]} arg-doc)) (t/is (= {:xt/id (:xt/id sub-arg-doc) :crux.db.fn/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc {:xt/id :ivan :name "Ivan2"})]]} sub-arg-doc)))) (t/testing "copes with args doc having been replaced" (let [sergei {:xt/id :sergei :name "Sergei"} arg-doc {:xt/id :args :crux.db.fn/tx-events [[:crux.tx/put :sergei (c/hash-doc sergei)]]}] (db/submit-docs (:document-store *api*) {(c/hash-doc arg-doc) arg-doc (c/hash-doc sergei) sergei}) (let [tx @(db/submit-tx (:tx-log *api*) [[:crux.tx/fn :put-sergei (c/hash-doc arg-doc)]])] (xt/await-tx *api* tx) (t/is (= sergei (xt/entity (xt/db *api*) :sergei)))))) (t/testing "failed tx-fn" (fix/submit+await-tx [[::xt/fn :put-petr {:name "Petr"}]]) (t/is (nil? (xt/entity (xt/db *api*) :petr))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) last ::txe/tx-events first last))] (t/is (true? (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) :crux.db.fn/failed?)))))) (t/deftest handles-legacy-tx-fns-with-no-args-doc ;; we used to not submit args docs if the tx-fn was 0-arg, and hence had nothing to replace ;; we don't want the fix to assume that all tx-fns on the tx-log have an arg-doc (let [tx-fn (-> {:xt/id :tx-fn, :xt/fn '(fn [ctx] [[::xt/put {:xt/id :ivan}]])} (c/xt->crux)) docs {(c/hash-doc tx-fn) tx-fn}] (db/submit-docs (:document-store *api*) docs) (index-tx {::xt/tx-time (Date.), ::xt/tx-id 0} [[:crux.tx/put (c/new-id :tx-fn) tx-fn]] docs) (index-tx {::xt/tx-time (Date.), ::xt/tx-id 1} [[:crux.tx/fn :tx-fn]] docs) (t/is (= {:xt/id :ivan} (xt/entity (xt/db *api*) :ivan))))) (t/deftest test-tx-fn-doc-race-1049 (let [put-fn {:xt/id :put-fn :xt/fn '(fn [ctx doc] [[::xt/put doc]])} foo-doc {:crux.db/id :foo} !arg-doc-resps (atom [{:crux.db.fn/args [foo-doc]} {:crux.db.fn/tx-events [[:crux.tx/put (c/new-id :foo) (c/hash-doc foo-doc)]]}]) ->mocked-doc-store (fn [_opts] (reify db/DocumentStore (submit-docs [_ docs]) (fetch-docs [_ ids] (->> ids (into {} (map (juxt identity (some-fn {(c/hash-doc put-fn) (c/xt->crux put-fn) (c/hash-doc foo-doc) foo-doc} (fn [id] (let [[[doc] _] (swap-vals! !arg-doc-resps rest)] (merge doc {:crux.db/id id})))))))))))] (with-open [node (xt/start-node {:xtdb/document-store ->mocked-doc-store})] (xt/submit-tx node [[::xt/put put-fn]]) (xt/submit-tx node [[::xt/fn :put-fn foo-doc]]) (xt/sync node) (t/is (= #{[:put-fn] [:foo]} (xt/q (xt/db node) '{:find [?e] :where [[?e :xt/id]]})))))) (t/deftest ensure-tx-fn-arg-docs-replaced-even-when-tx-aborts-960 (fix/submit+await-tx [[::xt/put {:xt/id :foo :xt/fn '(fn [ctx arg] [])}] [::xt/match :foo {:xt/id :foo}] [::xt/fn :foo :foo-arg]]) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) first :xtdb.tx.event/tx-events last last)) arg-doc (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt))] (t/is (= {:crux.db.fn/failed? true} (dissoc arg-doc :xt/id))) (t/is (uuid? (:xt/id arg-doc))))) (t/deftest test-documents-with-int-short-byte-float-eids-1043 (fix/submit+await-tx [[::xt/put {:xt/id (int 10), :name "foo"}] [::xt/put {:xt/id (short 12), :name "bar"}] [::xt/put {:xt/id (byte 16), :name "baz"}] [::xt/put {:xt/id (float 1.1), :name "quux"}]]) (let [db (xt/db *api*)] (t/is (= #{["foo"] ["bar"] ["baz"] ["quux"]} (xt/q (xt/db *api*) '{:find [?name] :where [[?e :name ?name]]}))) (t/is (= {:xt/id (long 10), :name "foo"} (xt/entity db (int 10)))) (t/is (= {:xt/id (long 10), :name "foo"} (xt/entity db (long 10)))) (t/is (= #{[10 "foo"]} (xt/q (xt/db *api*) {:find '[?e ?name] :where '[[?e :name ?name]] :args [{:?e (int 10)}]})))) (t/testing "10 as int and long are the same key" (fix/submit+await-tx [[::xt/put {:xt/id 10, :name "foo2"}]]) (t/is (= #{[10 "foo2"]} (xt/q (xt/db *api*) {:find '[?e ?name] :where '[[?e :name ?name]] :args [{:?e (int 10)}]}))))) (t/deftest test-put-evict-in-same-transaction-1337 (t/testing "put then evict" (fix/submit+await-tx [[::xt/put {:xt/id :test1/a, :test1? true}]]) (fix/submit+await-tx [[::xt/put {:xt/id :test1/b, :test1? true, :test1/evicted? true}] [::xt/evict :test1/b]]) (let [db (xt/db *api*)] (t/is (= {:xt/id :test1/a, :test1? true} (xt/entity db :test1/a))) (t/is (nil? (xt/entity db :test1/b))) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :test1/evicted? nil))) (t/is (empty? (db/entity-history index-snapshot :test1/b :asc {})))) (t/is (= #{[:test1/a]} (xt/q db '{:find [?e], :where [[?e :test1? true]]}))) (t/is (= #{} (xt/q db '{:find [?e], :where [[?e :test1/evicted? true]]}))))) (t/testing "put then evict an earlier entity" (fix/submit+await-tx [[::xt/put {:xt/id :test2/a, :test2? true, :test2/evicted? true}]]) (fix/submit+await-tx [[::xt/put {:xt/id :test2/b, :test2? true}] [::xt/evict :test2/a]]) (let [db (xt/db *api*)] (t/is (nil? (xt/entity db :test2/a))) (t/is (= {:xt/id :test2/b, :test2? true} (xt/entity db :test2/b))) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :test2/evicted? nil))) (t/is (empty? (db/entity-history index-snapshot :test2/a :asc {})))) (t/is (= #{[:test2/b]} (xt/q db '{:find [?e], :where [[?e :test2? true]]}))) (t/is (= #{} (xt/q db '{:find [?e], :where [[?e :test2/evicted? true]]}))))) (t/testing "evict then put" (fix/submit+await-tx [[::xt/put {:xt/id :test3/a, :test3? true}]]) (fix/submit+await-tx [[::xt/evict :test3/a] [::xt/put {:xt/id :test3/b, :test3? true}]]) (let [db (xt/db *api*)] (t/is (nil? (xt/entity db :test3/a))) (t/is (= {:xt/id :test3/b, :test3? true} (xt/entity db :test3/b))) (t/is (= #{[:test3/b]} (xt/q db '{:find [?e], :where [[?e :test3? true]]}))))) ;; TODO fails, see #1337 #_ (t/testing "evict then re-put" (fix/submit+await-tx [[::xt/put {:xt/id :test4, :test4? true}]]) (fix/submit+await-tx [[::xt/evict :test4] [::xt/put {:xt/id :test4, :test4? true}]]) (let [db (xt/db *api*)] (t/is (= {:xt/id :test4, :test4? true} (xt/entity db :test4))) (t/is (= #{[:test4]} (xt/q db '{:find [?e], :where [[?e :test4? true]]})))))) (t/deftest test-avs-only-shared-by-evicted-entities-1338 (t/testing "only one entity, AV removed" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :evict-me? true}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :evict-me? nil))))) ;; TODO fails, see #1338 #_ (t/testing "shared by multiple evicted entities" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :evict-me? true}] [::xt/put {:xt/id :bar, :evict-me? true}]]) (fix/submit+await-tx [[::xt/evict :foo] [::xt/evict :bar]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :evict-me? nil)))))) (t/deftest node-shutdown-interrupts-tx-ingestion (let [op-count 10 !calls (atom 0) node (xt/start-node {})] (with-redefs [tx/index-tx-event (let [f tx/index-tx-event] (fn [& args] (let [target-time (+ (System/currentTimeMillis) 200)] (while (< (System/currentTimeMillis) target-time))) (swap! !calls inc) (apply f args)))] @(try (let [tx (xt/submit-tx node (repeat op-count [::xt/put {:xt/id :foo}])) await-fut (future (t/is (thrown? InterruptedException (xt/await-tx node tx))))] (Thread/sleep 100) ; to ensure the await starts before the node closes await-fut) (finally (.close node)))) (t/is (instance? InterruptedException (db/ingester-error (:tx-ingester node)))) (t/is (< @!calls op-count)))) (t/deftest empty-tx-can-be-awaited-1519 (let [tx (xt/submit-tx *api* []) _ (xt/await-tx *api* tx (Duration/ofSeconds 1))] (t/is (= (select-keys tx [::xt/tx-id]) (xt/latest-submitted-tx *api*))) (t/is (= tx (xt/latest-completed-tx *api*))) (t/is (xt/tx-committed? *api* tx)))) (t/deftest handles-secondary-indices (letfn [(with-persistent-golden-stores [node-config db-dir] (-> node-config (assoc :xtdb/tx-log {:kv-store {:xtdb/module 'xtdb.rocksdb/->kv-store :db-dir (io/file db-dir "txs")}} :xtdb/document-store {:kv-store {:xtdb/module 'xtdb.rocksdb/->kv-store :db-dir (io/file db-dir "docs")}}))) (with-persistent-indices [node-config idx-dir] (-> node-config (assoc :xtdb/index-store {:kv-store {:xtdb/module 'xtdb.rocksdb/->kv-store :db-dir idx-dir}}))) (with-secondary-index ([node-config after-tx-id opts process-tx-f] (-> node-config (assoc ::index2 (-> (fn [{:keys [secondary-indices]}] (tx/register-index! secondary-indices after-tx-id opts process-tx-f) nil) (with-meta {::sys/deps {:secondary-indices :xtdb/secondary-indices} ::sys/before #{[:xtdb/tx-ingester]}}))))))] (t/testing "indexes into secondary indices" (let [!txs (atom [])] (with-open [node (xt/start-node (-> {} (with-secondary-index nil {} (fn [tx] (swap! !txs conj tx)))))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]]) (t/is (= [0] (map ::xt/tx-id @!txs)))))) (t/testing "secondary indices catch up to XTDB indices on node startup" (fix/with-tmp-dirs #{db-dir idx-dir} (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir)))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]])) (let [!txs (atom [])] (with-open [_node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir) (with-secondary-index nil {} (fn [tx] (swap! !txs conj tx)))))] ;; NOTE: don't need `sync` - should happen before node becomes available. (t/is (= [0] (map ::xt/tx-id @!txs))))))) (t/testing "XTDB catches up without replaying tx to secondary indices" (fix/with-tmp-dirs #{db-dir} (let [!txs (atom [])] (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-secondary-index nil {} (fn [tx] (swap! !txs conj tx)))))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]])) (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-secondary-index 0 {} (fn [tx] (swap! !txs conj tx)))))] (xt/sync node) (t/is (= 0 (::xt/tx-id (xt/latest-completed-tx node)))) (t/is (= [0] (map ::xt/tx-id @!txs))))))) (t/testing "passes through tx-ops on request" (fix/with-tmp-dirs #{db-dir idx-dir} (let [!txs (atom [])] (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir) (with-secondary-index nil {:with-tx-ops? true} (fn [tx] (swap! !txs conj tx)))))] (fix/submit+await-tx node [[::xt/put {:xt/id :ivan :name "Ivan"}]]) (t/is (= [{::xt/tx-id 0 ::xt/tx-ops [[::xt/put {:xt/id :ivan, :name "Ivan"}]]}] (->> @!txs (map #(select-keys % [::xt/tx-id ::xt/tx-ops]))))))))) (with-redefs [log-impl/enabled? (constantly false)] (t/testing "handles secondary indexes blowing up" (with-open [node (xt/start-node (-> {} (with-secondary-index nil {} (fn [_tx] (throw (ex-info "boom!" {}))))))] (t/is (thrown-with-msg? ExceptionInfo #"boom!" (try (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]]) (catch Exception e (throw (.getCause e)))))) (t/is (nil? (xt/latest-completed-tx node))))) (t/testing "handles secondary indexes blowing up on startup" (fix/with-tmp-dirs #{db-dir idx-dir} (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir)))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]])) (t/is (thrown-with-msg? ExceptionInfo #"boom!" (try (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir) (with-secondary-index nil {} (fn [_tx] (throw (ex-info "boom!" {})))))) (catch Exception e (throw (.getCause e))))))))))) (t/deftest tx-committed-throws-correctly-1579 (let [tx (fix/submit+await-tx [[::xt/put {:xt/id :foo}]])] (t/is (xt/tx-committed? *api* tx)) (t/is (xt/tx-committed? *api* {::xt/tx-id 0})) (t/is (thrown? xtdb.IllegalArgumentException (xt/tx-committed? *api* nil))) (t/is (thrown? xtdb.IllegalArgumentException (xt/tx-committed? *api* {}))) (t/is (thrown? xtdb.IllegalArgumentException (xt/tx-committed? *api* {::xt/tx-id nil}))) (t/is (thrown? ClassCastException (xt/tx-committed? *api* {::xt/tx-id :a}))) ;; "skipped" tx-ids (e.g. handling Kafka offsets), and negative or non-integer tx-ids are also incorrect but not currently detected #_ (t/is (thrown? xtdb.api.NodeOutOfSyncException (xt/tx-committed? *api* {::xt/tx-id -1.5}))))) (t/deftest can-query-documents-with-url-id-1638 ;; TODO: the (XT) hash of the URL depends on the serialized form of the URL object, ;; which in turn depends on its cached hashCode field. couple of fun things here: ;; - if nothing has yet computed the hashCode, it serializes `-1` ;; - the hashCode computation depends on the resolved IP address of the domain name (non-deterministic) ;; we (arguably incorrectly) expect the serialized form to be deterministic ;; we could consider re-implementing c/value->buffer for URL, but this would have backwards compatibility implications #_ ; (let [url (URL. "https://xtdb.com") doc {:xt/id url}] (fix/submit+await-tx [[::xt/put doc]]) (let [db (xt/db *api*)] (t/is (= doc (xt/entity db url))) (t/is (= #{[url]} (xt/q db '{:find [id] :where [[id :xt/id]]})))))) (t/deftest match-failure-of-a-put-shouldnt-affect-subsequent-indexing-1683 (fix/submit+await-tx [[::xt/match :bar {:xt/id :bar}] [::xt/put {:xt/id :foo}]]) (let [db (xt/db *api*)] (t/is (nil? (xt/entity db :foo)))) (fix/submit+await-tx [[::xt/put {:xt/id :foo}]]) (let [db (xt/db *api*)] (t/is (= {:xt/id :foo} (xt/entity db :foo))) (t/is (= #{[:foo]} (xt/q db '{:find [e], :where [[e :xt/id]]})))))
82890
(ns xtdb.tx-test (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.test :as t] [clojure.tools.logging.impl :as log-impl] [xtdb.api :as xt] [xtdb.bus :as bus] [xtdb.codec :as c] [xtdb.db :as db] [xtdb.fixtures :as fix :refer [*api*]] [xtdb.rdf :as rdf] [xtdb.system :as sys] [xtdb.tx :as tx] [xtdb.tx.event :as txe]) (:import [clojure.lang ExceptionInfo Keyword PersistentArrayMap] [java.net URI URL] java.time.Duration [java.util Collections Date HashMap HashSet UUID])) (t/use-fixtures :each fix/with-node fix/with-silent-test-check (fn [f] (f) (#'tx/reset-tx-fn-error))) (def picasso-id (keyword "http://dbpedia.org/resource/Pablo_Picasso")) (def picasso-eid (c/new-id picasso-id)) (def picasso (-> "xtdb/Pablo_Picasso.ntriples" (rdf/ntriples) (rdf/->default-language) (rdf/->maps-by-id) (get picasso-id))) ;; TODO: This is a large, useful, test that exercises many parts, but ;; might be better split up. (t/deftest test-can-index-tx-ops-acceptance-test (let [content-hash (c/hash-doc picasso) valid-time #inst "2018-05-21" {::xt/keys [tx-time tx-id]} (fix/submit+await-tx [[::xt/put picasso valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/testing "can see entity at transact and valid time" (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash content-hash :vt valid-time :tt tx-time :tx-id tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") tx-time tx-id)))) (t/testing "cannot see entity before valid or transact time" (t/is (nil? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") #inst "2018-05-20" tx-id))) (t/is (nil? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") tx-time -1)))) (t/testing "can see entity after valid or transact time" (t/is (some? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") #inst "2018-05-22" tx-id))) (t/is (some? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") tx-time tx-id)))) (t/testing "can see entity history" (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash content-hash :vt valid-time :tt tx-time :tx-id tx-id})] (db/entity-history index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") :desc {}))))) (t/testing "add new version of entity in the past" (let [new-picasso (assoc picasso :foo :bar) new-content-hash (c/hash-doc new-picasso) new-valid-time #inst "2018-05-20" {new-tx-time ::xt/tx-time new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put new-picasso new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash new-content-hash :vt new-valid-time :tt new-tx-time :tx-id new-tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id))) (t/is (nil? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") #inst "2018-05-20" -1)))))) (t/testing "add new version of entity in the future" (let [new-picasso (assoc picasso :baz :boz) new-content-hash (c/hash-doc new-picasso) new-valid-time #inst "2018-05-22" {new-tx-time ::xt/tx-time new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put new-picasso new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash new-content-hash :vt new-valid-time :tt new-tx-time :tx-id new-tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id))) (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash content-hash :vt valid-time :tt tx-time :tx-id tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time tx-id)))) (t/testing "can correct entity at earlier valid time" (let [new-picasso (assoc picasso :bar :foo) new-content-hash (c/hash-doc new-picasso) prev-tx-time new-tx-time prev-tx-id new-tx-id new-valid-time #inst "2018-05-22" {new-tx-time ::xt/tx-time new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put new-picasso new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash new-content-hash :vt new-valid-time :tt new-tx-time :tx-id new-tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id))) (t/is (= prev-tx-id (:tx-id (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") prev-tx-time prev-tx-id))))))) (t/testing "can delete entity" (let [new-valid-time #inst "2018-05-23" {new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/delete (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (nil? (.content-hash (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id)))) (t/testing "first version of entity is still visible in the past" (t/is (= tx-id (:tx-id (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") valid-time new-tx-id)))))))))) (t/testing "can retrieve history of entity" (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= 5 (count (db/entity-history index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") :desc {:with-corrections? true})))))))) (t/deftest test-can-cas-entity (let [{picasso-tx-time ::xt/tx-time, picasso-tx-id ::xt/tx-id} (xt/submit-tx *api* [[::xt/put picasso]])] (t/testing "compare and set does nothing with wrong content hash" (let [wrong-picasso (assoc picasso :baz :boz) cas-failure-tx (xt/submit-tx *api* [[::xt/cas wrong-picasso (assoc picasso :foo :bar)]])] (xt/await-tx *api* cas-failure-tx (Duration/ofMillis 1000)) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {})))))) (t/testing "compare and set updates with correct content hash" (let [new-picasso (assoc picasso :new? true) {new-tx-time ::xt/tx-time, new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/cas picasso new-picasso]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc new-picasso) :vt new-tx-time :tt new-tx-time :tx-id new-tx-id}) (c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {}))))))) (t/testing "compare and set can update non existing nil entity" (let [ivan {:xt/id :ivan, :value 12} {ivan-tx-time ::xt/tx-time, ivan-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/cas nil ivan]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid (c/new-id :ivan) :content-hash (c/hash-doc ivan) :vt ivan-tx-time :tt ivan-tx-time :tx-id ivan-tx-id})] (db/entity-history index-snapshot :ivan :desc {}))))))) (t/deftest test-match-ops (let [{picasso-tx-time ::xt/tx-time, picasso-tx-id ::xt/tx-id} (xt/submit-tx *api* [[::xt/put picasso]])] (t/testing "match does nothing with wrong content hash" (let [wrong-picasso (assoc picasso :baz :boz) match-failure-tx (xt/submit-tx *api* [[::xt/match picasso-id wrong-picasso]])] (xt/await-tx *api* match-failure-tx (Duration/ofMillis 1000)) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {})))))) (t/testing "match continues with correct content hash" (let [new-picasso (assoc picasso :new? true) {new-tx-time ::xt/tx-time, new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/match picasso-id picasso] [::xt/put new-picasso]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc new-picasso) :vt new-tx-time :tt new-tx-time :tx-id new-tx-id}) (c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {}))))))) (t/testing "match can check non existing entity" (let [ivan {:xt/id :ivan, :value 12} {ivan-tx-time ::xt/tx-time, ivan-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/match :ivan nil] [::xt/put ivan]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid (c/new-id :ivan) :content-hash (c/hash-doc ivan) :vt ivan-tx-time :tt ivan-tx-time :tx-id ivan-tx-id})] (db/entity-history index-snapshot :ivan :desc {}))))))) (t/deftest test-can-evict-entity (t/testing "removes all traces of entity from indices" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :value 0}]]) (fix/submit+await-tx [[::xt/put {:xt/id :foo, :value 1}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [history (db/entity-history index-snapshot :foo :desc {})] (t/testing "eviction removes tx history" (t/is (empty? history))) (t/testing "eviction removes docs" (t/is (empty? (->> (db/fetch-docs (:document-store *api*) (keep :content-hash history)) vals (remove c/evicted-doc?)))))))) (t/testing "clears entity history for valid-time ranges" (fix/submit+await-tx [[::xt/put {:xt/id :bar, :value 0} #inst "2012" #inst "2018"]]) (fix/submit+await-tx [[::xt/evict :bar]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [history (db/entity-history index-snapshot :bar :desc {})] (t/testing "eviction removes tx history" (t/is (empty? history))))))) (defn index-tx [tx tx-events docs] (let [{:keys [xtdb/tx-indexer]} @(:!system *api*) in-flight-tx (db/begin-tx tx-indexer tx nil)] (db/index-tx-events in-flight-tx tx-events docs) (db/commit in-flight-tx))) (t/deftest test-handles-legacy-evict-events (let [{put-tx-time ::xt/tx-time, put-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put picasso #inst "2018-05-21"]]) evict-tx-time #inst "2018-05-22" evict-tx-id (inc put-tx-id) index-evict! (fn [] (index-tx {::xt/tx-time evict-tx-time ::xt/tx-id evict-tx-id} [[:crux.tx/evict picasso-id #inst "2018-05-23"]] {}))] ;; we have to index these manually because the new evict API won't allow docs ;; with the legacy valid-time range (t/testing "eviction throws if legacy params and no explicit override" (t/is (thrown-with-msg? IllegalArgumentException #"^Evict no longer supports time-range parameters." (index-evict!)))) (t/testing "no docs evicted yet" (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (seq (->> (db/fetch-docs (:document-store *api*) (->> (db/entity-history index-snapshot picasso-id :desc {}) (keep :content-hash))) vals (remove c/evicted-doc?)))))) (binding [tx/*evict-all-on-legacy-time-ranges?* true] (let [{:keys [docs]} (index-evict!)] (db/submit-docs (:document-store *api*) docs) (t/testing "eviction removes docs" (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (->> (db/fetch-docs (:document-store *api*) (->> (db/entity-history index-snapshot picasso-id :desc {}) (keep :content-hash))) vals (remove c/evicted-doc?)))))))))) (t/deftest test-multiple-txs-in-same-ms-441 (let [ivan {:crux.db/id :ivan} ivan1 (assoc ivan :value 1) ivan2 (assoc ivan :value 2) t #inst "2019-11-29" docs {(c/hash-doc ivan1) ivan1 (c/hash-doc ivan2) ivan2}] (db/submit-docs (:document-store *api*) docs) (index-tx {::xt/tx-time t, ::xt/tx-id 1} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan1))]] docs) (index-tx {::xt/tx-time t, ::xt/tx-id 2} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan2))]] docs) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 2 (c/hash-doc ivan2)) (c/->EntityTx (c/new-id :ivan) t t 1 (c/hash-doc ivan1))] (db/entity-history index-snapshot :ivan :desc {:with-corrections? true}))) (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 2 (c/hash-doc ivan2))] (db/entity-history index-snapshot :ivan :desc {:start-valid-time t :start-tx {::xt/tx-id 2}}))) (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 1 (c/hash-doc ivan1))] (db/entity-history index-snapshot :ivan :desc {:start-valid-time t :start-tx {::xt/tx-id 1}}))) (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 2 (c/hash-doc ivan2))] (db/entity-history index-snapshot :ivan :asc {:start-valid-time t})))))) (t/deftest test-entity-history-seq-corner-cases (let [ivan {:crux.db/id :ivan} ivan1 (assoc ivan :value 1) ivan2 (assoc ivan :value 2) t1 #inst "2020-05-01" t2 #inst "2020-05-02" docs {(c/hash-doc ivan1) ivan1 (c/hash-doc ivan2) ivan2}] (db/submit-docs (:document-store *api*) docs) (index-tx {::xt/tx-time t1, ::xt/tx-id 1} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan1)) t1]] docs) (index-tx {::xt/tx-time t2, ::xt/tx-id 2} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan2)) t1] [:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan2))]] docs) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [etx-v1-t1 (c/->EntityTx (c/new-id :ivan) t1 t1 1 (c/hash-doc ivan1)) etx-v1-t2 (c/->EntityTx (c/new-id :ivan) t1 t2 2 (c/hash-doc ivan2)) etx-v2-t2 (c/->EntityTx (c/new-id :ivan) t2 t2 2 (c/hash-doc ivan2))] (letfn [(history-asc [opts] (vec (db/entity-history index-snapshot :ivan :asc opts))) (history-desc [opts] (vec (db/entity-history index-snapshot :ivan :desc opts)))] (t/testing "start is inclusive" (t/is (= [etx-v2-t2 etx-v1-t2] (history-desc {:start-tx {::xt/tx-id 2} :start-valid-time t2}))) (t/is (= [etx-v1-t2] (history-desc {:start-valid-time t1}))) (t/is (= [etx-v1-t2 etx-v2-t2] (history-asc {:start-tx {::xt/tx-id 2}}))) (t/is (= [etx-v1-t1 etx-v1-t2 etx-v2-t2] (history-asc {:start-tx {::xt/tx-id 1} :start-valid-time t1 :with-corrections? true})))) (t/testing "end is exclusive" (t/is (= [etx-v2-t2] (history-desc {:start-valid-time t2, :start-tx {::xt/tx-id 2} :end-valid-time t1, :end-tx {::xt/tx-id 1}}))) (t/is (= [] (history-desc {:end-valid-time t2}))) (t/is (= [etx-v1-t1] (history-asc {:end-tx {::xt/tx-id 2}}))) (t/is (= [] (history-asc {:start-valid-time t1, :end-tx {::xt/tx-id 1}}))))))))) (t/deftest test-put-delete-range-semantics (t/are [txs history] (let [eid (keyword (gensym "ivan")) ivan {:xt/id eid, :name "<NAME>"} res (mapv (fn [[value & vts]] (xt/submit-tx *api* [(into (if value [::xt/put (assoc ivan :value value)] [::xt/delete eid]) vts)])) txs) last-tx (last res)] (xt/await-tx *api* last-tx nil) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (for [[vt tx-idx value] history] [vt (get-in res [tx-idx ::xt/tx-id]) (c/hash-doc (when value (assoc ivan :value value)))]) (->> (db/entity-history index-snapshot eid :asc {}) (map (juxt :vt :tx-id :content-hash))))))) ;; pairs ;; [[value vt ?end-vt] ...] ;; [[vt tx-idx value] ...] [[26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-26" 0 26] [#inst "2019-11-29" 0 nil]] ;; re-instates the previous value at the end of the range [[25 #inst "2019-11-25"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 26] [#inst "2019-11-29" 0 25]] ;; delete a range [[25 #inst "2019-11-25"] [nil #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 nil] [#inst "2019-11-29" 0 25]] ;; override a range [[25 #inst "2019-11-25" #inst "2019-11-27"] [nil #inst "2019-11-25" #inst "2019-11-27"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 1 nil] [#inst "2019-11-26" 2 26] [#inst "2019-11-27" 2 26] [#inst "2019-11-29" 0 nil]] ;; merge a range [[25 #inst "2019-11-25" #inst "2019-11-27"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 26] [#inst "2019-11-27" 1 26] [#inst "2019-11-29" 0 nil]] ;; shouldn't override the value at end-vt if there's one there [[25 #inst "2019-11-25"] [29 #inst "2019-11-29"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 2 26] [#inst "2019-11-29" 1 29]] ;; should re-instate 28 at the end of the range [[25 #inst "2019-11-25"] [28 #inst "2019-11-28"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 2 26] [#inst "2019-11-28" 2 26] [#inst "2019-11-29" 1 28]] ;; 26.1 should overwrite the full range [[28 #inst "2019-11-28"] [26 #inst "2019-11-26" #inst "2019-11-29"] [26.1 #inst "2019-11-26"]] [[#inst "2019-11-26" 2 26.1] [#inst "2019-11-28" 2 26.1] [#inst "2019-11-29" 0 28]] ;; 27 should override the latter half of the range [[25 #inst "2019-11-25"] [26 #inst "2019-11-26" #inst "2019-11-29"] [27 #inst "2019-11-27"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 26] [#inst "2019-11-27" 2 27] [#inst "2019-11-29" 0 25]] ;; 27 should still override the latter half of the range [[25 #inst "2019-11-25"] [28 #inst "2019-11-28"] [26 #inst "2019-11-26" #inst "2019-11-29"] [27 #inst "2019-11-27"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 2 26] [#inst "2019-11-27" 3 27] [#inst "2019-11-28" 3 27] [#inst "2019-11-29" 1 28]])) ;; TODO: This test just shows that this is an issue, if we fix the ;; underlying issue this test should start failing. We can then change ;; the second assertion if we want to keep it around to ensure it ;; keeps working. (t/deftest test-corrections-in-the-past-slowes-down-bitemp-144 (let [ivan {:xt/id :ivan :name "<NAME>"} start-valid-time #inst "2019" number-of-versions 1000 tx (fix/submit+await-tx (for [n (range number-of-versions)] [::xt/put (assoc ivan :version n) (Date. (+ (.getTime start-valid-time) (inc (long n))))]))] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [baseline-time (let [start-time (System/nanoTime) valid-time (Date. (+ (.getTime start-valid-time) number-of-versions))] (t/testing "last version of entity is visible at now" (t/is (= valid-time (:vt (db/entity-as-of index-snapshot :ivan valid-time (::xt/tx-id tx)))))) (- (System/nanoTime) start-time))] (let [start-time (System/nanoTime) valid-time (Date. (+ (.getTime start-valid-time) number-of-versions))] (t/testing "no version is visible before transactions" (t/is (nil? (db/entity-as-of index-snapshot :ivan valid-time -1))) (let [corrections-time (- (System/nanoTime) start-time)] ;; TODO: This can be a bit flaky. This assertion was ;; mainly there to prove the opposite, but it has been ;; fixed. Can be added back to sanity check when ;; changing indexes. #_(t/is (>= baseline-time corrections-time))))))))) (t/deftest test-can-read-kv-tx-log (let [ivan {:xt/id :ivan :name "<NAME>"} tx1-ivan (assoc ivan :version 1) tx1-valid-time #inst "2018-11-26" {tx1-id ::xt/tx-id tx1-tx-time ::xt/tx-time} (fix/submit+await-tx [[::xt/put tx1-ivan tx1-valid-time]]) tx2-ivan (assoc ivan :version 2) tx2-petr {:xt/id :petr :name "<NAME>"} tx2-valid-time #inst "2018-11-27" {tx2-id ::xt/tx-id tx2-tx-time ::xt/tx-time} (fix/submit+await-tx [[::xt/put tx2-ivan tx2-valid-time] [::xt/put tx2-petr tx2-valid-time]])] (with-open [log-iterator (db/open-tx-log (:tx-log *api*) nil)] (let [log (iterator-seq log-iterator)] (t/is (not (realized? log))) (t/is (= [{::xt/tx-id tx1-id ::xt/tx-time tx1-tx-time :xtdb.tx.event/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc tx1-ivan) tx1-valid-time]] ::xt/submit-tx-opts {}} {::xt/tx-id tx2-id ::xt/tx-time tx2-tx-time :xtdb.tx.event/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc tx2-ivan) tx2-valid-time] [:crux.tx/put (c/new-id :petr) (c/hash-doc tx2-petr) tx2-valid-time]] ::xt/submit-tx-opts {}}] log)))))) (t/deftest migrates-unhashed-tx-log-eids (let [doc {:crux.db/id :foo} doc-id (c/hash-doc doc)] (db/submit-docs (:document-store *api*) {doc-id doc}) (doto @(db/submit-tx (:tx-log *api*) [[:crux.tx/match :foo (c/new-id c/nil-id-buffer)] [:crux.tx/put :foo doc-id]]) (->> (xt/await-tx *api*))) (t/is (= {:xt/id :foo} (xt/entity (xt/db *api*) :foo))) (with-open [log-iterator (xt/open-tx-log *api* nil nil)] (let [evts (::xt/tx-events (first (iterator-seq log-iterator)))] ;; have to check not= too because Id's `equals` conforms its input to Id (t/is (not= [::xt/match :foo (c/new-id c/nil-id-buffer)] (first evts))) (t/is (not= [::xt/put :foo doc-id] (second evts))) (t/is (= [[::xt/match (c/new-id :foo) (c/new-id c/nil-id-buffer)] [::xt/put (c/new-id :foo) doc-id]] evts)))) (fix/submit+await-tx [[::xt/delete :foo]]) (t/is (nil? (xt/entity (xt/db *api*) :foo))))) (t/deftest test-can-apply-transaction-fn (with-redefs [tx/tx-fn-eval-cache (memoize eval)] (let [v1-ivan {:xt/id :ivan :name "<NAME>" :age 40} v4-ivan (assoc v1-ivan :name "<NAME>") update-attribute-fn {:xt/id :update-attribute-fn :xt/fn '(fn [ctx eid k f] [[::xt/put (update (xtdb.api/entity (xtdb.api/db ctx) eid) k (eval f))]])}] (fix/submit+await-tx [[::xt/put v1-ivan] [::xt/put update-attribute-fn]]) (t/is (= v1-ivan (xt/entity (xt/db *api*) :ivan))) (t/is (= update-attribute-fn (xt/entity (xt/db *api*) :update-attribute-fn))) (some-> (#'tx/reset-tx-fn-error) throw) (let [v2-ivan (assoc v1-ivan :age 41)] (fix/submit+await-tx [[::xt/fn :update-attribute-fn :ivan :age `inc]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v2-ivan (xt/entity (xt/db *api*) :ivan))) (t/testing "resulting documents are indexed" (t/is (= #{[41]} (xt/q (xt/db *api*) '[:find age :where [e :name "<NAME>"] [e :age age]])))) (t/testing "exceptions" (t/testing "non existing tx fn" (let [tx (fix/submit+await-tx '[[::xt/fn :non-existing-fn]])] (t/is (= v2-ivan (xt/entity (xt/db *api*) :ivan))) (t/is (false? (xt/tx-committed? *api* tx))))) (t/testing "invalid arguments" (fix/submit+await-tx '[[::xt/fn :update-attribute-fn :ivan :age foo]]) (t/is (thrown? clojure.lang.Compiler$CompilerException (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "invalid results" (fix/submit+await-tx [[::xt/put {:xt/id :invalid-fn :xt/fn '(fn [ctx] [[::xt/foo]])}]]) (fix/submit+await-tx '[[::xt/fn :invalid-fn]]) (t/is (thrown-with-msg? IllegalArgumentException #"Invalid tx op" (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "no ::xt/fn" (fix/submit+await-tx [[::xt/put {:xt/id :no-fn}]]) (let [tx (fix/submit+await-tx '[[::xt/fn :no-fn]])] (t/is (false? (xt/tx-committed? *api* tx))))) (t/testing "not a fn" (fix/submit+await-tx [[::xt/put {:xt/id :not-a-fn :xt/fn 0}]]) (fix/submit+await-tx '[[::xt/fn :not-a-fn]]) (t/is (thrown? ClassCastException (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "compilation errors" (fix/submit+await-tx [[::xt/put {:xt/id :compilation-error-fn :xt/fn '(fn [ctx] unknown-symbol)}]]) (fix/submit+await-tx '[[::xt/fn :compilation-error-fn]]) (t/is (thrown-with-msg? Exception #"Syntax error compiling" (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "exception thrown" (fix/submit+await-tx [[::xt/put {:xt/id :exception-fn :xt/fn '(fn [ctx] (throw (RuntimeException. "foo")))}]]) (fix/submit+await-tx '[[::xt/fn :exception-fn]]) (t/is (thrown-with-msg? RuntimeException #"foo" (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "still working after errors" (let [v3-ivan (assoc v1-ivan :age 40)] (fix/submit+await-tx [[::xt/fn :update-attribute-fn :ivan :age `dec]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v3-ivan (xt/entity (xt/db *api*) :ivan)))))) (t/testing "sees in-transaction version of entities (including itself)" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 1}]]) (let [tx (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 2}] [::xt/put {:xt/id :doubling-fn :xt/fn '(fn [ctx] [[::xt/put (-> (xtdb.api/entity (xtdb.api/db ctx) :foo) (update :foo * 2))]])}] [::xt/fn :doubling-fn]])] (t/is (xt/tx-committed? *api* tx)) (t/is (= {:xt/id :foo, :foo 4} (xt/entity (xt/db *api*) :foo))))) (t/testing "function ops can return other function ops" (let [returns-fn {:xt/id :returns-fn :xt/fn '(fn [ctx] [[::xt/fn :update-attribute-fn :ivan :name `string/upper-case]])}] (fix/submit+await-tx [[::xt/put returns-fn]]) (fix/submit+await-tx [[::xt/fn :returns-fn]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v4-ivan (xt/entity (xt/db *api*) :ivan))))) (t/testing "repeated 'merge' operation behaves correctly" (let [v5-ivan (merge v4-ivan {:height 180 :hair-style "short" :mass 60}) merge-fn {:xt/id :merge-fn :xt/fn `(fn [ctx# eid# m#] [[::xt/put (merge (xt/entity (xt/db ctx#) eid#) m#)]])}] (fix/submit+await-tx [[::xt/put merge-fn]]) (fix/submit+await-tx [[::xt/fn :merge-fn :ivan {:mass 60, :hair-style "short"}]]) (fix/submit+await-tx [[::xt/fn :merge-fn :ivan {:height 180}]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v5-ivan (xt/entity (xt/db *api*) :ivan))))) (t/testing "function ops can return other function ops that also the forked ctx" (let [returns-fn {:xt/id :returns-fn :xt/fn '(fn [ctx] [[::xt/put {:xt/id :ivan :name "modified ivan"}] [::xt/fn :update-attribute-fn :ivan :name `string/upper-case]])}] (fix/submit+await-tx [[::xt/put returns-fn]]) (fix/submit+await-tx [[::xt/fn :returns-fn]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= {:xt/id :ivan :name "MODIFIED IVAN"} (xt/entity (xt/db *api*) :ivan))))) (t/testing "can access current transaction on tx-fn context" (fix/submit+await-tx [[::xt/put {:xt/id :tx-metadata-fn :xt/fn `(fn [ctx#] [[::xt/put {:xt/id :tx-metadata ::xt/current-tx (xt/indexing-tx ctx#)}]])}]]) (let [submitted-tx (fix/submit+await-tx '[[::xt/fn :tx-metadata-fn]])] (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= {:xt/id :tx-metadata ::xt/current-tx submitted-tx} (xt/entity (xt/db *api*) :tx-metadata))))))))) (t/deftest tx-fn-sees-in-tx-query-results (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 1}]]) (let [tx (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 2}] [::xt/put {:xt/id :put :xt/fn '(fn [ctx doc] [[::xt/put doc]])}] [::xt/fn :put {:xt/id :bar, :ref :foo}] [::xt/put {:xt/id :doubling-fn :xt/fn '(fn [ctx] (let [db (xtdb.api/db ctx)] [[::xt/put {:xt/id :prn-out :e (xtdb.api/entity db :bar) :q (first (xtdb.api/q db {:find '[e v] :where '[[e :xt/id :bar] [e :ref v]]}))}] [::xt/put (-> (xtdb.api/entity db :foo) (update :foo * 2))]]))}] [::xt/fn :doubling-fn]])] (t/is (xt/tx-committed? *api* tx)) (t/is (= {:xt/id :foo, :foo 4} (xt/entity (xt/db *api*) :foo))) (t/is (= {:xt/id :prn-out :e {:xt/id :bar :ref :foo} :q [:bar :foo]} (xt/entity (xt/db *api*) :prn-out))))) (t/deftest tx-log-evict-454 [] (fix/submit+await-tx [[::xt/put {:xt/id :to-evict}]]) (fix/submit+await-tx [[::xt/cas {:xt/id :to-evict} {:xt/id :to-evict :test "test"}]]) (fix/submit+await-tx [[::xt/evict :to-evict]]) (with-open [log-iterator (xt/open-tx-log *api* nil true)] (t/is (= [[[::xt/put {:xt/id #xtdb/id "<KEY>abe<KEY>0<KEY>c<KEY>c<KEY>45bdcf6fb<KEY>", ::xt/evicted? true}]] [[::xt/cas {:xt/id #xtdb/id "6abe<KEY>06510aa<KEY>37371<KEY>c<KEY>c<KEY>224<KEY>bdcf6fb0", ::xt/evicted? true} {:xt/id #xtdb/id "<KEY>abe<KEY>06510aa<KEY>3737167c<KEY>c<KEY>45bdcf6fb0", ::xt/evicted? true}]] [[::xt/evict #xtdb/id "<KEY>"]]] (->> (iterator-seq log-iterator) (map ::xt/tx-ops)))))) (t/deftest transaction-fn-return-values-457 (with-redefs [tx/tx-fn-eval-cache (memoize eval)] (let [nil-fn {:xt/id :nil-fn :xt/fn '(fn [ctx] nil)} false-fn {:xt/id :false-fn :xt/fn '(fn [ctx] false)}] (fix/submit+await-tx [[::xt/put nil-fn] [::xt/put false-fn]]) (fix/submit+await-tx [[::xt/fn :nil-fn] [::xt/put {:xt/id :foo :foo? true}]]) (t/is (= {:xt/id :foo, :foo? true} (xt/entity (xt/db *api*) :foo))) (fix/submit+await-tx [[::xt/fn :false-fn] [::xt/put {:xt/id :bar :bar? true}]]) (t/is (nil? (xt/entity (xt/db *api*) :bar)))))) (t/deftest map-ordering-362 (t/testing "cas is independent of map ordering" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo :bar}]]) (fix/submit+await-tx [[::xt/cas {:foo :bar, :xt/id :foo} {:xt/id :foo, :foo :baz}]]) (t/is (= {:xt/id :foo, :foo :baz} (xt/entity (xt/db *api*) :foo)))) (t/testing "entities with map keys can be retrieved regardless of ordering" (let [doc {:xt/id {:foo 1, :bar 2}}] (fix/submit+await-tx [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db *api*) {:foo 1, :bar 2}))) (t/is (= doc (xt/entity (xt/db *api*) {:bar 2, :foo 1}))))) (t/testing "entities with map values can be joined regardless of ordering" (let [doc {:xt/id {:foo 2, :bar 4}}] (fix/submit+await-tx [[::xt/put doc] [::xt/put {:xt/id :baz, :joins {:bar 4, :foo 2}}] [::xt/put {:xt/id :quux, :joins {:foo 2, :bar 4}}]]) (t/is (= #{[{:foo 2, :bar 4} :baz] [{:foo 2, :bar 4} :quux]} (xt/q (xt/db *api*) '{:find [parent child] :where [[parent :xt/id _] [child :joins parent]]})))))) (t/deftest incomparable-colls-1001 (t/testing "can store and retrieve incomparable colls (#1001)" (let [foo {:xt/id :foo :foo {:bar #{7 "hello"}}}] (fix/submit+await-tx [[::xt/put foo]]) (t/is (= #{[foo]} (xt/q (xt/db *api*) '{:find [(pull ?e [*])] :where [[?e :foo {:bar #{"hello" 7}}]]})))) (let [foo {:xt/id :foo :foo {{:foo 1} :foo1 {:foo 2} :foo2}}] (fix/submit+await-tx [[::xt/put foo]]) (t/is (= #{[foo]} (xt/q (xt/db *api*) '{:find [(pull ?e [*])] :where [[?e :foo {{:foo 2} :foo2, {:foo 1} :foo1}]]})))))) (t/deftest test-java-ids-and-values-1398 (letfn [(test-id [id] (t/testing "As ID" (with-open [node (xt/start-node {})] (let [doc {:xt/id id}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) id))) (t/is #{[id]} (xt/q (xt/db node) '{:find [?id] :where [[?id :xt/id]]})))))) (test-value [value] (t/testing "As Value" (with-open [node (xt/start-node {})] (let [doc {:xt/id :foo :bar value}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) :foo))) (t/is #{[value]} (xt/q (xt/db node) '{:find [?val] :where [[?id :bar ?val]]}))))))] (t/testing "Keyword" (doto (Keyword/intern "foo") (test-id) (test-value))) (t/testing "String" (doto "foo" (test-id) (test-value))) (t/testing "Long" (doto 100 (test-id) (test-value))) (t/testing "UUID" (doto (UUID/randomUUID) (test-id) (test-value))) (t/testing "URI" (doto (URI/create "mailto:<EMAIL>") (test-id) (test-value))) (t/testing "URL" (doto (URL. "https://github.com/xtdb/xtdb") (test-id) (test-value))) (t/testing "IPersistentMap" (doto (-> (PersistentArrayMap/EMPTY) (.assoc "foo" "bar")) (test-id) (test-value))) (t/testing "Set" (doto (HashSet.) (.add "foo") (.add "bar") (test-value))) (t/testing "Singleton Map" (doto (Collections/singletonMap "foo" "bar") (test-id) (test-value))) (t/testing "HashMap with single entry" (doto (HashMap.) (.put "foo" "bar") (test-id) (test-value))) (t/testing "HashMap with multiple entries" (doto (HashMap.) (.put "foo" "bar") (.put "baz" "waka") (test-id) (test-value))) (t/testing "HashMap with entries added in different order" (let [val1 (doto (HashMap.) (.put "foo" "bar") (.put "baz" "waka")) val2 (doto (HashMap.) (.put "baz" "waka") (.put "foo" "bar"))] (t/is (= val1 val2)) (t/testing "As ID" (with-open [node (xt/start-node {})] (let [doc {:xt/id val1}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) val2))) (let [result (xt/q (xt/db node) '{:find [?id] :where [[?id :xt/id]]})] (t/is #{[val1]} result) (t/is #{[val2]} result))))) (t/testing "As Value" (with-open [node (xt/start-node {})] (let [doc {:xt/id :foo :bar val1}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) :foo))) (let [result (xt/q (xt/db node) '{:find [?val] :where [[?id :bar ?val]]})] (t/is #{[val1]} result) (t/is #{[val2]} result))))))))) (t/deftest overlapping-valid-time-ranges-434 (let [_ (fix/submit+await-tx [[::xt/put {:xt/id :foo, :v 10} #inst "2019-01-01"] [::xt/put {:xt/id :foo, :v 10} #inst "2020-01-10"] [::xt/put {:xt/id :bar, :v 5} #inst "2020-01-05"] [::xt/put {:xt/id :bar, :v 10} #inst "2020-01-10"] [::xt/put {:xt/id :baz, :v 10} #inst "2020-01-10"]]) last-tx (fix/submit+await-tx [[::xt/put {:xt/id :foo, :v 10} #inst "2019-01-01"] [::xt/put {:xt/id :bar, :v 7} #inst "2020-01-07"] ;; mixing foo and bar shouldn't matter [::xt/put {:xt/id :foo, :v 8} #inst "2020-01-08" #inst "2020-01-12"] ; reverts to 10 afterwards [::xt/put {:xt/id :foo, :v 9} #inst "2020-01-09" #inst "2020-01-11"] ; reverts to 8 afterwards, then 10 [::xt/put {:xt/id :bar, :v 8} #inst "2020-01-08" #inst "2020-01-09"] ; reverts to 7 afterwards [::xt/put {:xt/id :bar, :v 11} #inst "2020-01-11" #inst "2020-01-12"] ; reverts to 10 afterwards ]) db (xt/db *api*)] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [eid->history (fn [eid] (let [history (db/entity-history index-snapshot (c/new-id eid) :asc {:start-valid-time #inst "2020-01-01"}) docs (db/fetch-docs (:document-store *api*) (map :content-hash history))] (->> history (mapv (fn [{:keys [content-hash vt]}] [vt (:v (get docs content-hash))])))))] ;; transaction functions, asserts both still apply at the start of the transaction (t/is (= [[#inst "2020-01-08" 8] [#inst "2020-01-09" 9] [#inst "2020-01-10" 9] [#inst "2020-01-11" 8] [#inst "2020-01-12" 10]] (eid->history :foo))) (t/is (= [[#inst "2020-01-05" 5] [#inst "2020-01-07" 7] [#inst "2020-01-08" 8] [#inst "2020-01-09" 7] [#inst "2020-01-10" 10] [#inst "2020-01-11" 11] [#inst "2020-01-12" 10]] (eid->history :bar))))))) (t/deftest cas-docs-not-evicting-371 (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo :bar}] [::xt/put {:xt/id :frob :foo :bar}]]) (fix/submit+await-tx [[::xt/cas {:xt/id :foo, :foo :baz} {:xt/id :foo, :foo :quux}] [::xt/put {:xt/id :frob :foo :baz}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (let [docs (db/fetch-docs (:document-store *api*) #{(c/hash-doc {:xt/id :foo, :foo :bar}) (c/hash-doc {:xt/id :foo, :foo :baz}) (c/hash-doc {:xt/id :foo, :foo :quux})})] (t/is (= 3 (count docs))) (t/is (every? (comp c/evicted-doc? val) docs))) (t/testing "even though the CaS was unrelated, the whole transaction fails - we should still evict those docs" (fix/submit+await-tx [[::xt/evict :frob]]) (let [docs (db/fetch-docs (:document-store *api*) #{(c/hash-doc {:xt/id :frob, :foo :bar}) (c/hash-doc {:xt/id :frob, :foo :baz})})] (t/is (= 2 (count docs))) (t/is (every? (comp c/evicted-doc? val) docs))))) (t/deftest raises-tx-events-422 (let [!events (atom []) !latch (promise)] (bus/listen (:bus *api*) {::xt/event-types #{::tx/indexing-tx ::tx/indexed-tx}} (fn [evt] (swap! !events conj evt) (when (= ::tx/indexed-tx (::xt/event-type evt)) (deliver !latch @!events)))) (let [doc-1 {:xt/id :foo, :value 1} doc-2 {:xt/id :bar, :value 2} doc-ids #{(c/hash-doc doc-1) (c/hash-doc doc-2)} submitted-tx (fix/submit+await-tx [[::xt/put doc-1] [::xt/put doc-2]])] (when (= ::timeout (deref !latch 500 ::timeout)) (t/is false)) (t/is (= [{::xt/event-type ::tx/indexing-tx, :submitted-tx submitted-tx} {::xt/event-type ::tx/indexed-tx, :submitted-tx submitted-tx, :committed? true :doc-ids doc-ids :av-count 4 ::txe/tx-events [[:crux.tx/put #xtdb/id "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33" #xtdb/id "974e28e6484fb6c66e5ca6444ec616207800d815"] [:crux.tx/put #xtdb/id "62cdb7020ff920e5aa642c3d4066950dd1f01f4d" #xtdb/id "f2cb628efd5123743c30137b08282b9dee82104a"]]}] (-> (vec @!events) (update 1 dissoc :bytes-indexed))))))) (t/deftest await-fails-quickly-738 (with-redefs [tx/index-tx-event (fn [_ _ _] (Thread/sleep 100) (throw (ex-info "test error for await-fails-quickly-738" {})))] (let [last-tx (xt/submit-tx *api* [[::xt/put {:xt/id :foo}]])] (t/testing "Testing fail while we are awaiting an event" (t/is (thrown-with-msg? Exception #"Transaction ingester aborted" (xt/await-tx *api* last-tx (Duration/ofMillis 1000))))) (t/testing "Testing fail before we await an event" (t/is (thrown-with-msg? Exception #"Transaction ingester aborted" (xt/await-tx *api* last-tx (Duration/ofMillis 1000)))))))) (t/deftest test-evict-documents-with-common-attributes (fix/submit+await-tx [[::xt/put {:xt/id :foo, :count 1}] [::xt/put {:xt/id :bar, :count 1}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (t/is (= #{[:bar]} (xt/q (xt/db *api*) '{:find [?e] :where [[?e :count 1]]})))) (t/deftest replaces-tx-fn-arg-docs (fix/submit+await-tx [[::xt/put {:xt/id :put-ivan :xt/fn '(fn [ctx doc] [[::xt/put (assoc doc :xt/id :ivan)]])}]]) (t/testing "replaces args doc with resulting ops" (fix/submit+await-tx [[::xt/fn :put-ivan {:name "<NAME>"}]]) (t/is (= {:xt/id :ivan, :name "<NAME>"} (xt/entity (xt/db *api*) :ivan))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) last ::txe/tx-events first last))] (t/is (= {:crux.db.fn/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc {:xt/id :ivan, :name "<NAME>"})]]} (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt) (dissoc :xt/id)))))) (t/testing "replaces fn with no args" (fix/submit+await-tx [[::xt/put {:xt/id :no-args :xt/fn '(fn [ctx] [[::xt/put {:xt/id :no-fn-args-doc}]])}]]) (fix/submit+await-tx [[::xt/fn :no-args]]) (t/is (= {:xt/id :no-fn-args-doc} (xt/entity (xt/db *api*) :no-fn-args-doc))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) last ::txe/tx-events first last))] (t/is (= {:crux.db.fn/tx-events [[:crux.tx/put (c/new-id :no-fn-args-doc) (c/hash-doc {:xt/id :no-fn-args-doc})]]} (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt) (dissoc :xt/id)))))) (t/testing "nested tx-fn" (fix/submit+await-tx [[::xt/put {:xt/id :put-bob-and-ivan :xt/fn '(fn [ctx bob ivan] [[::xt/put (assoc bob :xt/id :bob)] [::xt/fn :put-ivan ivan]])}]]) (fix/submit+await-tx [[::xt/fn :put-bob-and-ivan {:name "<NAME>"} {:name "<NAME>"}]]) (t/is (= {:xt/id :ivan, :name "<NAME>"} (xt/entity (xt/db *api*) :ivan))) (t/is (= {:xt/id :bob, :name "<NAME>"} (xt/entity (xt/db *api*) :bob))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) 1)] (-> (iterator-seq tx-log) last ::txe/tx-events first last)) arg-doc (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt)) sub-arg-doc-id (-> arg-doc :crux.db.fn/tx-events second last) sub-arg-doc (-> (db/fetch-docs (:document-store *api*) #{sub-arg-doc-id}) (get sub-arg-doc-id) (c/crux->xt))] (t/is (= {:xt/id (:xt/id arg-doc) :crux.db.fn/tx-events [[:crux.tx/put (c/new-id :bob) (c/hash-doc {:xt/id :bob, :name "<NAME>"})] [:crux.tx/fn (c/new-id :put-ivan) sub-arg-doc-id]]} arg-doc)) (t/is (= {:xt/id (:xt/id sub-arg-doc) :crux.db.fn/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc {:xt/id :ivan :name "<NAME>"})]]} sub-arg-doc)))) (t/testing "copes with args doc having been replaced" (let [sergei {:xt/id :sergei :name "<NAME>"} arg-doc {:xt/id :args :crux.db.fn/tx-events [[:crux.tx/put :sergei (c/hash-doc sergei)]]}] (db/submit-docs (:document-store *api*) {(c/hash-doc arg-doc) arg-doc (c/hash-doc sergei) sergei}) (let [tx @(db/submit-tx (:tx-log *api*) [[:crux.tx/fn :put-sergei (c/hash-doc arg-doc)]])] (xt/await-tx *api* tx) (t/is (= sergei (xt/entity (xt/db *api*) :sergei)))))) (t/testing "failed tx-fn" (fix/submit+await-tx [[::xt/fn :put-petr {:name "<NAME>"}]]) (t/is (nil? (xt/entity (xt/db *api*) :petr))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) last ::txe/tx-events first last))] (t/is (true? (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) :crux.db.fn/failed?)))))) (t/deftest handles-legacy-tx-fns-with-no-args-doc ;; we used to not submit args docs if the tx-fn was 0-arg, and hence had nothing to replace ;; we don't want the fix to assume that all tx-fns on the tx-log have an arg-doc (let [tx-fn (-> {:xt/id :tx-fn, :xt/fn '(fn [ctx] [[::xt/put {:xt/id :ivan}]])} (c/xt->crux)) docs {(c/hash-doc tx-fn) tx-fn}] (db/submit-docs (:document-store *api*) docs) (index-tx {::xt/tx-time (Date.), ::xt/tx-id 0} [[:crux.tx/put (c/new-id :tx-fn) tx-fn]] docs) (index-tx {::xt/tx-time (Date.), ::xt/tx-id 1} [[:crux.tx/fn :tx-fn]] docs) (t/is (= {:xt/id :ivan} (xt/entity (xt/db *api*) :ivan))))) (t/deftest test-tx-fn-doc-race-1049 (let [put-fn {:xt/id :put-fn :xt/fn '(fn [ctx doc] [[::xt/put doc]])} foo-doc {:crux.db/id :foo} !arg-doc-resps (atom [{:crux.db.fn/args [foo-doc]} {:crux.db.fn/tx-events [[:crux.tx/put (c/new-id :foo) (c/hash-doc foo-doc)]]}]) ->mocked-doc-store (fn [_opts] (reify db/DocumentStore (submit-docs [_ docs]) (fetch-docs [_ ids] (->> ids (into {} (map (juxt identity (some-fn {(c/hash-doc put-fn) (c/xt->crux put-fn) (c/hash-doc foo-doc) foo-doc} (fn [id] (let [[[doc] _] (swap-vals! !arg-doc-resps rest)] (merge doc {:crux.db/id id})))))))))))] (with-open [node (xt/start-node {:xtdb/document-store ->mocked-doc-store})] (xt/submit-tx node [[::xt/put put-fn]]) (xt/submit-tx node [[::xt/fn :put-fn foo-doc]]) (xt/sync node) (t/is (= #{[:put-fn] [:foo]} (xt/q (xt/db node) '{:find [?e] :where [[?e :xt/id]]})))))) (t/deftest ensure-tx-fn-arg-docs-replaced-even-when-tx-aborts-960 (fix/submit+await-tx [[::xt/put {:xt/id :foo :xt/fn '(fn [ctx arg] [])}] [::xt/match :foo {:xt/id :foo}] [::xt/fn :foo :foo-arg]]) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) first :xtdb.tx.event/tx-events last last)) arg-doc (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt))] (t/is (= {:crux.db.fn/failed? true} (dissoc arg-doc :xt/id))) (t/is (uuid? (:xt/id arg-doc))))) (t/deftest test-documents-with-int-short-byte-float-eids-1043 (fix/submit+await-tx [[::xt/put {:xt/id (int 10), :name "foo"}] [::xt/put {:xt/id (short 12), :name "bar"}] [::xt/put {:xt/id (byte 16), :name "baz"}] [::xt/put {:xt/id (float 1.1), :name "quux"}]]) (let [db (xt/db *api*)] (t/is (= #{["foo"] ["bar"] ["baz"] ["quux"]} (xt/q (xt/db *api*) '{:find [?name] :where [[?e :name ?name]]}))) (t/is (= {:xt/id (long 10), :name "foo"} (xt/entity db (int 10)))) (t/is (= {:xt/id (long 10), :name "foo"} (xt/entity db (long 10)))) (t/is (= #{[10 "foo"]} (xt/q (xt/db *api*) {:find '[?e ?name] :where '[[?e :name ?name]] :args [{:?e (int 10)}]})))) (t/testing "10 as int and long are the same key" (fix/submit+await-tx [[::xt/put {:xt/id 10, :name "foo2"}]]) (t/is (= #{[10 "foo2"]} (xt/q (xt/db *api*) {:find '[?e ?name] :where '[[?e :name ?name]] :args [{:?e (int 10)}]}))))) (t/deftest test-put-evict-in-same-transaction-1337 (t/testing "put then evict" (fix/submit+await-tx [[::xt/put {:xt/id :test1/a, :test1? true}]]) (fix/submit+await-tx [[::xt/put {:xt/id :test1/b, :test1? true, :test1/evicted? true}] [::xt/evict :test1/b]]) (let [db (xt/db *api*)] (t/is (= {:xt/id :test1/a, :test1? true} (xt/entity db :test1/a))) (t/is (nil? (xt/entity db :test1/b))) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :test1/evicted? nil))) (t/is (empty? (db/entity-history index-snapshot :test1/b :asc {})))) (t/is (= #{[:test1/a]} (xt/q db '{:find [?e], :where [[?e :test1? true]]}))) (t/is (= #{} (xt/q db '{:find [?e], :where [[?e :test1/evicted? true]]}))))) (t/testing "put then evict an earlier entity" (fix/submit+await-tx [[::xt/put {:xt/id :test2/a, :test2? true, :test2/evicted? true}]]) (fix/submit+await-tx [[::xt/put {:xt/id :test2/b, :test2? true}] [::xt/evict :test2/a]]) (let [db (xt/db *api*)] (t/is (nil? (xt/entity db :test2/a))) (t/is (= {:xt/id :test2/b, :test2? true} (xt/entity db :test2/b))) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :test2/evicted? nil))) (t/is (empty? (db/entity-history index-snapshot :test2/a :asc {})))) (t/is (= #{[:test2/b]} (xt/q db '{:find [?e], :where [[?e :test2? true]]}))) (t/is (= #{} (xt/q db '{:find [?e], :where [[?e :test2/evicted? true]]}))))) (t/testing "evict then put" (fix/submit+await-tx [[::xt/put {:xt/id :test3/a, :test3? true}]]) (fix/submit+await-tx [[::xt/evict :test3/a] [::xt/put {:xt/id :test3/b, :test3? true}]]) (let [db (xt/db *api*)] (t/is (nil? (xt/entity db :test3/a))) (t/is (= {:xt/id :test3/b, :test3? true} (xt/entity db :test3/b))) (t/is (= #{[:test3/b]} (xt/q db '{:find [?e], :where [[?e :test3? true]]}))))) ;; TODO fails, see #1337 #_ (t/testing "evict then re-put" (fix/submit+await-tx [[::xt/put {:xt/id :test4, :test4? true}]]) (fix/submit+await-tx [[::xt/evict :test4] [::xt/put {:xt/id :test4, :test4? true}]]) (let [db (xt/db *api*)] (t/is (= {:xt/id :test4, :test4? true} (xt/entity db :test4))) (t/is (= #{[:test4]} (xt/q db '{:find [?e], :where [[?e :test4? true]]})))))) (t/deftest test-avs-only-shared-by-evicted-entities-1338 (t/testing "only one entity, AV removed" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :evict-me? true}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :evict-me? nil))))) ;; TODO fails, see #1338 #_ (t/testing "shared by multiple evicted entities" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :evict-me? true}] [::xt/put {:xt/id :bar, :evict-me? true}]]) (fix/submit+await-tx [[::xt/evict :foo] [::xt/evict :bar]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :evict-me? nil)))))) (t/deftest node-shutdown-interrupts-tx-ingestion (let [op-count 10 !calls (atom 0) node (xt/start-node {})] (with-redefs [tx/index-tx-event (let [f tx/index-tx-event] (fn [& args] (let [target-time (+ (System/currentTimeMillis) 200)] (while (< (System/currentTimeMillis) target-time))) (swap! !calls inc) (apply f args)))] @(try (let [tx (xt/submit-tx node (repeat op-count [::xt/put {:xt/id :foo}])) await-fut (future (t/is (thrown? InterruptedException (xt/await-tx node tx))))] (Thread/sleep 100) ; to ensure the await starts before the node closes await-fut) (finally (.close node)))) (t/is (instance? InterruptedException (db/ingester-error (:tx-ingester node)))) (t/is (< @!calls op-count)))) (t/deftest empty-tx-can-be-awaited-1519 (let [tx (xt/submit-tx *api* []) _ (xt/await-tx *api* tx (Duration/ofSeconds 1))] (t/is (= (select-keys tx [::xt/tx-id]) (xt/latest-submitted-tx *api*))) (t/is (= tx (xt/latest-completed-tx *api*))) (t/is (xt/tx-committed? *api* tx)))) (t/deftest handles-secondary-indices (letfn [(with-persistent-golden-stores [node-config db-dir] (-> node-config (assoc :xtdb/tx-log {:kv-store {:xtdb/module 'xtdb.rocksdb/->kv-store :db-dir (io/file db-dir "txs")}} :xtdb/document-store {:kv-store {:xtdb/module 'xtdb.rocksdb/->kv-store :db-dir (io/file db-dir "docs")}}))) (with-persistent-indices [node-config idx-dir] (-> node-config (assoc :xtdb/index-store {:kv-store {:xtdb/module 'xtdb.rocksdb/->kv-store :db-dir idx-dir}}))) (with-secondary-index ([node-config after-tx-id opts process-tx-f] (-> node-config (assoc ::index2 (-> (fn [{:keys [secondary-indices]}] (tx/register-index! secondary-indices after-tx-id opts process-tx-f) nil) (with-meta {::sys/deps {:secondary-indices :xtdb/secondary-indices} ::sys/before #{[:xtdb/tx-ingester]}}))))))] (t/testing "indexes into secondary indices" (let [!txs (atom [])] (with-open [node (xt/start-node (-> {} (with-secondary-index nil {} (fn [tx] (swap! !txs conj tx)))))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]]) (t/is (= [0] (map ::xt/tx-id @!txs)))))) (t/testing "secondary indices catch up to XTDB indices on node startup" (fix/with-tmp-dirs #{db-dir idx-dir} (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir)))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]])) (let [!txs (atom [])] (with-open [_node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir) (with-secondary-index nil {} (fn [tx] (swap! !txs conj tx)))))] ;; NOTE: don't need `sync` - should happen before node becomes available. (t/is (= [0] (map ::xt/tx-id @!txs))))))) (t/testing "XTDB catches up without replaying tx to secondary indices" (fix/with-tmp-dirs #{db-dir} (let [!txs (atom [])] (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-secondary-index nil {} (fn [tx] (swap! !txs conj tx)))))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]])) (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-secondary-index 0 {} (fn [tx] (swap! !txs conj tx)))))] (xt/sync node) (t/is (= 0 (::xt/tx-id (xt/latest-completed-tx node)))) (t/is (= [0] (map ::xt/tx-id @!txs))))))) (t/testing "passes through tx-ops on request" (fix/with-tmp-dirs #{db-dir idx-dir} (let [!txs (atom [])] (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir) (with-secondary-index nil {:with-tx-ops? true} (fn [tx] (swap! !txs conj tx)))))] (fix/submit+await-tx node [[::xt/put {:xt/id :ivan :name "<NAME>"}]]) (t/is (= [{::xt/tx-id 0 ::xt/tx-ops [[::xt/put {:xt/id :ivan, :name "<NAME>"}]]}] (->> @!txs (map #(select-keys % [::xt/tx-id ::xt/tx-ops]))))))))) (with-redefs [log-impl/enabled? (constantly false)] (t/testing "handles secondary indexes blowing up" (with-open [node (xt/start-node (-> {} (with-secondary-index nil {} (fn [_tx] (throw (ex-info "boom!" {}))))))] (t/is (thrown-with-msg? ExceptionInfo #"boom!" (try (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]]) (catch Exception e (throw (.getCause e)))))) (t/is (nil? (xt/latest-completed-tx node))))) (t/testing "handles secondary indexes blowing up on startup" (fix/with-tmp-dirs #{db-dir idx-dir} (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir)))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]])) (t/is (thrown-with-msg? ExceptionInfo #"boom!" (try (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir) (with-secondary-index nil {} (fn [_tx] (throw (ex-info "boom!" {})))))) (catch Exception e (throw (.getCause e))))))))))) (t/deftest tx-committed-throws-correctly-1579 (let [tx (fix/submit+await-tx [[::xt/put {:xt/id :foo}]])] (t/is (xt/tx-committed? *api* tx)) (t/is (xt/tx-committed? *api* {::xt/tx-id 0})) (t/is (thrown? xtdb.IllegalArgumentException (xt/tx-committed? *api* nil))) (t/is (thrown? xtdb.IllegalArgumentException (xt/tx-committed? *api* {}))) (t/is (thrown? xtdb.IllegalArgumentException (xt/tx-committed? *api* {::xt/tx-id nil}))) (t/is (thrown? ClassCastException (xt/tx-committed? *api* {::xt/tx-id :a}))) ;; "skipped" tx-ids (e.g. handling Kafka offsets), and negative or non-integer tx-ids are also incorrect but not currently detected #_ (t/is (thrown? xtdb.api.NodeOutOfSyncException (xt/tx-committed? *api* {::xt/tx-id -1.5}))))) (t/deftest can-query-documents-with-url-id-1638 ;; TODO: the (XT) hash of the URL depends on the serialized form of the URL object, ;; which in turn depends on its cached hashCode field. couple of fun things here: ;; - if nothing has yet computed the hashCode, it serializes `-1` ;; - the hashCode computation depends on the resolved IP address of the domain name (non-deterministic) ;; we (arguably incorrectly) expect the serialized form to be deterministic ;; we could consider re-implementing c/value->buffer for URL, but this would have backwards compatibility implications #_ ; (let [url (URL. "https://xtdb.com") doc {:xt/id url}] (fix/submit+await-tx [[::xt/put doc]]) (let [db (xt/db *api*)] (t/is (= doc (xt/entity db url))) (t/is (= #{[url]} (xt/q db '{:find [id] :where [[id :xt/id]]})))))) (t/deftest match-failure-of-a-put-shouldnt-affect-subsequent-indexing-1683 (fix/submit+await-tx [[::xt/match :bar {:xt/id :bar}] [::xt/put {:xt/id :foo}]]) (let [db (xt/db *api*)] (t/is (nil? (xt/entity db :foo)))) (fix/submit+await-tx [[::xt/put {:xt/id :foo}]]) (let [db (xt/db *api*)] (t/is (= {:xt/id :foo} (xt/entity db :foo))) (t/is (= #{[:foo]} (xt/q db '{:find [e], :where [[e :xt/id]]})))))
true
(ns xtdb.tx-test (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.test :as t] [clojure.tools.logging.impl :as log-impl] [xtdb.api :as xt] [xtdb.bus :as bus] [xtdb.codec :as c] [xtdb.db :as db] [xtdb.fixtures :as fix :refer [*api*]] [xtdb.rdf :as rdf] [xtdb.system :as sys] [xtdb.tx :as tx] [xtdb.tx.event :as txe]) (:import [clojure.lang ExceptionInfo Keyword PersistentArrayMap] [java.net URI URL] java.time.Duration [java.util Collections Date HashMap HashSet UUID])) (t/use-fixtures :each fix/with-node fix/with-silent-test-check (fn [f] (f) (#'tx/reset-tx-fn-error))) (def picasso-id (keyword "http://dbpedia.org/resource/Pablo_Picasso")) (def picasso-eid (c/new-id picasso-id)) (def picasso (-> "xtdb/Pablo_Picasso.ntriples" (rdf/ntriples) (rdf/->default-language) (rdf/->maps-by-id) (get picasso-id))) ;; TODO: This is a large, useful, test that exercises many parts, but ;; might be better split up. (t/deftest test-can-index-tx-ops-acceptance-test (let [content-hash (c/hash-doc picasso) valid-time #inst "2018-05-21" {::xt/keys [tx-time tx-id]} (fix/submit+await-tx [[::xt/put picasso valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/testing "can see entity at transact and valid time" (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash content-hash :vt valid-time :tt tx-time :tx-id tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") tx-time tx-id)))) (t/testing "cannot see entity before valid or transact time" (t/is (nil? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") #inst "2018-05-20" tx-id))) (t/is (nil? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") tx-time -1)))) (t/testing "can see entity after valid or transact time" (t/is (some? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") #inst "2018-05-22" tx-id))) (t/is (some? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") tx-time tx-id)))) (t/testing "can see entity history" (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash content-hash :vt valid-time :tt tx-time :tx-id tx-id})] (db/entity-history index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") :desc {}))))) (t/testing "add new version of entity in the past" (let [new-picasso (assoc picasso :foo :bar) new-content-hash (c/hash-doc new-picasso) new-valid-time #inst "2018-05-20" {new-tx-time ::xt/tx-time new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put new-picasso new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash new-content-hash :vt new-valid-time :tt new-tx-time :tx-id new-tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id))) (t/is (nil? (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") #inst "2018-05-20" -1)))))) (t/testing "add new version of entity in the future" (let [new-picasso (assoc picasso :baz :boz) new-content-hash (c/hash-doc new-picasso) new-valid-time #inst "2018-05-22" {new-tx-time ::xt/tx-time new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put new-picasso new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash new-content-hash :vt new-valid-time :tt new-tx-time :tx-id new-tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id))) (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash content-hash :vt valid-time :tt tx-time :tx-id tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time tx-id)))) (t/testing "can correct entity at earlier valid time" (let [new-picasso (assoc picasso :bar :foo) new-content-hash (c/hash-doc new-picasso) prev-tx-time new-tx-time prev-tx-id new-tx-id new-valid-time #inst "2018-05-22" {new-tx-time ::xt/tx-time new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put new-picasso new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (c/map->EntityTx {:eid picasso-eid :content-hash new-content-hash :vt new-valid-time :tt new-tx-time :tx-id new-tx-id}) (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id))) (t/is (= prev-tx-id (:tx-id (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") prev-tx-time prev-tx-id))))))) (t/testing "can delete entity" (let [new-valid-time #inst "2018-05-23" {new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/delete (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (nil? (.content-hash (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") new-valid-time new-tx-id)))) (t/testing "first version of entity is still visible in the past" (t/is (= tx-id (:tx-id (db/entity-as-of index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") valid-time new-tx-id)))))))))) (t/testing "can retrieve history of entity" (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= 5 (count (db/entity-history index-snapshot (keyword "http://dbpedia.org/resource/Pablo_Picasso") :desc {:with-corrections? true})))))))) (t/deftest test-can-cas-entity (let [{picasso-tx-time ::xt/tx-time, picasso-tx-id ::xt/tx-id} (xt/submit-tx *api* [[::xt/put picasso]])] (t/testing "compare and set does nothing with wrong content hash" (let [wrong-picasso (assoc picasso :baz :boz) cas-failure-tx (xt/submit-tx *api* [[::xt/cas wrong-picasso (assoc picasso :foo :bar)]])] (xt/await-tx *api* cas-failure-tx (Duration/ofMillis 1000)) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {})))))) (t/testing "compare and set updates with correct content hash" (let [new-picasso (assoc picasso :new? true) {new-tx-time ::xt/tx-time, new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/cas picasso new-picasso]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc new-picasso) :vt new-tx-time :tt new-tx-time :tx-id new-tx-id}) (c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {}))))))) (t/testing "compare and set can update non existing nil entity" (let [ivan {:xt/id :ivan, :value 12} {ivan-tx-time ::xt/tx-time, ivan-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/cas nil ivan]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid (c/new-id :ivan) :content-hash (c/hash-doc ivan) :vt ivan-tx-time :tt ivan-tx-time :tx-id ivan-tx-id})] (db/entity-history index-snapshot :ivan :desc {}))))))) (t/deftest test-match-ops (let [{picasso-tx-time ::xt/tx-time, picasso-tx-id ::xt/tx-id} (xt/submit-tx *api* [[::xt/put picasso]])] (t/testing "match does nothing with wrong content hash" (let [wrong-picasso (assoc picasso :baz :boz) match-failure-tx (xt/submit-tx *api* [[::xt/match picasso-id wrong-picasso]])] (xt/await-tx *api* match-failure-tx (Duration/ofMillis 1000)) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {})))))) (t/testing "match continues with correct content hash" (let [new-picasso (assoc picasso :new? true) {new-tx-time ::xt/tx-time, new-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/match picasso-id picasso] [::xt/put new-picasso]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc new-picasso) :vt new-tx-time :tt new-tx-time :tx-id new-tx-id}) (c/map->EntityTx {:eid picasso-eid :content-hash (c/hash-doc picasso) :vt picasso-tx-time :tt picasso-tx-time :tx-id picasso-tx-id})] (db/entity-history index-snapshot picasso-id :desc {}))))))) (t/testing "match can check non existing entity" (let [ivan {:xt/id :ivan, :value 12} {ivan-tx-time ::xt/tx-time, ivan-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/match :ivan nil] [::xt/put ivan]])] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/map->EntityTx {:eid (c/new-id :ivan) :content-hash (c/hash-doc ivan) :vt ivan-tx-time :tt ivan-tx-time :tx-id ivan-tx-id})] (db/entity-history index-snapshot :ivan :desc {}))))))) (t/deftest test-can-evict-entity (t/testing "removes all traces of entity from indices" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :value 0}]]) (fix/submit+await-tx [[::xt/put {:xt/id :foo, :value 1}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [history (db/entity-history index-snapshot :foo :desc {})] (t/testing "eviction removes tx history" (t/is (empty? history))) (t/testing "eviction removes docs" (t/is (empty? (->> (db/fetch-docs (:document-store *api*) (keep :content-hash history)) vals (remove c/evicted-doc?)))))))) (t/testing "clears entity history for valid-time ranges" (fix/submit+await-tx [[::xt/put {:xt/id :bar, :value 0} #inst "2012" #inst "2018"]]) (fix/submit+await-tx [[::xt/evict :bar]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [history (db/entity-history index-snapshot :bar :desc {})] (t/testing "eviction removes tx history" (t/is (empty? history))))))) (defn index-tx [tx tx-events docs] (let [{:keys [xtdb/tx-indexer]} @(:!system *api*) in-flight-tx (db/begin-tx tx-indexer tx nil)] (db/index-tx-events in-flight-tx tx-events docs) (db/commit in-flight-tx))) (t/deftest test-handles-legacy-evict-events (let [{put-tx-time ::xt/tx-time, put-tx-id ::xt/tx-id} (fix/submit+await-tx [[::xt/put picasso #inst "2018-05-21"]]) evict-tx-time #inst "2018-05-22" evict-tx-id (inc put-tx-id) index-evict! (fn [] (index-tx {::xt/tx-time evict-tx-time ::xt/tx-id evict-tx-id} [[:crux.tx/evict picasso-id #inst "2018-05-23"]] {}))] ;; we have to index these manually because the new evict API won't allow docs ;; with the legacy valid-time range (t/testing "eviction throws if legacy params and no explicit override" (t/is (thrown-with-msg? IllegalArgumentException #"^Evict no longer supports time-range parameters." (index-evict!)))) (t/testing "no docs evicted yet" (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (seq (->> (db/fetch-docs (:document-store *api*) (->> (db/entity-history index-snapshot picasso-id :desc {}) (keep :content-hash))) vals (remove c/evicted-doc?)))))) (binding [tx/*evict-all-on-legacy-time-ranges?* true] (let [{:keys [docs]} (index-evict!)] (db/submit-docs (:document-store *api*) docs) (t/testing "eviction removes docs" (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (->> (db/fetch-docs (:document-store *api*) (->> (db/entity-history index-snapshot picasso-id :desc {}) (keep :content-hash))) vals (remove c/evicted-doc?)))))))))) (t/deftest test-multiple-txs-in-same-ms-441 (let [ivan {:crux.db/id :ivan} ivan1 (assoc ivan :value 1) ivan2 (assoc ivan :value 2) t #inst "2019-11-29" docs {(c/hash-doc ivan1) ivan1 (c/hash-doc ivan2) ivan2}] (db/submit-docs (:document-store *api*) docs) (index-tx {::xt/tx-time t, ::xt/tx-id 1} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan1))]] docs) (index-tx {::xt/tx-time t, ::xt/tx-id 2} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan2))]] docs) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 2 (c/hash-doc ivan2)) (c/->EntityTx (c/new-id :ivan) t t 1 (c/hash-doc ivan1))] (db/entity-history index-snapshot :ivan :desc {:with-corrections? true}))) (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 2 (c/hash-doc ivan2))] (db/entity-history index-snapshot :ivan :desc {:start-valid-time t :start-tx {::xt/tx-id 2}}))) (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 1 (c/hash-doc ivan1))] (db/entity-history index-snapshot :ivan :desc {:start-valid-time t :start-tx {::xt/tx-id 1}}))) (t/is (= [(c/->EntityTx (c/new-id :ivan) t t 2 (c/hash-doc ivan2))] (db/entity-history index-snapshot :ivan :asc {:start-valid-time t})))))) (t/deftest test-entity-history-seq-corner-cases (let [ivan {:crux.db/id :ivan} ivan1 (assoc ivan :value 1) ivan2 (assoc ivan :value 2) t1 #inst "2020-05-01" t2 #inst "2020-05-02" docs {(c/hash-doc ivan1) ivan1 (c/hash-doc ivan2) ivan2}] (db/submit-docs (:document-store *api*) docs) (index-tx {::xt/tx-time t1, ::xt/tx-id 1} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan1)) t1]] docs) (index-tx {::xt/tx-time t2, ::xt/tx-id 2} [[:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan2)) t1] [:crux.tx/put :ivan (c/->id-buffer (c/hash-doc ivan2))]] docs) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [etx-v1-t1 (c/->EntityTx (c/new-id :ivan) t1 t1 1 (c/hash-doc ivan1)) etx-v1-t2 (c/->EntityTx (c/new-id :ivan) t1 t2 2 (c/hash-doc ivan2)) etx-v2-t2 (c/->EntityTx (c/new-id :ivan) t2 t2 2 (c/hash-doc ivan2))] (letfn [(history-asc [opts] (vec (db/entity-history index-snapshot :ivan :asc opts))) (history-desc [opts] (vec (db/entity-history index-snapshot :ivan :desc opts)))] (t/testing "start is inclusive" (t/is (= [etx-v2-t2 etx-v1-t2] (history-desc {:start-tx {::xt/tx-id 2} :start-valid-time t2}))) (t/is (= [etx-v1-t2] (history-desc {:start-valid-time t1}))) (t/is (= [etx-v1-t2 etx-v2-t2] (history-asc {:start-tx {::xt/tx-id 2}}))) (t/is (= [etx-v1-t1 etx-v1-t2 etx-v2-t2] (history-asc {:start-tx {::xt/tx-id 1} :start-valid-time t1 :with-corrections? true})))) (t/testing "end is exclusive" (t/is (= [etx-v2-t2] (history-desc {:start-valid-time t2, :start-tx {::xt/tx-id 2} :end-valid-time t1, :end-tx {::xt/tx-id 1}}))) (t/is (= [] (history-desc {:end-valid-time t2}))) (t/is (= [etx-v1-t1] (history-asc {:end-tx {::xt/tx-id 2}}))) (t/is (= [] (history-asc {:start-valid-time t1, :end-tx {::xt/tx-id 1}}))))))))) (t/deftest test-put-delete-range-semantics (t/are [txs history] (let [eid (keyword (gensym "ivan")) ivan {:xt/id eid, :name "PI:NAME:<NAME>END_PI"} res (mapv (fn [[value & vts]] (xt/submit-tx *api* [(into (if value [::xt/put (assoc ivan :value value)] [::xt/delete eid]) vts)])) txs) last-tx (last res)] (xt/await-tx *api* last-tx nil) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (= (for [[vt tx-idx value] history] [vt (get-in res [tx-idx ::xt/tx-id]) (c/hash-doc (when value (assoc ivan :value value)))]) (->> (db/entity-history index-snapshot eid :asc {}) (map (juxt :vt :tx-id :content-hash))))))) ;; pairs ;; [[value vt ?end-vt] ...] ;; [[vt tx-idx value] ...] [[26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-26" 0 26] [#inst "2019-11-29" 0 nil]] ;; re-instates the previous value at the end of the range [[25 #inst "2019-11-25"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 26] [#inst "2019-11-29" 0 25]] ;; delete a range [[25 #inst "2019-11-25"] [nil #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 nil] [#inst "2019-11-29" 0 25]] ;; override a range [[25 #inst "2019-11-25" #inst "2019-11-27"] [nil #inst "2019-11-25" #inst "2019-11-27"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 1 nil] [#inst "2019-11-26" 2 26] [#inst "2019-11-27" 2 26] [#inst "2019-11-29" 0 nil]] ;; merge a range [[25 #inst "2019-11-25" #inst "2019-11-27"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 26] [#inst "2019-11-27" 1 26] [#inst "2019-11-29" 0 nil]] ;; shouldn't override the value at end-vt if there's one there [[25 #inst "2019-11-25"] [29 #inst "2019-11-29"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 2 26] [#inst "2019-11-29" 1 29]] ;; should re-instate 28 at the end of the range [[25 #inst "2019-11-25"] [28 #inst "2019-11-28"] [26 #inst "2019-11-26" #inst "2019-11-29"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 2 26] [#inst "2019-11-28" 2 26] [#inst "2019-11-29" 1 28]] ;; 26.1 should overwrite the full range [[28 #inst "2019-11-28"] [26 #inst "2019-11-26" #inst "2019-11-29"] [26.1 #inst "2019-11-26"]] [[#inst "2019-11-26" 2 26.1] [#inst "2019-11-28" 2 26.1] [#inst "2019-11-29" 0 28]] ;; 27 should override the latter half of the range [[25 #inst "2019-11-25"] [26 #inst "2019-11-26" #inst "2019-11-29"] [27 #inst "2019-11-27"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 1 26] [#inst "2019-11-27" 2 27] [#inst "2019-11-29" 0 25]] ;; 27 should still override the latter half of the range [[25 #inst "2019-11-25"] [28 #inst "2019-11-28"] [26 #inst "2019-11-26" #inst "2019-11-29"] [27 #inst "2019-11-27"]] [[#inst "2019-11-25" 0 25] [#inst "2019-11-26" 2 26] [#inst "2019-11-27" 3 27] [#inst "2019-11-28" 3 27] [#inst "2019-11-29" 1 28]])) ;; TODO: This test just shows that this is an issue, if we fix the ;; underlying issue this test should start failing. We can then change ;; the second assertion if we want to keep it around to ensure it ;; keeps working. (t/deftest test-corrections-in-the-past-slowes-down-bitemp-144 (let [ivan {:xt/id :ivan :name "PI:NAME:<NAME>END_PI"} start-valid-time #inst "2019" number-of-versions 1000 tx (fix/submit+await-tx (for [n (range number-of-versions)] [::xt/put (assoc ivan :version n) (Date. (+ (.getTime start-valid-time) (inc (long n))))]))] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [baseline-time (let [start-time (System/nanoTime) valid-time (Date. (+ (.getTime start-valid-time) number-of-versions))] (t/testing "last version of entity is visible at now" (t/is (= valid-time (:vt (db/entity-as-of index-snapshot :ivan valid-time (::xt/tx-id tx)))))) (- (System/nanoTime) start-time))] (let [start-time (System/nanoTime) valid-time (Date. (+ (.getTime start-valid-time) number-of-versions))] (t/testing "no version is visible before transactions" (t/is (nil? (db/entity-as-of index-snapshot :ivan valid-time -1))) (let [corrections-time (- (System/nanoTime) start-time)] ;; TODO: This can be a bit flaky. This assertion was ;; mainly there to prove the opposite, but it has been ;; fixed. Can be added back to sanity check when ;; changing indexes. #_(t/is (>= baseline-time corrections-time))))))))) (t/deftest test-can-read-kv-tx-log (let [ivan {:xt/id :ivan :name "PI:NAME:<NAME>END_PI"} tx1-ivan (assoc ivan :version 1) tx1-valid-time #inst "2018-11-26" {tx1-id ::xt/tx-id tx1-tx-time ::xt/tx-time} (fix/submit+await-tx [[::xt/put tx1-ivan tx1-valid-time]]) tx2-ivan (assoc ivan :version 2) tx2-petr {:xt/id :petr :name "PI:NAME:<NAME>END_PI"} tx2-valid-time #inst "2018-11-27" {tx2-id ::xt/tx-id tx2-tx-time ::xt/tx-time} (fix/submit+await-tx [[::xt/put tx2-ivan tx2-valid-time] [::xt/put tx2-petr tx2-valid-time]])] (with-open [log-iterator (db/open-tx-log (:tx-log *api*) nil)] (let [log (iterator-seq log-iterator)] (t/is (not (realized? log))) (t/is (= [{::xt/tx-id tx1-id ::xt/tx-time tx1-tx-time :xtdb.tx.event/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc tx1-ivan) tx1-valid-time]] ::xt/submit-tx-opts {}} {::xt/tx-id tx2-id ::xt/tx-time tx2-tx-time :xtdb.tx.event/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc tx2-ivan) tx2-valid-time] [:crux.tx/put (c/new-id :petr) (c/hash-doc tx2-petr) tx2-valid-time]] ::xt/submit-tx-opts {}}] log)))))) (t/deftest migrates-unhashed-tx-log-eids (let [doc {:crux.db/id :foo} doc-id (c/hash-doc doc)] (db/submit-docs (:document-store *api*) {doc-id doc}) (doto @(db/submit-tx (:tx-log *api*) [[:crux.tx/match :foo (c/new-id c/nil-id-buffer)] [:crux.tx/put :foo doc-id]]) (->> (xt/await-tx *api*))) (t/is (= {:xt/id :foo} (xt/entity (xt/db *api*) :foo))) (with-open [log-iterator (xt/open-tx-log *api* nil nil)] (let [evts (::xt/tx-events (first (iterator-seq log-iterator)))] ;; have to check not= too because Id's `equals` conforms its input to Id (t/is (not= [::xt/match :foo (c/new-id c/nil-id-buffer)] (first evts))) (t/is (not= [::xt/put :foo doc-id] (second evts))) (t/is (= [[::xt/match (c/new-id :foo) (c/new-id c/nil-id-buffer)] [::xt/put (c/new-id :foo) doc-id]] evts)))) (fix/submit+await-tx [[::xt/delete :foo]]) (t/is (nil? (xt/entity (xt/db *api*) :foo))))) (t/deftest test-can-apply-transaction-fn (with-redefs [tx/tx-fn-eval-cache (memoize eval)] (let [v1-ivan {:xt/id :ivan :name "PI:NAME:<NAME>END_PI" :age 40} v4-ivan (assoc v1-ivan :name "PI:NAME:<NAME>END_PI") update-attribute-fn {:xt/id :update-attribute-fn :xt/fn '(fn [ctx eid k f] [[::xt/put (update (xtdb.api/entity (xtdb.api/db ctx) eid) k (eval f))]])}] (fix/submit+await-tx [[::xt/put v1-ivan] [::xt/put update-attribute-fn]]) (t/is (= v1-ivan (xt/entity (xt/db *api*) :ivan))) (t/is (= update-attribute-fn (xt/entity (xt/db *api*) :update-attribute-fn))) (some-> (#'tx/reset-tx-fn-error) throw) (let [v2-ivan (assoc v1-ivan :age 41)] (fix/submit+await-tx [[::xt/fn :update-attribute-fn :ivan :age `inc]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v2-ivan (xt/entity (xt/db *api*) :ivan))) (t/testing "resulting documents are indexed" (t/is (= #{[41]} (xt/q (xt/db *api*) '[:find age :where [e :name "PI:NAME:<NAME>END_PI"] [e :age age]])))) (t/testing "exceptions" (t/testing "non existing tx fn" (let [tx (fix/submit+await-tx '[[::xt/fn :non-existing-fn]])] (t/is (= v2-ivan (xt/entity (xt/db *api*) :ivan))) (t/is (false? (xt/tx-committed? *api* tx))))) (t/testing "invalid arguments" (fix/submit+await-tx '[[::xt/fn :update-attribute-fn :ivan :age foo]]) (t/is (thrown? clojure.lang.Compiler$CompilerException (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "invalid results" (fix/submit+await-tx [[::xt/put {:xt/id :invalid-fn :xt/fn '(fn [ctx] [[::xt/foo]])}]]) (fix/submit+await-tx '[[::xt/fn :invalid-fn]]) (t/is (thrown-with-msg? IllegalArgumentException #"Invalid tx op" (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "no ::xt/fn" (fix/submit+await-tx [[::xt/put {:xt/id :no-fn}]]) (let [tx (fix/submit+await-tx '[[::xt/fn :no-fn]])] (t/is (false? (xt/tx-committed? *api* tx))))) (t/testing "not a fn" (fix/submit+await-tx [[::xt/put {:xt/id :not-a-fn :xt/fn 0}]]) (fix/submit+await-tx '[[::xt/fn :not-a-fn]]) (t/is (thrown? ClassCastException (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "compilation errors" (fix/submit+await-tx [[::xt/put {:xt/id :compilation-error-fn :xt/fn '(fn [ctx] unknown-symbol)}]]) (fix/submit+await-tx '[[::xt/fn :compilation-error-fn]]) (t/is (thrown-with-msg? Exception #"Syntax error compiling" (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "exception thrown" (fix/submit+await-tx [[::xt/put {:xt/id :exception-fn :xt/fn '(fn [ctx] (throw (RuntimeException. "foo")))}]]) (fix/submit+await-tx '[[::xt/fn :exception-fn]]) (t/is (thrown-with-msg? RuntimeException #"foo" (some-> (#'tx/reset-tx-fn-error) throw)))) (t/testing "still working after errors" (let [v3-ivan (assoc v1-ivan :age 40)] (fix/submit+await-tx [[::xt/fn :update-attribute-fn :ivan :age `dec]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v3-ivan (xt/entity (xt/db *api*) :ivan)))))) (t/testing "sees in-transaction version of entities (including itself)" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 1}]]) (let [tx (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 2}] [::xt/put {:xt/id :doubling-fn :xt/fn '(fn [ctx] [[::xt/put (-> (xtdb.api/entity (xtdb.api/db ctx) :foo) (update :foo * 2))]])}] [::xt/fn :doubling-fn]])] (t/is (xt/tx-committed? *api* tx)) (t/is (= {:xt/id :foo, :foo 4} (xt/entity (xt/db *api*) :foo))))) (t/testing "function ops can return other function ops" (let [returns-fn {:xt/id :returns-fn :xt/fn '(fn [ctx] [[::xt/fn :update-attribute-fn :ivan :name `string/upper-case]])}] (fix/submit+await-tx [[::xt/put returns-fn]]) (fix/submit+await-tx [[::xt/fn :returns-fn]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v4-ivan (xt/entity (xt/db *api*) :ivan))))) (t/testing "repeated 'merge' operation behaves correctly" (let [v5-ivan (merge v4-ivan {:height 180 :hair-style "short" :mass 60}) merge-fn {:xt/id :merge-fn :xt/fn `(fn [ctx# eid# m#] [[::xt/put (merge (xt/entity (xt/db ctx#) eid#) m#)]])}] (fix/submit+await-tx [[::xt/put merge-fn]]) (fix/submit+await-tx [[::xt/fn :merge-fn :ivan {:mass 60, :hair-style "short"}]]) (fix/submit+await-tx [[::xt/fn :merge-fn :ivan {:height 180}]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= v5-ivan (xt/entity (xt/db *api*) :ivan))))) (t/testing "function ops can return other function ops that also the forked ctx" (let [returns-fn {:xt/id :returns-fn :xt/fn '(fn [ctx] [[::xt/put {:xt/id :ivan :name "modified ivan"}] [::xt/fn :update-attribute-fn :ivan :name `string/upper-case]])}] (fix/submit+await-tx [[::xt/put returns-fn]]) (fix/submit+await-tx [[::xt/fn :returns-fn]]) (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= {:xt/id :ivan :name "MODIFIED IVAN"} (xt/entity (xt/db *api*) :ivan))))) (t/testing "can access current transaction on tx-fn context" (fix/submit+await-tx [[::xt/put {:xt/id :tx-metadata-fn :xt/fn `(fn [ctx#] [[::xt/put {:xt/id :tx-metadata ::xt/current-tx (xt/indexing-tx ctx#)}]])}]]) (let [submitted-tx (fix/submit+await-tx '[[::xt/fn :tx-metadata-fn]])] (some-> (#'tx/reset-tx-fn-error) throw) (t/is (= {:xt/id :tx-metadata ::xt/current-tx submitted-tx} (xt/entity (xt/db *api*) :tx-metadata))))))))) (t/deftest tx-fn-sees-in-tx-query-results (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 1}]]) (let [tx (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo 2}] [::xt/put {:xt/id :put :xt/fn '(fn [ctx doc] [[::xt/put doc]])}] [::xt/fn :put {:xt/id :bar, :ref :foo}] [::xt/put {:xt/id :doubling-fn :xt/fn '(fn [ctx] (let [db (xtdb.api/db ctx)] [[::xt/put {:xt/id :prn-out :e (xtdb.api/entity db :bar) :q (first (xtdb.api/q db {:find '[e v] :where '[[e :xt/id :bar] [e :ref v]]}))}] [::xt/put (-> (xtdb.api/entity db :foo) (update :foo * 2))]]))}] [::xt/fn :doubling-fn]])] (t/is (xt/tx-committed? *api* tx)) (t/is (= {:xt/id :foo, :foo 4} (xt/entity (xt/db *api*) :foo))) (t/is (= {:xt/id :prn-out :e {:xt/id :bar :ref :foo} :q [:bar :foo]} (xt/entity (xt/db *api*) :prn-out))))) (t/deftest tx-log-evict-454 [] (fix/submit+await-tx [[::xt/put {:xt/id :to-evict}]]) (fix/submit+await-tx [[::xt/cas {:xt/id :to-evict} {:xt/id :to-evict :test "test"}]]) (fix/submit+await-tx [[::xt/evict :to-evict]]) (with-open [log-iterator (xt/open-tx-log *api* nil true)] (t/is (= [[[::xt/put {:xt/id #xtdb/id "PI:KEY:<KEY>END_PIabePI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PI45bdcf6fbPI:KEY:<KEY>END_PI", ::xt/evicted? true}]] [[::xt/cas {:xt/id #xtdb/id "6abePI:KEY:<KEY>END_PI06510aaPI:KEY:<KEY>END_PI37371PI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PI224PI:KEY:<KEY>END_PIbdcf6fb0", ::xt/evicted? true} {:xt/id #xtdb/id "PI:KEY:<KEY>END_PIabePI:KEY:<KEY>END_PI06510aaPI:KEY:<KEY>END_PI3737167cPI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PI45bdcf6fb0", ::xt/evicted? true}]] [[::xt/evict #xtdb/id "PI:KEY:<KEY>END_PI"]]] (->> (iterator-seq log-iterator) (map ::xt/tx-ops)))))) (t/deftest transaction-fn-return-values-457 (with-redefs [tx/tx-fn-eval-cache (memoize eval)] (let [nil-fn {:xt/id :nil-fn :xt/fn '(fn [ctx] nil)} false-fn {:xt/id :false-fn :xt/fn '(fn [ctx] false)}] (fix/submit+await-tx [[::xt/put nil-fn] [::xt/put false-fn]]) (fix/submit+await-tx [[::xt/fn :nil-fn] [::xt/put {:xt/id :foo :foo? true}]]) (t/is (= {:xt/id :foo, :foo? true} (xt/entity (xt/db *api*) :foo))) (fix/submit+await-tx [[::xt/fn :false-fn] [::xt/put {:xt/id :bar :bar? true}]]) (t/is (nil? (xt/entity (xt/db *api*) :bar)))))) (t/deftest map-ordering-362 (t/testing "cas is independent of map ordering" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo :bar}]]) (fix/submit+await-tx [[::xt/cas {:foo :bar, :xt/id :foo} {:xt/id :foo, :foo :baz}]]) (t/is (= {:xt/id :foo, :foo :baz} (xt/entity (xt/db *api*) :foo)))) (t/testing "entities with map keys can be retrieved regardless of ordering" (let [doc {:xt/id {:foo 1, :bar 2}}] (fix/submit+await-tx [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db *api*) {:foo 1, :bar 2}))) (t/is (= doc (xt/entity (xt/db *api*) {:bar 2, :foo 1}))))) (t/testing "entities with map values can be joined regardless of ordering" (let [doc {:xt/id {:foo 2, :bar 4}}] (fix/submit+await-tx [[::xt/put doc] [::xt/put {:xt/id :baz, :joins {:bar 4, :foo 2}}] [::xt/put {:xt/id :quux, :joins {:foo 2, :bar 4}}]]) (t/is (= #{[{:foo 2, :bar 4} :baz] [{:foo 2, :bar 4} :quux]} (xt/q (xt/db *api*) '{:find [parent child] :where [[parent :xt/id _] [child :joins parent]]})))))) (t/deftest incomparable-colls-1001 (t/testing "can store and retrieve incomparable colls (#1001)" (let [foo {:xt/id :foo :foo {:bar #{7 "hello"}}}] (fix/submit+await-tx [[::xt/put foo]]) (t/is (= #{[foo]} (xt/q (xt/db *api*) '{:find [(pull ?e [*])] :where [[?e :foo {:bar #{"hello" 7}}]]})))) (let [foo {:xt/id :foo :foo {{:foo 1} :foo1 {:foo 2} :foo2}}] (fix/submit+await-tx [[::xt/put foo]]) (t/is (= #{[foo]} (xt/q (xt/db *api*) '{:find [(pull ?e [*])] :where [[?e :foo {{:foo 2} :foo2, {:foo 1} :foo1}]]})))))) (t/deftest test-java-ids-and-values-1398 (letfn [(test-id [id] (t/testing "As ID" (with-open [node (xt/start-node {})] (let [doc {:xt/id id}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) id))) (t/is #{[id]} (xt/q (xt/db node) '{:find [?id] :where [[?id :xt/id]]})))))) (test-value [value] (t/testing "As Value" (with-open [node (xt/start-node {})] (let [doc {:xt/id :foo :bar value}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) :foo))) (t/is #{[value]} (xt/q (xt/db node) '{:find [?val] :where [[?id :bar ?val]]}))))))] (t/testing "Keyword" (doto (Keyword/intern "foo") (test-id) (test-value))) (t/testing "String" (doto "foo" (test-id) (test-value))) (t/testing "Long" (doto 100 (test-id) (test-value))) (t/testing "UUID" (doto (UUID/randomUUID) (test-id) (test-value))) (t/testing "URI" (doto (URI/create "mailto:PI:EMAIL:<EMAIL>END_PI") (test-id) (test-value))) (t/testing "URL" (doto (URL. "https://github.com/xtdb/xtdb") (test-id) (test-value))) (t/testing "IPersistentMap" (doto (-> (PersistentArrayMap/EMPTY) (.assoc "foo" "bar")) (test-id) (test-value))) (t/testing "Set" (doto (HashSet.) (.add "foo") (.add "bar") (test-value))) (t/testing "Singleton Map" (doto (Collections/singletonMap "foo" "bar") (test-id) (test-value))) (t/testing "HashMap with single entry" (doto (HashMap.) (.put "foo" "bar") (test-id) (test-value))) (t/testing "HashMap with multiple entries" (doto (HashMap.) (.put "foo" "bar") (.put "baz" "waka") (test-id) (test-value))) (t/testing "HashMap with entries added in different order" (let [val1 (doto (HashMap.) (.put "foo" "bar") (.put "baz" "waka")) val2 (doto (HashMap.) (.put "baz" "waka") (.put "foo" "bar"))] (t/is (= val1 val2)) (t/testing "As ID" (with-open [node (xt/start-node {})] (let [doc {:xt/id val1}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) val2))) (let [result (xt/q (xt/db node) '{:find [?id] :where [[?id :xt/id]]})] (t/is #{[val1]} result) (t/is #{[val2]} result))))) (t/testing "As Value" (with-open [node (xt/start-node {})] (let [doc {:xt/id :foo :bar val1}] (fix/submit+await-tx node [[::xt/put doc]]) (t/is (= doc (xt/entity (xt/db node) :foo))) (let [result (xt/q (xt/db node) '{:find [?val] :where [[?id :bar ?val]]})] (t/is #{[val1]} result) (t/is #{[val2]} result))))))))) (t/deftest overlapping-valid-time-ranges-434 (let [_ (fix/submit+await-tx [[::xt/put {:xt/id :foo, :v 10} #inst "2019-01-01"] [::xt/put {:xt/id :foo, :v 10} #inst "2020-01-10"] [::xt/put {:xt/id :bar, :v 5} #inst "2020-01-05"] [::xt/put {:xt/id :bar, :v 10} #inst "2020-01-10"] [::xt/put {:xt/id :baz, :v 10} #inst "2020-01-10"]]) last-tx (fix/submit+await-tx [[::xt/put {:xt/id :foo, :v 10} #inst "2019-01-01"] [::xt/put {:xt/id :bar, :v 7} #inst "2020-01-07"] ;; mixing foo and bar shouldn't matter [::xt/put {:xt/id :foo, :v 8} #inst "2020-01-08" #inst "2020-01-12"] ; reverts to 10 afterwards [::xt/put {:xt/id :foo, :v 9} #inst "2020-01-09" #inst "2020-01-11"] ; reverts to 8 afterwards, then 10 [::xt/put {:xt/id :bar, :v 8} #inst "2020-01-08" #inst "2020-01-09"] ; reverts to 7 afterwards [::xt/put {:xt/id :bar, :v 11} #inst "2020-01-11" #inst "2020-01-12"] ; reverts to 10 afterwards ]) db (xt/db *api*)] (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (let [eid->history (fn [eid] (let [history (db/entity-history index-snapshot (c/new-id eid) :asc {:start-valid-time #inst "2020-01-01"}) docs (db/fetch-docs (:document-store *api*) (map :content-hash history))] (->> history (mapv (fn [{:keys [content-hash vt]}] [vt (:v (get docs content-hash))])))))] ;; transaction functions, asserts both still apply at the start of the transaction (t/is (= [[#inst "2020-01-08" 8] [#inst "2020-01-09" 9] [#inst "2020-01-10" 9] [#inst "2020-01-11" 8] [#inst "2020-01-12" 10]] (eid->history :foo))) (t/is (= [[#inst "2020-01-05" 5] [#inst "2020-01-07" 7] [#inst "2020-01-08" 8] [#inst "2020-01-09" 7] [#inst "2020-01-10" 10] [#inst "2020-01-11" 11] [#inst "2020-01-12" 10]] (eid->history :bar))))))) (t/deftest cas-docs-not-evicting-371 (fix/submit+await-tx [[::xt/put {:xt/id :foo, :foo :bar}] [::xt/put {:xt/id :frob :foo :bar}]]) (fix/submit+await-tx [[::xt/cas {:xt/id :foo, :foo :baz} {:xt/id :foo, :foo :quux}] [::xt/put {:xt/id :frob :foo :baz}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (let [docs (db/fetch-docs (:document-store *api*) #{(c/hash-doc {:xt/id :foo, :foo :bar}) (c/hash-doc {:xt/id :foo, :foo :baz}) (c/hash-doc {:xt/id :foo, :foo :quux})})] (t/is (= 3 (count docs))) (t/is (every? (comp c/evicted-doc? val) docs))) (t/testing "even though the CaS was unrelated, the whole transaction fails - we should still evict those docs" (fix/submit+await-tx [[::xt/evict :frob]]) (let [docs (db/fetch-docs (:document-store *api*) #{(c/hash-doc {:xt/id :frob, :foo :bar}) (c/hash-doc {:xt/id :frob, :foo :baz})})] (t/is (= 2 (count docs))) (t/is (every? (comp c/evicted-doc? val) docs))))) (t/deftest raises-tx-events-422 (let [!events (atom []) !latch (promise)] (bus/listen (:bus *api*) {::xt/event-types #{::tx/indexing-tx ::tx/indexed-tx}} (fn [evt] (swap! !events conj evt) (when (= ::tx/indexed-tx (::xt/event-type evt)) (deliver !latch @!events)))) (let [doc-1 {:xt/id :foo, :value 1} doc-2 {:xt/id :bar, :value 2} doc-ids #{(c/hash-doc doc-1) (c/hash-doc doc-2)} submitted-tx (fix/submit+await-tx [[::xt/put doc-1] [::xt/put doc-2]])] (when (= ::timeout (deref !latch 500 ::timeout)) (t/is false)) (t/is (= [{::xt/event-type ::tx/indexing-tx, :submitted-tx submitted-tx} {::xt/event-type ::tx/indexed-tx, :submitted-tx submitted-tx, :committed? true :doc-ids doc-ids :av-count 4 ::txe/tx-events [[:crux.tx/put #xtdb/id "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33" #xtdb/id "974e28e6484fb6c66e5ca6444ec616207800d815"] [:crux.tx/put #xtdb/id "62cdb7020ff920e5aa642c3d4066950dd1f01f4d" #xtdb/id "f2cb628efd5123743c30137b08282b9dee82104a"]]}] (-> (vec @!events) (update 1 dissoc :bytes-indexed))))))) (t/deftest await-fails-quickly-738 (with-redefs [tx/index-tx-event (fn [_ _ _] (Thread/sleep 100) (throw (ex-info "test error for await-fails-quickly-738" {})))] (let [last-tx (xt/submit-tx *api* [[::xt/put {:xt/id :foo}]])] (t/testing "Testing fail while we are awaiting an event" (t/is (thrown-with-msg? Exception #"Transaction ingester aborted" (xt/await-tx *api* last-tx (Duration/ofMillis 1000))))) (t/testing "Testing fail before we await an event" (t/is (thrown-with-msg? Exception #"Transaction ingester aborted" (xt/await-tx *api* last-tx (Duration/ofMillis 1000)))))))) (t/deftest test-evict-documents-with-common-attributes (fix/submit+await-tx [[::xt/put {:xt/id :foo, :count 1}] [::xt/put {:xt/id :bar, :count 1}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (t/is (= #{[:bar]} (xt/q (xt/db *api*) '{:find [?e] :where [[?e :count 1]]})))) (t/deftest replaces-tx-fn-arg-docs (fix/submit+await-tx [[::xt/put {:xt/id :put-ivan :xt/fn '(fn [ctx doc] [[::xt/put (assoc doc :xt/id :ivan)]])}]]) (t/testing "replaces args doc with resulting ops" (fix/submit+await-tx [[::xt/fn :put-ivan {:name "PI:NAME:<NAME>END_PI"}]]) (t/is (= {:xt/id :ivan, :name "PI:NAME:<NAME>END_PI"} (xt/entity (xt/db *api*) :ivan))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) last ::txe/tx-events first last))] (t/is (= {:crux.db.fn/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc {:xt/id :ivan, :name "PI:NAME:<NAME>END_PI"})]]} (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt) (dissoc :xt/id)))))) (t/testing "replaces fn with no args" (fix/submit+await-tx [[::xt/put {:xt/id :no-args :xt/fn '(fn [ctx] [[::xt/put {:xt/id :no-fn-args-doc}]])}]]) (fix/submit+await-tx [[::xt/fn :no-args]]) (t/is (= {:xt/id :no-fn-args-doc} (xt/entity (xt/db *api*) :no-fn-args-doc))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) last ::txe/tx-events first last))] (t/is (= {:crux.db.fn/tx-events [[:crux.tx/put (c/new-id :no-fn-args-doc) (c/hash-doc {:xt/id :no-fn-args-doc})]]} (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt) (dissoc :xt/id)))))) (t/testing "nested tx-fn" (fix/submit+await-tx [[::xt/put {:xt/id :put-bob-and-ivan :xt/fn '(fn [ctx bob ivan] [[::xt/put (assoc bob :xt/id :bob)] [::xt/fn :put-ivan ivan]])}]]) (fix/submit+await-tx [[::xt/fn :put-bob-and-ivan {:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}]]) (t/is (= {:xt/id :ivan, :name "PI:NAME:<NAME>END_PI"} (xt/entity (xt/db *api*) :ivan))) (t/is (= {:xt/id :bob, :name "PI:NAME:<NAME>END_PI"} (xt/entity (xt/db *api*) :bob))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) 1)] (-> (iterator-seq tx-log) last ::txe/tx-events first last)) arg-doc (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt)) sub-arg-doc-id (-> arg-doc :crux.db.fn/tx-events second last) sub-arg-doc (-> (db/fetch-docs (:document-store *api*) #{sub-arg-doc-id}) (get sub-arg-doc-id) (c/crux->xt))] (t/is (= {:xt/id (:xt/id arg-doc) :crux.db.fn/tx-events [[:crux.tx/put (c/new-id :bob) (c/hash-doc {:xt/id :bob, :name "PI:NAME:<NAME>END_PI"})] [:crux.tx/fn (c/new-id :put-ivan) sub-arg-doc-id]]} arg-doc)) (t/is (= {:xt/id (:xt/id sub-arg-doc) :crux.db.fn/tx-events [[:crux.tx/put (c/new-id :ivan) (c/hash-doc {:xt/id :ivan :name "PI:NAME:<NAME>END_PI"})]]} sub-arg-doc)))) (t/testing "copes with args doc having been replaced" (let [sergei {:xt/id :sergei :name "PI:NAME:<NAME>END_PI"} arg-doc {:xt/id :args :crux.db.fn/tx-events [[:crux.tx/put :sergei (c/hash-doc sergei)]]}] (db/submit-docs (:document-store *api*) {(c/hash-doc arg-doc) arg-doc (c/hash-doc sergei) sergei}) (let [tx @(db/submit-tx (:tx-log *api*) [[:crux.tx/fn :put-sergei (c/hash-doc arg-doc)]])] (xt/await-tx *api* tx) (t/is (= sergei (xt/entity (xt/db *api*) :sergei)))))) (t/testing "failed tx-fn" (fix/submit+await-tx [[::xt/fn :put-petr {:name "PI:NAME:<NAME>END_PI"}]]) (t/is (nil? (xt/entity (xt/db *api*) :petr))) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) last ::txe/tx-events first last))] (t/is (true? (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) :crux.db.fn/failed?)))))) (t/deftest handles-legacy-tx-fns-with-no-args-doc ;; we used to not submit args docs if the tx-fn was 0-arg, and hence had nothing to replace ;; we don't want the fix to assume that all tx-fns on the tx-log have an arg-doc (let [tx-fn (-> {:xt/id :tx-fn, :xt/fn '(fn [ctx] [[::xt/put {:xt/id :ivan}]])} (c/xt->crux)) docs {(c/hash-doc tx-fn) tx-fn}] (db/submit-docs (:document-store *api*) docs) (index-tx {::xt/tx-time (Date.), ::xt/tx-id 0} [[:crux.tx/put (c/new-id :tx-fn) tx-fn]] docs) (index-tx {::xt/tx-time (Date.), ::xt/tx-id 1} [[:crux.tx/fn :tx-fn]] docs) (t/is (= {:xt/id :ivan} (xt/entity (xt/db *api*) :ivan))))) (t/deftest test-tx-fn-doc-race-1049 (let [put-fn {:xt/id :put-fn :xt/fn '(fn [ctx doc] [[::xt/put doc]])} foo-doc {:crux.db/id :foo} !arg-doc-resps (atom [{:crux.db.fn/args [foo-doc]} {:crux.db.fn/tx-events [[:crux.tx/put (c/new-id :foo) (c/hash-doc foo-doc)]]}]) ->mocked-doc-store (fn [_opts] (reify db/DocumentStore (submit-docs [_ docs]) (fetch-docs [_ ids] (->> ids (into {} (map (juxt identity (some-fn {(c/hash-doc put-fn) (c/xt->crux put-fn) (c/hash-doc foo-doc) foo-doc} (fn [id] (let [[[doc] _] (swap-vals! !arg-doc-resps rest)] (merge doc {:crux.db/id id})))))))))))] (with-open [node (xt/start-node {:xtdb/document-store ->mocked-doc-store})] (xt/submit-tx node [[::xt/put put-fn]]) (xt/submit-tx node [[::xt/fn :put-fn foo-doc]]) (xt/sync node) (t/is (= #{[:put-fn] [:foo]} (xt/q (xt/db node) '{:find [?e] :where [[?e :xt/id]]})))))) (t/deftest ensure-tx-fn-arg-docs-replaced-even-when-tx-aborts-960 (fix/submit+await-tx [[::xt/put {:xt/id :foo :xt/fn '(fn [ctx arg] [])}] [::xt/match :foo {:xt/id :foo}] [::xt/fn :foo :foo-arg]]) (let [arg-doc-id (with-open [tx-log (db/open-tx-log (:tx-log *api*) nil)] (-> (iterator-seq tx-log) first :xtdb.tx.event/tx-events last last)) arg-doc (-> (db/fetch-docs (:document-store *api*) #{arg-doc-id}) (get arg-doc-id) (c/crux->xt))] (t/is (= {:crux.db.fn/failed? true} (dissoc arg-doc :xt/id))) (t/is (uuid? (:xt/id arg-doc))))) (t/deftest test-documents-with-int-short-byte-float-eids-1043 (fix/submit+await-tx [[::xt/put {:xt/id (int 10), :name "foo"}] [::xt/put {:xt/id (short 12), :name "bar"}] [::xt/put {:xt/id (byte 16), :name "baz"}] [::xt/put {:xt/id (float 1.1), :name "quux"}]]) (let [db (xt/db *api*)] (t/is (= #{["foo"] ["bar"] ["baz"] ["quux"]} (xt/q (xt/db *api*) '{:find [?name] :where [[?e :name ?name]]}))) (t/is (= {:xt/id (long 10), :name "foo"} (xt/entity db (int 10)))) (t/is (= {:xt/id (long 10), :name "foo"} (xt/entity db (long 10)))) (t/is (= #{[10 "foo"]} (xt/q (xt/db *api*) {:find '[?e ?name] :where '[[?e :name ?name]] :args [{:?e (int 10)}]})))) (t/testing "10 as int and long are the same key" (fix/submit+await-tx [[::xt/put {:xt/id 10, :name "foo2"}]]) (t/is (= #{[10 "foo2"]} (xt/q (xt/db *api*) {:find '[?e ?name] :where '[[?e :name ?name]] :args [{:?e (int 10)}]}))))) (t/deftest test-put-evict-in-same-transaction-1337 (t/testing "put then evict" (fix/submit+await-tx [[::xt/put {:xt/id :test1/a, :test1? true}]]) (fix/submit+await-tx [[::xt/put {:xt/id :test1/b, :test1? true, :test1/evicted? true}] [::xt/evict :test1/b]]) (let [db (xt/db *api*)] (t/is (= {:xt/id :test1/a, :test1? true} (xt/entity db :test1/a))) (t/is (nil? (xt/entity db :test1/b))) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :test1/evicted? nil))) (t/is (empty? (db/entity-history index-snapshot :test1/b :asc {})))) (t/is (= #{[:test1/a]} (xt/q db '{:find [?e], :where [[?e :test1? true]]}))) (t/is (= #{} (xt/q db '{:find [?e], :where [[?e :test1/evicted? true]]}))))) (t/testing "put then evict an earlier entity" (fix/submit+await-tx [[::xt/put {:xt/id :test2/a, :test2? true, :test2/evicted? true}]]) (fix/submit+await-tx [[::xt/put {:xt/id :test2/b, :test2? true}] [::xt/evict :test2/a]]) (let [db (xt/db *api*)] (t/is (nil? (xt/entity db :test2/a))) (t/is (= {:xt/id :test2/b, :test2? true} (xt/entity db :test2/b))) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :test2/evicted? nil))) (t/is (empty? (db/entity-history index-snapshot :test2/a :asc {})))) (t/is (= #{[:test2/b]} (xt/q db '{:find [?e], :where [[?e :test2? true]]}))) (t/is (= #{} (xt/q db '{:find [?e], :where [[?e :test2/evicted? true]]}))))) (t/testing "evict then put" (fix/submit+await-tx [[::xt/put {:xt/id :test3/a, :test3? true}]]) (fix/submit+await-tx [[::xt/evict :test3/a] [::xt/put {:xt/id :test3/b, :test3? true}]]) (let [db (xt/db *api*)] (t/is (nil? (xt/entity db :test3/a))) (t/is (= {:xt/id :test3/b, :test3? true} (xt/entity db :test3/b))) (t/is (= #{[:test3/b]} (xt/q db '{:find [?e], :where [[?e :test3? true]]}))))) ;; TODO fails, see #1337 #_ (t/testing "evict then re-put" (fix/submit+await-tx [[::xt/put {:xt/id :test4, :test4? true}]]) (fix/submit+await-tx [[::xt/evict :test4] [::xt/put {:xt/id :test4, :test4? true}]]) (let [db (xt/db *api*)] (t/is (= {:xt/id :test4, :test4? true} (xt/entity db :test4))) (t/is (= #{[:test4]} (xt/q db '{:find [?e], :where [[?e :test4? true]]})))))) (t/deftest test-avs-only-shared-by-evicted-entities-1338 (t/testing "only one entity, AV removed" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :evict-me? true}]]) (fix/submit+await-tx [[::xt/evict :foo]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :evict-me? nil))))) ;; TODO fails, see #1338 #_ (t/testing "shared by multiple evicted entities" (fix/submit+await-tx [[::xt/put {:xt/id :foo, :evict-me? true}] [::xt/put {:xt/id :bar, :evict-me? true}]]) (fix/submit+await-tx [[::xt/evict :foo] [::xt/evict :bar]]) (with-open [index-snapshot (db/open-index-snapshot (:index-store *api*))] (t/is (empty? (db/av index-snapshot :evict-me? nil)))))) (t/deftest node-shutdown-interrupts-tx-ingestion (let [op-count 10 !calls (atom 0) node (xt/start-node {})] (with-redefs [tx/index-tx-event (let [f tx/index-tx-event] (fn [& args] (let [target-time (+ (System/currentTimeMillis) 200)] (while (< (System/currentTimeMillis) target-time))) (swap! !calls inc) (apply f args)))] @(try (let [tx (xt/submit-tx node (repeat op-count [::xt/put {:xt/id :foo}])) await-fut (future (t/is (thrown? InterruptedException (xt/await-tx node tx))))] (Thread/sleep 100) ; to ensure the await starts before the node closes await-fut) (finally (.close node)))) (t/is (instance? InterruptedException (db/ingester-error (:tx-ingester node)))) (t/is (< @!calls op-count)))) (t/deftest empty-tx-can-be-awaited-1519 (let [tx (xt/submit-tx *api* []) _ (xt/await-tx *api* tx (Duration/ofSeconds 1))] (t/is (= (select-keys tx [::xt/tx-id]) (xt/latest-submitted-tx *api*))) (t/is (= tx (xt/latest-completed-tx *api*))) (t/is (xt/tx-committed? *api* tx)))) (t/deftest handles-secondary-indices (letfn [(with-persistent-golden-stores [node-config db-dir] (-> node-config (assoc :xtdb/tx-log {:kv-store {:xtdb/module 'xtdb.rocksdb/->kv-store :db-dir (io/file db-dir "txs")}} :xtdb/document-store {:kv-store {:xtdb/module 'xtdb.rocksdb/->kv-store :db-dir (io/file db-dir "docs")}}))) (with-persistent-indices [node-config idx-dir] (-> node-config (assoc :xtdb/index-store {:kv-store {:xtdb/module 'xtdb.rocksdb/->kv-store :db-dir idx-dir}}))) (with-secondary-index ([node-config after-tx-id opts process-tx-f] (-> node-config (assoc ::index2 (-> (fn [{:keys [secondary-indices]}] (tx/register-index! secondary-indices after-tx-id opts process-tx-f) nil) (with-meta {::sys/deps {:secondary-indices :xtdb/secondary-indices} ::sys/before #{[:xtdb/tx-ingester]}}))))))] (t/testing "indexes into secondary indices" (let [!txs (atom [])] (with-open [node (xt/start-node (-> {} (with-secondary-index nil {} (fn [tx] (swap! !txs conj tx)))))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]]) (t/is (= [0] (map ::xt/tx-id @!txs)))))) (t/testing "secondary indices catch up to XTDB indices on node startup" (fix/with-tmp-dirs #{db-dir idx-dir} (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir)))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]])) (let [!txs (atom [])] (with-open [_node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir) (with-secondary-index nil {} (fn [tx] (swap! !txs conj tx)))))] ;; NOTE: don't need `sync` - should happen before node becomes available. (t/is (= [0] (map ::xt/tx-id @!txs))))))) (t/testing "XTDB catches up without replaying tx to secondary indices" (fix/with-tmp-dirs #{db-dir} (let [!txs (atom [])] (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-secondary-index nil {} (fn [tx] (swap! !txs conj tx)))))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]])) (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-secondary-index 0 {} (fn [tx] (swap! !txs conj tx)))))] (xt/sync node) (t/is (= 0 (::xt/tx-id (xt/latest-completed-tx node)))) (t/is (= [0] (map ::xt/tx-id @!txs))))))) (t/testing "passes through tx-ops on request" (fix/with-tmp-dirs #{db-dir idx-dir} (let [!txs (atom [])] (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir) (with-secondary-index nil {:with-tx-ops? true} (fn [tx] (swap! !txs conj tx)))))] (fix/submit+await-tx node [[::xt/put {:xt/id :ivan :name "PI:NAME:<NAME>END_PI"}]]) (t/is (= [{::xt/tx-id 0 ::xt/tx-ops [[::xt/put {:xt/id :ivan, :name "PI:NAME:<NAME>END_PI"}]]}] (->> @!txs (map #(select-keys % [::xt/tx-id ::xt/tx-ops]))))))))) (with-redefs [log-impl/enabled? (constantly false)] (t/testing "handles secondary indexes blowing up" (with-open [node (xt/start-node (-> {} (with-secondary-index nil {} (fn [_tx] (throw (ex-info "boom!" {}))))))] (t/is (thrown-with-msg? ExceptionInfo #"boom!" (try (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]]) (catch Exception e (throw (.getCause e)))))) (t/is (nil? (xt/latest-completed-tx node))))) (t/testing "handles secondary indexes blowing up on startup" (fix/with-tmp-dirs #{db-dir idx-dir} (with-open [node (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir)))] (fix/submit+await-tx node [[::xt/put {:xt/id :foo}]])) (t/is (thrown-with-msg? ExceptionInfo #"boom!" (try (xt/start-node (-> {} (with-persistent-golden-stores db-dir) (with-persistent-indices idx-dir) (with-secondary-index nil {} (fn [_tx] (throw (ex-info "boom!" {})))))) (catch Exception e (throw (.getCause e))))))))))) (t/deftest tx-committed-throws-correctly-1579 (let [tx (fix/submit+await-tx [[::xt/put {:xt/id :foo}]])] (t/is (xt/tx-committed? *api* tx)) (t/is (xt/tx-committed? *api* {::xt/tx-id 0})) (t/is (thrown? xtdb.IllegalArgumentException (xt/tx-committed? *api* nil))) (t/is (thrown? xtdb.IllegalArgumentException (xt/tx-committed? *api* {}))) (t/is (thrown? xtdb.IllegalArgumentException (xt/tx-committed? *api* {::xt/tx-id nil}))) (t/is (thrown? ClassCastException (xt/tx-committed? *api* {::xt/tx-id :a}))) ;; "skipped" tx-ids (e.g. handling Kafka offsets), and negative or non-integer tx-ids are also incorrect but not currently detected #_ (t/is (thrown? xtdb.api.NodeOutOfSyncException (xt/tx-committed? *api* {::xt/tx-id -1.5}))))) (t/deftest can-query-documents-with-url-id-1638 ;; TODO: the (XT) hash of the URL depends on the serialized form of the URL object, ;; which in turn depends on its cached hashCode field. couple of fun things here: ;; - if nothing has yet computed the hashCode, it serializes `-1` ;; - the hashCode computation depends on the resolved IP address of the domain name (non-deterministic) ;; we (arguably incorrectly) expect the serialized form to be deterministic ;; we could consider re-implementing c/value->buffer for URL, but this would have backwards compatibility implications #_ ; (let [url (URL. "https://xtdb.com") doc {:xt/id url}] (fix/submit+await-tx [[::xt/put doc]]) (let [db (xt/db *api*)] (t/is (= doc (xt/entity db url))) (t/is (= #{[url]} (xt/q db '{:find [id] :where [[id :xt/id]]})))))) (t/deftest match-failure-of-a-put-shouldnt-affect-subsequent-indexing-1683 (fix/submit+await-tx [[::xt/match :bar {:xt/id :bar}] [::xt/put {:xt/id :foo}]]) (let [db (xt/db *api*)] (t/is (nil? (xt/entity db :foo)))) (fix/submit+await-tx [[::xt/put {:xt/id :foo}]]) (let [db (xt/db *api*)] (t/is (= {:xt/id :foo} (xt/entity db :foo))) (t/is (= #{[:foo]} (xt/q db '{:find [e], :where [[e :xt/id]]})))))
[ { "context": "alias)]\n {:filename path\n :password password\n :alias key-name}))))\n\n(defn- check-sa", "end": 4503, "score": 0.9988777041435242, "start": 4495, "tag": "PASSWORD", "value": "password" } ]
c#-metabase/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj
hanakhry/Crime_Admin
0
(ns metabase-enterprise.sso.integrations.saml "Implementation of the SAML backend for SSO. The basic flow of of a SAML login is: 1. User attempts to access some `url` but is not authenticated 2. User is redirected to `GET /auth/sso` 3. Metabase issues another redirect to the identity provider URI 4. User logs into their identity provider (i.e. Auth0) 5. Identity provider POSTs to Metabase with successful auth info 6. Metabase parses/validates the SAML response 7. Metabase inits the user session, responds with a redirect to back to the original `url`" (:require [buddy.core.codecs :as codecs] [clojure.string :as str] [clojure.tools.logging :as log] [medley.core :as m] [metabase-enterprise.sso.api.sso :as sso] [metabase-enterprise.sso.integrations.sso-settings :as sso-settings] [metabase-enterprise.sso.integrations.sso-utils :as sso-utils] [metabase.api.common :as api] [metabase.api.session :as session] [metabase.integrations.common :as integrations.common] [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 :refer [trs tru]] [ring.util.codec :as codec] [ring.util.response :as resp] [saml20-clj.core :as saml] [schema.core :as s]) (:import java.util.UUID)) (defn- group-names->ids "Translate a user's group names to a set of MB group IDs using the configured mappings" [group-names] (->> (cond-> group-names (string? group-names) vector) (map keyword) (mapcat (sso-settings/saml-group-mappings)) set)) (defn- all-mapped-group-ids "Returns the set of all MB group IDs that have configured mappings" [] (-> (sso-settings/saml-group-mappings) vals flatten set)) (defn- sync-groups! "Sync a user's groups based on mappings configured in the SAML settings" [user group-names] (when (sso-settings/saml-group-sync) (when group-names (integrations.common/sync-group-memberships! user (group-names->ids group-names) (all-mapped-group-ids) false)))) (s/defn ^:private fetch-or-create-user! :- (s/maybe {:id UUID, s/Keyword s/Any}) "Returns a Session for the given `email`. Will create the user if needed." [{:keys [first-name last-name email group-names user-attributes device-info]}] (when-not (sso-settings/saml-configured?) (throw (IllegalArgumentException. (tru "Can't create new SAML user when SAML is not configured")))) (when-not email (throw (ex-info (str (tru "Invalid SAML configuration: could not find user email.") " " (tru "We tried looking for {0}, but couldn't find the attribute." (sso-settings/saml-attribute-email)) " " (tru "Please make sure your SAML IdP is properly configured.")) {:status-code 400, :user-attributes (keys user-attributes)}))) (when-let [user (or (sso-utils/fetch-and-update-login-attributes! email user-attributes) (sso-utils/create-new-sso-user! {:first_name first-name :last_name last-name :email email :sso_source "saml" :login_attributes user-attributes}))] (sync-groups! user group-names) (session/create-session! :sso user device-info))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; SAML route supporting functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- acs-url [] (str (public-settings/site-url) "/auth/sso")) (defn- sp-cert-keystore-details [] (when-let [path (sso-settings/saml-keystore-path)] (when-let [password (sso-settings/saml-keystore-password)] (when-let [key-name (sso-settings/saml-keystore-alias)] {:filename path :password password :alias key-name})))) (defn- check-saml-enabled [] (api/check (sso-settings/saml-configured?) [400 (tru "SAML has not been enabled and/or configured")])) (defmethod sso/sso-get :saml ;; Initial call that will result in a redirect to the IDP along with information about how the IDP can authenticate ;; and redirect them back to us [req] (check-saml-enabled) (try (let [redirect-url (or (get-in req [:params :redirect]) (log/warn (trs "Warning: expected `redirect` param, but none is present")) (public-settings/site-url)) idp-url (sso-settings/saml-identity-provider-uri) saml-request (saml/request {:request-id (str "id-" (java.util.UUID/randomUUID)) :sp-name (sso-settings/saml-application-name) :issuer (sso-settings/saml-application-name) :acs-url (acs-url) :idp-url idp-url :credential (sp-cert-keystore-details)}) relay-state (saml/str->base64 redirect-url)] (saml/idp-redirect-response saml-request idp-url relay-state)) (catch Throwable e (let [msg (trs "Error generating SAML request")] (log/error e msg) (throw (ex-info msg {:status-code 500} e)))))) (defn- validate-response [response] (let [idp-cert (or (sso-settings/saml-identity-provider-certificate) (throw (ex-info (str (tru "Unable to log in: SAML IdP certificate is not set.")) {:status-code 500})))] (try (saml/validate response idp-cert (sp-cert-keystore-details) {:acs-url (acs-url) :issuer (sso-settings/saml-identity-provider-issuer)}) (catch Throwable e (log/error e (trs "SAML response validation failed")) (throw (ex-info (tru "Unable to log in: SAML response validation failed") {:status-code 401} e)))))) (defn- xml-string->saml-response [xml-string] (validate-response (saml/->Response xml-string))) (defn- unwrap-user-attributes "For some reason all of the user attributes coming back from the saml library are wrapped in a list, instead of 'Ryan', it's ('Ryan'). This function discards the list if there's just a single item in it." [m] (m/map-vals (fn [maybe-coll] (if (and (coll? maybe-coll) (= 1 (count maybe-coll))) (first maybe-coll) maybe-coll)) m)) (defn- saml-response->attributes [saml-response] (let [assertions (saml/assertions saml-response) attrs (-> assertions first :attrs unwrap-user-attributes)] (when-not attrs (throw (ex-info (str (tru "Unable to log in: SAML info does not contain user attributes.")) {:status-code 401}))) attrs)) (defn- base64-decode [s] (when (u/base64-string? s) (codecs/bytes->str (codec/base64-decode s)))) (defmethod sso/sso-post :saml ;; Does the verification of the IDP's response and 'logs the user in'. The attributes are available in the response: ;; `(get-in saml-info [:assertions :attrs]) [{:keys [params], :as request}] (check-saml-enabled) (let [continue-url (u/ignore-exceptions (when-let [s (some-> (:RelayState params) base64-decode)] (when-not (str/blank? s) s))) xml-string (base64-decode (:SAMLResponse params)) saml-response (xml-string->saml-response xml-string) attrs (saml-response->attributes saml-response) email (get attrs (sso-settings/saml-attribute-email)) first-name (get attrs (sso-settings/saml-attribute-firstname) "Unknown") last-name (get attrs (sso-settings/saml-attribute-lastname) "Unknown") groups (get attrs (sso-settings/saml-attribute-group)) session (fetch-or-create-user! {:first-name first-name :last-name last-name :email email :group-names groups :user-attributes attrs :device-info (request.u/device-info request)}) response (resp/redirect (or continue-url (public-settings/site-url)))] (mw.session/set-session-cookie request response session)))
24352
(ns metabase-enterprise.sso.integrations.saml "Implementation of the SAML backend for SSO. The basic flow of of a SAML login is: 1. User attempts to access some `url` but is not authenticated 2. User is redirected to `GET /auth/sso` 3. Metabase issues another redirect to the identity provider URI 4. User logs into their identity provider (i.e. Auth0) 5. Identity provider POSTs to Metabase with successful auth info 6. Metabase parses/validates the SAML response 7. Metabase inits the user session, responds with a redirect to back to the original `url`" (:require [buddy.core.codecs :as codecs] [clojure.string :as str] [clojure.tools.logging :as log] [medley.core :as m] [metabase-enterprise.sso.api.sso :as sso] [metabase-enterprise.sso.integrations.sso-settings :as sso-settings] [metabase-enterprise.sso.integrations.sso-utils :as sso-utils] [metabase.api.common :as api] [metabase.api.session :as session] [metabase.integrations.common :as integrations.common] [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 :refer [trs tru]] [ring.util.codec :as codec] [ring.util.response :as resp] [saml20-clj.core :as saml] [schema.core :as s]) (:import java.util.UUID)) (defn- group-names->ids "Translate a user's group names to a set of MB group IDs using the configured mappings" [group-names] (->> (cond-> group-names (string? group-names) vector) (map keyword) (mapcat (sso-settings/saml-group-mappings)) set)) (defn- all-mapped-group-ids "Returns the set of all MB group IDs that have configured mappings" [] (-> (sso-settings/saml-group-mappings) vals flatten set)) (defn- sync-groups! "Sync a user's groups based on mappings configured in the SAML settings" [user group-names] (when (sso-settings/saml-group-sync) (when group-names (integrations.common/sync-group-memberships! user (group-names->ids group-names) (all-mapped-group-ids) false)))) (s/defn ^:private fetch-or-create-user! :- (s/maybe {:id UUID, s/Keyword s/Any}) "Returns a Session for the given `email`. Will create the user if needed." [{:keys [first-name last-name email group-names user-attributes device-info]}] (when-not (sso-settings/saml-configured?) (throw (IllegalArgumentException. (tru "Can't create new SAML user when SAML is not configured")))) (when-not email (throw (ex-info (str (tru "Invalid SAML configuration: could not find user email.") " " (tru "We tried looking for {0}, but couldn't find the attribute." (sso-settings/saml-attribute-email)) " " (tru "Please make sure your SAML IdP is properly configured.")) {:status-code 400, :user-attributes (keys user-attributes)}))) (when-let [user (or (sso-utils/fetch-and-update-login-attributes! email user-attributes) (sso-utils/create-new-sso-user! {:first_name first-name :last_name last-name :email email :sso_source "saml" :login_attributes user-attributes}))] (sync-groups! user group-names) (session/create-session! :sso user device-info))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; SAML route supporting functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- acs-url [] (str (public-settings/site-url) "/auth/sso")) (defn- sp-cert-keystore-details [] (when-let [path (sso-settings/saml-keystore-path)] (when-let [password (sso-settings/saml-keystore-password)] (when-let [key-name (sso-settings/saml-keystore-alias)] {:filename path :password <PASSWORD> :alias key-name})))) (defn- check-saml-enabled [] (api/check (sso-settings/saml-configured?) [400 (tru "SAML has not been enabled and/or configured")])) (defmethod sso/sso-get :saml ;; Initial call that will result in a redirect to the IDP along with information about how the IDP can authenticate ;; and redirect them back to us [req] (check-saml-enabled) (try (let [redirect-url (or (get-in req [:params :redirect]) (log/warn (trs "Warning: expected `redirect` param, but none is present")) (public-settings/site-url)) idp-url (sso-settings/saml-identity-provider-uri) saml-request (saml/request {:request-id (str "id-" (java.util.UUID/randomUUID)) :sp-name (sso-settings/saml-application-name) :issuer (sso-settings/saml-application-name) :acs-url (acs-url) :idp-url idp-url :credential (sp-cert-keystore-details)}) relay-state (saml/str->base64 redirect-url)] (saml/idp-redirect-response saml-request idp-url relay-state)) (catch Throwable e (let [msg (trs "Error generating SAML request")] (log/error e msg) (throw (ex-info msg {:status-code 500} e)))))) (defn- validate-response [response] (let [idp-cert (or (sso-settings/saml-identity-provider-certificate) (throw (ex-info (str (tru "Unable to log in: SAML IdP certificate is not set.")) {:status-code 500})))] (try (saml/validate response idp-cert (sp-cert-keystore-details) {:acs-url (acs-url) :issuer (sso-settings/saml-identity-provider-issuer)}) (catch Throwable e (log/error e (trs "SAML response validation failed")) (throw (ex-info (tru "Unable to log in: SAML response validation failed") {:status-code 401} e)))))) (defn- xml-string->saml-response [xml-string] (validate-response (saml/->Response xml-string))) (defn- unwrap-user-attributes "For some reason all of the user attributes coming back from the saml library are wrapped in a list, instead of 'Ryan', it's ('Ryan'). This function discards the list if there's just a single item in it." [m] (m/map-vals (fn [maybe-coll] (if (and (coll? maybe-coll) (= 1 (count maybe-coll))) (first maybe-coll) maybe-coll)) m)) (defn- saml-response->attributes [saml-response] (let [assertions (saml/assertions saml-response) attrs (-> assertions first :attrs unwrap-user-attributes)] (when-not attrs (throw (ex-info (str (tru "Unable to log in: SAML info does not contain user attributes.")) {:status-code 401}))) attrs)) (defn- base64-decode [s] (when (u/base64-string? s) (codecs/bytes->str (codec/base64-decode s)))) (defmethod sso/sso-post :saml ;; Does the verification of the IDP's response and 'logs the user in'. The attributes are available in the response: ;; `(get-in saml-info [:assertions :attrs]) [{:keys [params], :as request}] (check-saml-enabled) (let [continue-url (u/ignore-exceptions (when-let [s (some-> (:RelayState params) base64-decode)] (when-not (str/blank? s) s))) xml-string (base64-decode (:SAMLResponse params)) saml-response (xml-string->saml-response xml-string) attrs (saml-response->attributes saml-response) email (get attrs (sso-settings/saml-attribute-email)) first-name (get attrs (sso-settings/saml-attribute-firstname) "Unknown") last-name (get attrs (sso-settings/saml-attribute-lastname) "Unknown") groups (get attrs (sso-settings/saml-attribute-group)) session (fetch-or-create-user! {:first-name first-name :last-name last-name :email email :group-names groups :user-attributes attrs :device-info (request.u/device-info request)}) response (resp/redirect (or continue-url (public-settings/site-url)))] (mw.session/set-session-cookie request response session)))
true
(ns metabase-enterprise.sso.integrations.saml "Implementation of the SAML backend for SSO. The basic flow of of a SAML login is: 1. User attempts to access some `url` but is not authenticated 2. User is redirected to `GET /auth/sso` 3. Metabase issues another redirect to the identity provider URI 4. User logs into their identity provider (i.e. Auth0) 5. Identity provider POSTs to Metabase with successful auth info 6. Metabase parses/validates the SAML response 7. Metabase inits the user session, responds with a redirect to back to the original `url`" (:require [buddy.core.codecs :as codecs] [clojure.string :as str] [clojure.tools.logging :as log] [medley.core :as m] [metabase-enterprise.sso.api.sso :as sso] [metabase-enterprise.sso.integrations.sso-settings :as sso-settings] [metabase-enterprise.sso.integrations.sso-utils :as sso-utils] [metabase.api.common :as api] [metabase.api.session :as session] [metabase.integrations.common :as integrations.common] [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 :refer [trs tru]] [ring.util.codec :as codec] [ring.util.response :as resp] [saml20-clj.core :as saml] [schema.core :as s]) (:import java.util.UUID)) (defn- group-names->ids "Translate a user's group names to a set of MB group IDs using the configured mappings" [group-names] (->> (cond-> group-names (string? group-names) vector) (map keyword) (mapcat (sso-settings/saml-group-mappings)) set)) (defn- all-mapped-group-ids "Returns the set of all MB group IDs that have configured mappings" [] (-> (sso-settings/saml-group-mappings) vals flatten set)) (defn- sync-groups! "Sync a user's groups based on mappings configured in the SAML settings" [user group-names] (when (sso-settings/saml-group-sync) (when group-names (integrations.common/sync-group-memberships! user (group-names->ids group-names) (all-mapped-group-ids) false)))) (s/defn ^:private fetch-or-create-user! :- (s/maybe {:id UUID, s/Keyword s/Any}) "Returns a Session for the given `email`. Will create the user if needed." [{:keys [first-name last-name email group-names user-attributes device-info]}] (when-not (sso-settings/saml-configured?) (throw (IllegalArgumentException. (tru "Can't create new SAML user when SAML is not configured")))) (when-not email (throw (ex-info (str (tru "Invalid SAML configuration: could not find user email.") " " (tru "We tried looking for {0}, but couldn't find the attribute." (sso-settings/saml-attribute-email)) " " (tru "Please make sure your SAML IdP is properly configured.")) {:status-code 400, :user-attributes (keys user-attributes)}))) (when-let [user (or (sso-utils/fetch-and-update-login-attributes! email user-attributes) (sso-utils/create-new-sso-user! {:first_name first-name :last_name last-name :email email :sso_source "saml" :login_attributes user-attributes}))] (sync-groups! user group-names) (session/create-session! :sso user device-info))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; SAML route supporting functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- acs-url [] (str (public-settings/site-url) "/auth/sso")) (defn- sp-cert-keystore-details [] (when-let [path (sso-settings/saml-keystore-path)] (when-let [password (sso-settings/saml-keystore-password)] (when-let [key-name (sso-settings/saml-keystore-alias)] {:filename path :password PI:PASSWORD:<PASSWORD>END_PI :alias key-name})))) (defn- check-saml-enabled [] (api/check (sso-settings/saml-configured?) [400 (tru "SAML has not been enabled and/or configured")])) (defmethod sso/sso-get :saml ;; Initial call that will result in a redirect to the IDP along with information about how the IDP can authenticate ;; and redirect them back to us [req] (check-saml-enabled) (try (let [redirect-url (or (get-in req [:params :redirect]) (log/warn (trs "Warning: expected `redirect` param, but none is present")) (public-settings/site-url)) idp-url (sso-settings/saml-identity-provider-uri) saml-request (saml/request {:request-id (str "id-" (java.util.UUID/randomUUID)) :sp-name (sso-settings/saml-application-name) :issuer (sso-settings/saml-application-name) :acs-url (acs-url) :idp-url idp-url :credential (sp-cert-keystore-details)}) relay-state (saml/str->base64 redirect-url)] (saml/idp-redirect-response saml-request idp-url relay-state)) (catch Throwable e (let [msg (trs "Error generating SAML request")] (log/error e msg) (throw (ex-info msg {:status-code 500} e)))))) (defn- validate-response [response] (let [idp-cert (or (sso-settings/saml-identity-provider-certificate) (throw (ex-info (str (tru "Unable to log in: SAML IdP certificate is not set.")) {:status-code 500})))] (try (saml/validate response idp-cert (sp-cert-keystore-details) {:acs-url (acs-url) :issuer (sso-settings/saml-identity-provider-issuer)}) (catch Throwable e (log/error e (trs "SAML response validation failed")) (throw (ex-info (tru "Unable to log in: SAML response validation failed") {:status-code 401} e)))))) (defn- xml-string->saml-response [xml-string] (validate-response (saml/->Response xml-string))) (defn- unwrap-user-attributes "For some reason all of the user attributes coming back from the saml library are wrapped in a list, instead of 'Ryan', it's ('Ryan'). This function discards the list if there's just a single item in it." [m] (m/map-vals (fn [maybe-coll] (if (and (coll? maybe-coll) (= 1 (count maybe-coll))) (first maybe-coll) maybe-coll)) m)) (defn- saml-response->attributes [saml-response] (let [assertions (saml/assertions saml-response) attrs (-> assertions first :attrs unwrap-user-attributes)] (when-not attrs (throw (ex-info (str (tru "Unable to log in: SAML info does not contain user attributes.")) {:status-code 401}))) attrs)) (defn- base64-decode [s] (when (u/base64-string? s) (codecs/bytes->str (codec/base64-decode s)))) (defmethod sso/sso-post :saml ;; Does the verification of the IDP's response and 'logs the user in'. The attributes are available in the response: ;; `(get-in saml-info [:assertions :attrs]) [{:keys [params], :as request}] (check-saml-enabled) (let [continue-url (u/ignore-exceptions (when-let [s (some-> (:RelayState params) base64-decode)] (when-not (str/blank? s) s))) xml-string (base64-decode (:SAMLResponse params)) saml-response (xml-string->saml-response xml-string) attrs (saml-response->attributes saml-response) email (get attrs (sso-settings/saml-attribute-email)) first-name (get attrs (sso-settings/saml-attribute-firstname) "Unknown") last-name (get attrs (sso-settings/saml-attribute-lastname) "Unknown") groups (get attrs (sso-settings/saml-attribute-group)) session (fetch-or-create-user! {:first-name first-name :last-name last-name :email email :group-names groups :user-attributes attrs :device-info (request.u/device-info request)}) response (resp/redirect (or continue-url (public-settings/site-url)))] (mw.session/set-session-cookie request response session)))
[ { "context": "b-2.0\"\n [\"host\" \"port\" \"username\" \"password\"\n \"name\" \"db\" \"hostname\" \"url\"])", "end": 158, "score": 0.8699628710746765, "start": 150, "tag": "PASSWORD", "value": "password" } ]
src/claude/mongodb.clj
videlalvaro/claude
1
(ns claude.mongodb (:use claude.core) (:refer-clojure :exclude [name])) (expose-service "mongodb-2.0" ["host" "port" "username" "password" "name" "db" "hostname" "url"])
72632
(ns claude.mongodb (:use claude.core) (:refer-clojure :exclude [name])) (expose-service "mongodb-2.0" ["host" "port" "username" "<PASSWORD>" "name" "db" "hostname" "url"])
true
(ns claude.mongodb (:use claude.core) (:refer-clojure :exclude [name])) (expose-service "mongodb-2.0" ["host" "port" "username" "PI:PASSWORD:<PASSWORD>END_PI" "name" "db" "hostname" "url"])
[ { "context": ";; Copyright (c) Alan Dipert and Micha Niskin. All rights reserved.\n;; The use", "end": 28, "score": 0.9998751878738403, "start": 17, "tag": "NAME", "value": "Alan Dipert" }, { "context": ";; Copyright (c) Alan Dipert and Micha Niskin. All rights reserved.\n;; The use and distribution", "end": 45, "score": 0.9998618960380554, "start": 33, "tag": "NAME", "value": "Micha Niskin" }, { "context": " c add-sync!) (doto c (-> array propagate*))))\n\n;; javelin ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 1714, "score": 0.805415689945221, "start": 1713, "tag": "NAME", "value": "j" } ]
gh-pages/index.html.out/javelin/core.cljs
thedavidmeister/cljs-ntp
8
;; Copyright (c) Alan Dipert and Micha Niskin. 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 javelin.core (:require-macros [javelin.core]) (:require [goog.array :as garray] [goog.object :as gobj])) ;; helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare Cell cell? cell input? lens? cmp-rank) (def ^:private ^:dynamic *tx* nil) (def ^:private last-rank (atom 0)) (defn- propagate* [pri-map] (when-let [next (.shift pri-map)] (let [old (.-prev next) new (if-let [f (.-thunk next)] (f) (.-state next))] (when (not= new old) (set! (.-prev next) new) (-notify-watches next old new) (let [sinks (.-sinks next)] (dotimes [i (alength sinks)] (garray/binaryInsert pri-map (aget sinks i) cmp-rank)))) (recur pri-map)))) (defn deref* "If x is a Cell dereferences x and returns the value, otherwise returns x." [x] (if (cell? x) @x x)) (defn- next-rank [ ] (swap! last-rank inc)) (defn- cmp-rank [a b] (let [a (.-rank a) b (.-rank b)] (if (= a b) 0 (- a b)))) (defn- add-sync! [c] (garray/binaryInsert *tx* c cmp-rank)) (defn- safe-nth [c i] (try (nth c i) (catch js/Error _))) (defn- propagate! [c] (if *tx* (doto c add-sync!) (doto c (-> array propagate*)))) ;; javelin ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn destroy-cell! "Unlinks this Cell from the cell graph and resets all internal state. Watches are preserved when keep-watches? is true, otherwise they are all removed." ([this] (destroy-cell! this nil)) ([this keep-watches?] (let [srcs (.-sources this)] (set! (.-sources this) (array)) (set! (.-update this) nil) (set! (.-thunk this) nil) (when-not keep-watches? (set! (.-watches this) {}) (set! (.-numwatches this) 0)) (dotimes [i (alength srcs)] (when-let [c (cell? (aget srcs i))] (garray/removeIf (.-sinks c) #(= % this))))))) (defn- set-formula!* [this f sources updatefn] (when f (set! (.-constant this) true) (set! (.-sources this) (doto sources (.push f))) (dotimes [i (alength (.-sources this))] (let [source (aget (.-sources this) i)] (when (cell? source) (when (and (.-constant this) (not (.-constant source))) (set! (.-constant this) false)) (.push (.-sinks source) this) (if (> (.-rank source) (.-rank this)) (loop [q (array source)] (when-let [dep (.shift q)] (set! (.-rank dep) (next-rank)) (recur (.concat q (.-sinks dep))))))))) (set! (.-thunk this) #(let [argv (.slice (.-sources this)) f (deref* (.pop argv))] (dotimes [i (alength argv)] (aset argv i (deref* (aget argv i)))) (set! (.-state this) (.apply f nil argv)))) (set! (.-update this) updatefn)) (propagate! this)) (defn set-formula! "Given a Cell and optional formula function f and the cells f depends on, sources, updates the formula for this cell in place. If f and/or sources is not spcified they are set to nil." ([this] (destroy-cell! this true) (set-formula!* this nil nil nil)) ([this f] (destroy-cell! this true) (set-formula!* this f (array) nil)) ([this f sources] (destroy-cell! this true) (set-formula!* this f (into-array sources) nil)) ([this f sources updatefn] (destroy-cell! this true) (set-formula!* this f (into-array sources) updatefn))) (deftype Cell [meta state rank prev sources sinks thunk watches update constant numwatches] cljs.core/IPrintWithWriter (-pr-writer [this w _] (write-all w "#object [javelin.core.Cell " (pr-str state) "]")) cljs.core/IWithMeta (-with-meta [this meta] (Cell. meta state rank prev sources sinks thunk watches update constant numwatches)) cljs.core/IMeta (-meta [this] meta) cljs.core/IDeref (-deref [this] (.-state this)) cljs.core/IReset (-reset! [this x] (cond (lens? this) ((.-update this) x) (input? this) (do (set! (.-state this) x) (propagate! this)) :else (throw (js/Error. "can't swap! or reset! formula cell"))) (.-state this)) cljs.core/ISwap (-swap! [this f] (reset! this (f (.-state this)))) (-swap! [this f a] (reset! this (f (.-state this) a))) (-swap! [this f a b] (reset! this (f (.-state this) a b))) (-swap! [this f a b xs] (reset! this (apply f (.-state this) a b xs))) cljs.core/IWatchable (-notify-watches [this o n] (when (< 0 (.-numwatches this)) (doseq [[key f] watches] (f key this o n)))) (-add-watch [this k f] (when-not (contains? (.-watches this) k) (set! (.-numwatches this) (inc (.-numwatches this)))) (set! (.-watches this) (assoc watches k f))) (-remove-watch [this k] (when (contains? (.-watches this) k) (set! (.-numwatches this) (dec (.-numwatches this))) (set! (.-watches this) (dissoc watches k))))) (defn cell? "Returns c if c is a Cell, nil otherwise." [c] (when (= (type c) Cell) c)) (defn formula? [c] "Returns c if c is a formula cell, nil otherwise." (when (and (cell? c) (.-thunk c)) c)) (defn lens? [c] "Returns c if c is a lens, nil otherwise." (when (and (cell? c) (.-update c)) c)) (defn input? [c] "Returns c if c is an input cell, nil otherwise." (when (and (cell? c) (not (formula? c))) c)) (defn constant? [c] "Returns c if c is a constant formula cell, nil otherwise." (when (and (cell? c) (.-constant c)) c)) (defn set-cell! "Converts c to an input cell in place, setting its contents to x. It's okay if c was already an input cell. Changes will be propagated to any cells that depend on c." [c x] (set! (.-state c) x) (set-formula! c)) (defn formula "Returns a function that returns a formula cell with f as its formula, and if updatefn is provided the returned cell is a lens. See also: the javelin.core/cell= macro. (def x (cell 100)) (def y (cell 200)) (def z1 (cell= (+ x y))) (def z2 ((formula +) x y)) The formula cells z1 and z2 are equivalent." ([f] (formula f nil)) ([f updatefn] #(set-formula!* (cell ::none) f (.. js/Array -prototype -slice (call (js-arguments))) updatefn))) (defn lens "Returns a new lens whose value is the same as c's with update function f. This is equivalent to ((formula identity f) c)." [c f] ((formula identity f) c)) (defn cell "Returns a new input cell containing value x. The :meta option can be used to create the cell with the given metadata map." ([x] (Cell. nil x (next-rank) x (array) (array) nil {} nil false 0)) ([x & {:keys [meta]}] (Cell. meta x (next-rank) x (array) (array) nil {} nil false 0))) (def ^:deprecated lift "This function is deprecated, please use #'javelin.core/formula instead." formula) ;; javelin util ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn dosync* "Calls the thunk with no arguments within a transaction. Propagation of updates to formula cells is deferred until the transaction is complete. Input cells *will* update during the transaction. Transactions may be nested. See also: the javelin.core/dosync macro." [thunk] (if *tx* (thunk) (binding [*tx* (array)] (thunk) (let [tx *tx*] (binding [*tx* nil] (propagate* tx)))))) (defn alts! "Given a number of cells, returns a formula cell whose value is a seq of values from cells that changed in the last update. Note that multiple cells may update atomically, which is why the formula's value is a seq. Consider: (def a (cell {:x 1 :y 2})) (def x (cell= (:x a))) (def y (cell= (:y a))) (def z (alts! x y)) then, (deref z) ;=> (1 2) (swap! a assoc :x 42) (deref z) ;=> (42) (reset! a {:x 10 :y 20}) (deref z) ;=> (10 20) " [& cells] (let [olds (atom (repeat (count cells) ::none)) tag-neq #(vector (not= %1 %2) %2) diff #(->> %2 (map tag-neq %1) (filter first) (map second) distinct) proc #(let [news (diff (deref olds) %&)] (reset! olds %&) news)] (apply (formula proc) cells))) (defn cell-map "Given a function f and a cell c that contains a seqable collection of items, returns a seq of formula cells such that the ith formula cell is equivalent to (cell= (f (nth c i)))." [f c] (let [cseq ((formula seq) c)] (map #((formula (comp f safe-nth)) cseq %) (range 0 (count @cseq))))) (defn cell-doseq* "Given a function f and a cell c that contains a seqable collection of items, calls f for side effects once for each item in c, passing one argument: a formula cell equivalent to (cell= (nth c i)) for the ith item in c. Whenever c grows beyond its previous maximum size f is called as above for each item beyond the maximum size. Nothing happens when c shrinks. See also: the javelin.core/cell-doseq macro. Consider: (def things (cell [:a :b :c])) (cell-doseq* things (fn doit [x] (prn :creating @x) (add-watch x nil #(prn :updating %3 %4)))) ;; the following is printed: :creating :a :creating :b :creating :c Shrink things by removing the last item: (swap! things pop) ;; the following is printed (because the 3rd item in things is now nil, ;; since things only contains 2 items) -- note that the doit function is ;; not called (or we would see a :creating message): :updating :c nil Grow things such that it is one item larger than it ever was: (swap! things into [:u :v]) ;; the following is printed (because things now has 4 items, so the 3rd ;; item is now :u and the max size increases by one with the new item :v): :updating nil :u :creating :v A weird imagination is most useful to gain full advantage of all the features." [c f] (let [pool-size (atom 0)] (-> c ((formula (fn [items] (let [cnt (count items)] (when (< @pool-size cnt) (dotimes [i (- cnt @pool-size)] (f ((formula safe-nth) c (+ i @pool-size)))) (reset! pool-size cnt)))))))))
111236
;; Copyright (c) <NAME> and <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 javelin.core (:require-macros [javelin.core]) (:require [goog.array :as garray] [goog.object :as gobj])) ;; helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare Cell cell? cell input? lens? cmp-rank) (def ^:private ^:dynamic *tx* nil) (def ^:private last-rank (atom 0)) (defn- propagate* [pri-map] (when-let [next (.shift pri-map)] (let [old (.-prev next) new (if-let [f (.-thunk next)] (f) (.-state next))] (when (not= new old) (set! (.-prev next) new) (-notify-watches next old new) (let [sinks (.-sinks next)] (dotimes [i (alength sinks)] (garray/binaryInsert pri-map (aget sinks i) cmp-rank)))) (recur pri-map)))) (defn deref* "If x is a Cell dereferences x and returns the value, otherwise returns x." [x] (if (cell? x) @x x)) (defn- next-rank [ ] (swap! last-rank inc)) (defn- cmp-rank [a b] (let [a (.-rank a) b (.-rank b)] (if (= a b) 0 (- a b)))) (defn- add-sync! [c] (garray/binaryInsert *tx* c cmp-rank)) (defn- safe-nth [c i] (try (nth c i) (catch js/Error _))) (defn- propagate! [c] (if *tx* (doto c add-sync!) (doto c (-> array propagate*)))) ;; <NAME>avelin ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn destroy-cell! "Unlinks this Cell from the cell graph and resets all internal state. Watches are preserved when keep-watches? is true, otherwise they are all removed." ([this] (destroy-cell! this nil)) ([this keep-watches?] (let [srcs (.-sources this)] (set! (.-sources this) (array)) (set! (.-update this) nil) (set! (.-thunk this) nil) (when-not keep-watches? (set! (.-watches this) {}) (set! (.-numwatches this) 0)) (dotimes [i (alength srcs)] (when-let [c (cell? (aget srcs i))] (garray/removeIf (.-sinks c) #(= % this))))))) (defn- set-formula!* [this f sources updatefn] (when f (set! (.-constant this) true) (set! (.-sources this) (doto sources (.push f))) (dotimes [i (alength (.-sources this))] (let [source (aget (.-sources this) i)] (when (cell? source) (when (and (.-constant this) (not (.-constant source))) (set! (.-constant this) false)) (.push (.-sinks source) this) (if (> (.-rank source) (.-rank this)) (loop [q (array source)] (when-let [dep (.shift q)] (set! (.-rank dep) (next-rank)) (recur (.concat q (.-sinks dep))))))))) (set! (.-thunk this) #(let [argv (.slice (.-sources this)) f (deref* (.pop argv))] (dotimes [i (alength argv)] (aset argv i (deref* (aget argv i)))) (set! (.-state this) (.apply f nil argv)))) (set! (.-update this) updatefn)) (propagate! this)) (defn set-formula! "Given a Cell and optional formula function f and the cells f depends on, sources, updates the formula for this cell in place. If f and/or sources is not spcified they are set to nil." ([this] (destroy-cell! this true) (set-formula!* this nil nil nil)) ([this f] (destroy-cell! this true) (set-formula!* this f (array) nil)) ([this f sources] (destroy-cell! this true) (set-formula!* this f (into-array sources) nil)) ([this f sources updatefn] (destroy-cell! this true) (set-formula!* this f (into-array sources) updatefn))) (deftype Cell [meta state rank prev sources sinks thunk watches update constant numwatches] cljs.core/IPrintWithWriter (-pr-writer [this w _] (write-all w "#object [javelin.core.Cell " (pr-str state) "]")) cljs.core/IWithMeta (-with-meta [this meta] (Cell. meta state rank prev sources sinks thunk watches update constant numwatches)) cljs.core/IMeta (-meta [this] meta) cljs.core/IDeref (-deref [this] (.-state this)) cljs.core/IReset (-reset! [this x] (cond (lens? this) ((.-update this) x) (input? this) (do (set! (.-state this) x) (propagate! this)) :else (throw (js/Error. "can't swap! or reset! formula cell"))) (.-state this)) cljs.core/ISwap (-swap! [this f] (reset! this (f (.-state this)))) (-swap! [this f a] (reset! this (f (.-state this) a))) (-swap! [this f a b] (reset! this (f (.-state this) a b))) (-swap! [this f a b xs] (reset! this (apply f (.-state this) a b xs))) cljs.core/IWatchable (-notify-watches [this o n] (when (< 0 (.-numwatches this)) (doseq [[key f] watches] (f key this o n)))) (-add-watch [this k f] (when-not (contains? (.-watches this) k) (set! (.-numwatches this) (inc (.-numwatches this)))) (set! (.-watches this) (assoc watches k f))) (-remove-watch [this k] (when (contains? (.-watches this) k) (set! (.-numwatches this) (dec (.-numwatches this))) (set! (.-watches this) (dissoc watches k))))) (defn cell? "Returns c if c is a Cell, nil otherwise." [c] (when (= (type c) Cell) c)) (defn formula? [c] "Returns c if c is a formula cell, nil otherwise." (when (and (cell? c) (.-thunk c)) c)) (defn lens? [c] "Returns c if c is a lens, nil otherwise." (when (and (cell? c) (.-update c)) c)) (defn input? [c] "Returns c if c is an input cell, nil otherwise." (when (and (cell? c) (not (formula? c))) c)) (defn constant? [c] "Returns c if c is a constant formula cell, nil otherwise." (when (and (cell? c) (.-constant c)) c)) (defn set-cell! "Converts c to an input cell in place, setting its contents to x. It's okay if c was already an input cell. Changes will be propagated to any cells that depend on c." [c x] (set! (.-state c) x) (set-formula! c)) (defn formula "Returns a function that returns a formula cell with f as its formula, and if updatefn is provided the returned cell is a lens. See also: the javelin.core/cell= macro. (def x (cell 100)) (def y (cell 200)) (def z1 (cell= (+ x y))) (def z2 ((formula +) x y)) The formula cells z1 and z2 are equivalent." ([f] (formula f nil)) ([f updatefn] #(set-formula!* (cell ::none) f (.. js/Array -prototype -slice (call (js-arguments))) updatefn))) (defn lens "Returns a new lens whose value is the same as c's with update function f. This is equivalent to ((formula identity f) c)." [c f] ((formula identity f) c)) (defn cell "Returns a new input cell containing value x. The :meta option can be used to create the cell with the given metadata map." ([x] (Cell. nil x (next-rank) x (array) (array) nil {} nil false 0)) ([x & {:keys [meta]}] (Cell. meta x (next-rank) x (array) (array) nil {} nil false 0))) (def ^:deprecated lift "This function is deprecated, please use #'javelin.core/formula instead." formula) ;; javelin util ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn dosync* "Calls the thunk with no arguments within a transaction. Propagation of updates to formula cells is deferred until the transaction is complete. Input cells *will* update during the transaction. Transactions may be nested. See also: the javelin.core/dosync macro." [thunk] (if *tx* (thunk) (binding [*tx* (array)] (thunk) (let [tx *tx*] (binding [*tx* nil] (propagate* tx)))))) (defn alts! "Given a number of cells, returns a formula cell whose value is a seq of values from cells that changed in the last update. Note that multiple cells may update atomically, which is why the formula's value is a seq. Consider: (def a (cell {:x 1 :y 2})) (def x (cell= (:x a))) (def y (cell= (:y a))) (def z (alts! x y)) then, (deref z) ;=> (1 2) (swap! a assoc :x 42) (deref z) ;=> (42) (reset! a {:x 10 :y 20}) (deref z) ;=> (10 20) " [& cells] (let [olds (atom (repeat (count cells) ::none)) tag-neq #(vector (not= %1 %2) %2) diff #(->> %2 (map tag-neq %1) (filter first) (map second) distinct) proc #(let [news (diff (deref olds) %&)] (reset! olds %&) news)] (apply (formula proc) cells))) (defn cell-map "Given a function f and a cell c that contains a seqable collection of items, returns a seq of formula cells such that the ith formula cell is equivalent to (cell= (f (nth c i)))." [f c] (let [cseq ((formula seq) c)] (map #((formula (comp f safe-nth)) cseq %) (range 0 (count @cseq))))) (defn cell-doseq* "Given a function f and a cell c that contains a seqable collection of items, calls f for side effects once for each item in c, passing one argument: a formula cell equivalent to (cell= (nth c i)) for the ith item in c. Whenever c grows beyond its previous maximum size f is called as above for each item beyond the maximum size. Nothing happens when c shrinks. See also: the javelin.core/cell-doseq macro. Consider: (def things (cell [:a :b :c])) (cell-doseq* things (fn doit [x] (prn :creating @x) (add-watch x nil #(prn :updating %3 %4)))) ;; the following is printed: :creating :a :creating :b :creating :c Shrink things by removing the last item: (swap! things pop) ;; the following is printed (because the 3rd item in things is now nil, ;; since things only contains 2 items) -- note that the doit function is ;; not called (or we would see a :creating message): :updating :c nil Grow things such that it is one item larger than it ever was: (swap! things into [:u :v]) ;; the following is printed (because things now has 4 items, so the 3rd ;; item is now :u and the max size increases by one with the new item :v): :updating nil :u :creating :v A weird imagination is most useful to gain full advantage of all the features." [c f] (let [pool-size (atom 0)] (-> c ((formula (fn [items] (let [cnt (count items)] (when (< @pool-size cnt) (dotimes [i (- cnt @pool-size)] (f ((formula safe-nth) c (+ i @pool-size)))) (reset! pool-size cnt)))))))))
true
;; Copyright (c) PI:NAME:<NAME>END_PI and 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 javelin.core (:require-macros [javelin.core]) (:require [goog.array :as garray] [goog.object :as gobj])) ;; helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare Cell cell? cell input? lens? cmp-rank) (def ^:private ^:dynamic *tx* nil) (def ^:private last-rank (atom 0)) (defn- propagate* [pri-map] (when-let [next (.shift pri-map)] (let [old (.-prev next) new (if-let [f (.-thunk next)] (f) (.-state next))] (when (not= new old) (set! (.-prev next) new) (-notify-watches next old new) (let [sinks (.-sinks next)] (dotimes [i (alength sinks)] (garray/binaryInsert pri-map (aget sinks i) cmp-rank)))) (recur pri-map)))) (defn deref* "If x is a Cell dereferences x and returns the value, otherwise returns x." [x] (if (cell? x) @x x)) (defn- next-rank [ ] (swap! last-rank inc)) (defn- cmp-rank [a b] (let [a (.-rank a) b (.-rank b)] (if (= a b) 0 (- a b)))) (defn- add-sync! [c] (garray/binaryInsert *tx* c cmp-rank)) (defn- safe-nth [c i] (try (nth c i) (catch js/Error _))) (defn- propagate! [c] (if *tx* (doto c add-sync!) (doto c (-> array propagate*)))) ;; PI:NAME:<NAME>END_PIavelin ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn destroy-cell! "Unlinks this Cell from the cell graph and resets all internal state. Watches are preserved when keep-watches? is true, otherwise they are all removed." ([this] (destroy-cell! this nil)) ([this keep-watches?] (let [srcs (.-sources this)] (set! (.-sources this) (array)) (set! (.-update this) nil) (set! (.-thunk this) nil) (when-not keep-watches? (set! (.-watches this) {}) (set! (.-numwatches this) 0)) (dotimes [i (alength srcs)] (when-let [c (cell? (aget srcs i))] (garray/removeIf (.-sinks c) #(= % this))))))) (defn- set-formula!* [this f sources updatefn] (when f (set! (.-constant this) true) (set! (.-sources this) (doto sources (.push f))) (dotimes [i (alength (.-sources this))] (let [source (aget (.-sources this) i)] (when (cell? source) (when (and (.-constant this) (not (.-constant source))) (set! (.-constant this) false)) (.push (.-sinks source) this) (if (> (.-rank source) (.-rank this)) (loop [q (array source)] (when-let [dep (.shift q)] (set! (.-rank dep) (next-rank)) (recur (.concat q (.-sinks dep))))))))) (set! (.-thunk this) #(let [argv (.slice (.-sources this)) f (deref* (.pop argv))] (dotimes [i (alength argv)] (aset argv i (deref* (aget argv i)))) (set! (.-state this) (.apply f nil argv)))) (set! (.-update this) updatefn)) (propagate! this)) (defn set-formula! "Given a Cell and optional formula function f and the cells f depends on, sources, updates the formula for this cell in place. If f and/or sources is not spcified they are set to nil." ([this] (destroy-cell! this true) (set-formula!* this nil nil nil)) ([this f] (destroy-cell! this true) (set-formula!* this f (array) nil)) ([this f sources] (destroy-cell! this true) (set-formula!* this f (into-array sources) nil)) ([this f sources updatefn] (destroy-cell! this true) (set-formula!* this f (into-array sources) updatefn))) (deftype Cell [meta state rank prev sources sinks thunk watches update constant numwatches] cljs.core/IPrintWithWriter (-pr-writer [this w _] (write-all w "#object [javelin.core.Cell " (pr-str state) "]")) cljs.core/IWithMeta (-with-meta [this meta] (Cell. meta state rank prev sources sinks thunk watches update constant numwatches)) cljs.core/IMeta (-meta [this] meta) cljs.core/IDeref (-deref [this] (.-state this)) cljs.core/IReset (-reset! [this x] (cond (lens? this) ((.-update this) x) (input? this) (do (set! (.-state this) x) (propagate! this)) :else (throw (js/Error. "can't swap! or reset! formula cell"))) (.-state this)) cljs.core/ISwap (-swap! [this f] (reset! this (f (.-state this)))) (-swap! [this f a] (reset! this (f (.-state this) a))) (-swap! [this f a b] (reset! this (f (.-state this) a b))) (-swap! [this f a b xs] (reset! this (apply f (.-state this) a b xs))) cljs.core/IWatchable (-notify-watches [this o n] (when (< 0 (.-numwatches this)) (doseq [[key f] watches] (f key this o n)))) (-add-watch [this k f] (when-not (contains? (.-watches this) k) (set! (.-numwatches this) (inc (.-numwatches this)))) (set! (.-watches this) (assoc watches k f))) (-remove-watch [this k] (when (contains? (.-watches this) k) (set! (.-numwatches this) (dec (.-numwatches this))) (set! (.-watches this) (dissoc watches k))))) (defn cell? "Returns c if c is a Cell, nil otherwise." [c] (when (= (type c) Cell) c)) (defn formula? [c] "Returns c if c is a formula cell, nil otherwise." (when (and (cell? c) (.-thunk c)) c)) (defn lens? [c] "Returns c if c is a lens, nil otherwise." (when (and (cell? c) (.-update c)) c)) (defn input? [c] "Returns c if c is an input cell, nil otherwise." (when (and (cell? c) (not (formula? c))) c)) (defn constant? [c] "Returns c if c is a constant formula cell, nil otherwise." (when (and (cell? c) (.-constant c)) c)) (defn set-cell! "Converts c to an input cell in place, setting its contents to x. It's okay if c was already an input cell. Changes will be propagated to any cells that depend on c." [c x] (set! (.-state c) x) (set-formula! c)) (defn formula "Returns a function that returns a formula cell with f as its formula, and if updatefn is provided the returned cell is a lens. See also: the javelin.core/cell= macro. (def x (cell 100)) (def y (cell 200)) (def z1 (cell= (+ x y))) (def z2 ((formula +) x y)) The formula cells z1 and z2 are equivalent." ([f] (formula f nil)) ([f updatefn] #(set-formula!* (cell ::none) f (.. js/Array -prototype -slice (call (js-arguments))) updatefn))) (defn lens "Returns a new lens whose value is the same as c's with update function f. This is equivalent to ((formula identity f) c)." [c f] ((formula identity f) c)) (defn cell "Returns a new input cell containing value x. The :meta option can be used to create the cell with the given metadata map." ([x] (Cell. nil x (next-rank) x (array) (array) nil {} nil false 0)) ([x & {:keys [meta]}] (Cell. meta x (next-rank) x (array) (array) nil {} nil false 0))) (def ^:deprecated lift "This function is deprecated, please use #'javelin.core/formula instead." formula) ;; javelin util ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn dosync* "Calls the thunk with no arguments within a transaction. Propagation of updates to formula cells is deferred until the transaction is complete. Input cells *will* update during the transaction. Transactions may be nested. See also: the javelin.core/dosync macro." [thunk] (if *tx* (thunk) (binding [*tx* (array)] (thunk) (let [tx *tx*] (binding [*tx* nil] (propagate* tx)))))) (defn alts! "Given a number of cells, returns a formula cell whose value is a seq of values from cells that changed in the last update. Note that multiple cells may update atomically, which is why the formula's value is a seq. Consider: (def a (cell {:x 1 :y 2})) (def x (cell= (:x a))) (def y (cell= (:y a))) (def z (alts! x y)) then, (deref z) ;=> (1 2) (swap! a assoc :x 42) (deref z) ;=> (42) (reset! a {:x 10 :y 20}) (deref z) ;=> (10 20) " [& cells] (let [olds (atom (repeat (count cells) ::none)) tag-neq #(vector (not= %1 %2) %2) diff #(->> %2 (map tag-neq %1) (filter first) (map second) distinct) proc #(let [news (diff (deref olds) %&)] (reset! olds %&) news)] (apply (formula proc) cells))) (defn cell-map "Given a function f and a cell c that contains a seqable collection of items, returns a seq of formula cells such that the ith formula cell is equivalent to (cell= (f (nth c i)))." [f c] (let [cseq ((formula seq) c)] (map #((formula (comp f safe-nth)) cseq %) (range 0 (count @cseq))))) (defn cell-doseq* "Given a function f and a cell c that contains a seqable collection of items, calls f for side effects once for each item in c, passing one argument: a formula cell equivalent to (cell= (nth c i)) for the ith item in c. Whenever c grows beyond its previous maximum size f is called as above for each item beyond the maximum size. Nothing happens when c shrinks. See also: the javelin.core/cell-doseq macro. Consider: (def things (cell [:a :b :c])) (cell-doseq* things (fn doit [x] (prn :creating @x) (add-watch x nil #(prn :updating %3 %4)))) ;; the following is printed: :creating :a :creating :b :creating :c Shrink things by removing the last item: (swap! things pop) ;; the following is printed (because the 3rd item in things is now nil, ;; since things only contains 2 items) -- note that the doit function is ;; not called (or we would see a :creating message): :updating :c nil Grow things such that it is one item larger than it ever was: (swap! things into [:u :v]) ;; the following is printed (because things now has 4 items, so the 3rd ;; item is now :u and the max size increases by one with the new item :v): :updating nil :u :creating :v A weird imagination is most useful to gain full advantage of all the features." [c f] (let [pool-size (atom 0)] (-> c ((formula (fn [items] (let [cnt (count items)] (when (< @pool-size cnt) (dotimes [i (- cnt @pool-size)] (f ((formula safe-nth) c (+ i @pool-size)))) (reset! pool-size cnt)))))))))
[ { "context": "))\n\n(def federer\n (match-tree-by-player matches \"roger-federer\"))\n\n;;; The new functions start here\n\n(defn take-", "end": 3104, "score": 0.9798375964164734, "start": 3091, "tag": "USERNAME", "value": "roger-federer" }, { "context": " [:winner_slug :loser_slug])\n;; => {:winner_slug \"roger-federer\", :loser_slug \"guido-pella\"}\n\n(take-matches 3 fed", "end": 3591, "score": 0.9955359101295471, "start": 3578, "tag": "USERNAME", "value": "roger-federer" }, { "context": "({:tourney_slug \"wimbledon\",\n;; :loser_slug \"guido-pella\",\n;; :winner_sets_won 3,\n;; :mat", "end": 3707, "score": 0.8007832765579224, "start": 3703, "tag": "USERNAME", "value": "guid" }, { "context": "ney_slug \"wimbledon\",\n;; :loser_slug \"guido-pella\",\n;; :winner_sets_won 3,\n;; :match_scor", "end": 3714, "score": 0.5418850779533386, "start": 3710, "tag": "USERNAME", "value": "ella" }, { "context": "urney_year_id \"2016-540\",\n;; :tourney_order \"39\",\n;; :winner_seed \"3\",\n;; :loser_seed ", "end": 3912, "score": 0.538284957408905, "start": 3911, "tag": "NAME", "value": "3" }, { "context": "\",\n;; :match_order \"3\",\n;; :loser_name \"Guido Pella\",\n;; :winner_player_id \"f324\",\n;; :matc", "end": 4062, "score": 0.9998738765716553, "start": 4051, "tag": "NAME", "value": "Guido Pella" }, { "context": "ch_id \"2016-540-f324-pc11\",\n;; :winner_name \"Roger Federer\",\n;; :winner_games_won 20,\n;; :loser_ra", "end": 4503, "score": 0.9998580813407898, "start": 4490, "tag": "NAME", "value": "Roger Federer" }, { "context": "; :match_order \"3\",\n;; :loser_name \"Marcus Willis\",\n;; :winner_player_id \"f324\",\n;; :", "end": 5051, "score": 0.9998557567596436, "start": 5038, "tag": "NAME", "value": "Marcus Willis" }, { "context": "_id \"2016-540-f324-w521\",\n;; :winner_name \"Roger Federer\",\n;; :winner_games_won 18,\n;; :lose", "end": 5511, "score": 0.9998851418495178, "start": 5498, "tag": "NAME", "value": "Roger Federer" }, { "context": " :loser_seed \"\",\n;; :winner_slug \"roger-federer\",\n;; :match_order \"3\",\n;; :loser_", "end": 6007, "score": 0.9380665421485901, "start": 5994, "tag": "USERNAME", "value": "roger-federer" }, { "context": " :match_order \"3\",\n;; :loser_name \"Daniel Evans\",\n;; :winner_player_id \"f324\",\n;; ", "end": 6075, "score": 0.9998900890350342, "start": 6063, "tag": "NAME", "value": "Daniel Evans" }, { "context": "id \"2016-540-f324-e687\",\n;; :winner_name \"Roger Federer\",\n;; :winner_games_won 18,\n;; :lo", "end": 6544, "score": 0.9998921751976013, "start": 6531, "tag": "NAME", "value": "Roger Federer" }, { "context": "rney_slug \"marseille\",\n;; :loser_slug \"marcus-willis\",\n;; :winner_sets_won 2,\n;; :matc", "end": 6737, "score": 0.4975295066833496, "start": 6727, "tag": "USERNAME", "value": "cus-willis" }, { "context": " :loser_seed \"\",\n;; :winner_slug \"pierre-hugues-herbert\",\n;; :match_order \"5\",\n;; ", "end": 7041, "score": 0.7903347611427307, "start": 7037, "tag": "NAME", "value": "erre" }, { "context": " :loser_seed \"\",\n;; :winner_slug \"pierre-hugues-herbert\",\n;; :match_order \"5\",\n;; ", "end": 7048, "score": 0.9369235038757324, "start": 7042, "tag": "NAME", "value": "hugues" }, { "context": "r_seed \"\",\n;; :winner_slug \"pierre-hugues-herbert\",\n;; :match_order \"5\",\n;; :loser_", "end": 7056, "score": 0.9204696416854858, "start": 7049, "tag": "NAME", "value": "herbert" }, { "context": " :match_order \"5\",\n;; :loser_name \"Marcus Willis\",\n;; :winner_player_id \"h996\",\n;; ", "end": 7125, "score": 0.9998897314071655, "start": 7112, "tag": "NAME", "value": "Marcus Willis" }, { "context": "id \"2015-496-h996-w521\",\n;; :winner_name \"Pierre-Hugues Herbert\",\n;; :winner_games_won 14,\n;; :lo", "end": 7611, "score": 0.9998739957809448, "start": 7590, "tag": "NAME", "value": "Pierre-Hugues Herbert" }, { "context": ":loser_seed \"13\",\n;; :winner_slug \"benjamin-becker\",\n;; :match_order \"13\",\n;; :loser_n", "end": 8106, "score": 0.6037294864654541, "start": 8100, "tag": "USERNAME", "value": "becker" }, { "context": " :match_order \"13\",\n;; :loser_name \"Guido Pella\",\n;; :winner_player_id \"b896\",\n;; :", "end": 8172, "score": 0.9998748898506165, "start": 8161, "tag": "NAME", "value": "Guido Pella" }, { "context": "_id \"2016-741-b896-pc11\",\n;; :winner_name \"Benjamin Becker\",\n;; :winner_games_won 15,\n;; :lose", "end": 8635, "score": 0.9998970031738281, "start": 8620, "tag": "NAME", "value": "Benjamin Becker" }, { "context": "ourney_slug \"eastbourne\",\n;; :loser_slug \"benjamin-becker\",\n;; :winner_sets_won 2,\n;; ", "end": 8821, "score": 0.8990578651428223, "start": 8813, "tag": "USERNAME", "value": "benjamin" }, { "context": "ug \"eastbourne\",\n;; :loser_slug \"benjamin-becker\",\n;; :winner_sets_won 2,\n;; :matc", "end": 8828, "score": 0.9566188454627991, "start": 8822, "tag": "USERNAME", "value": "becker" }, { "context": " :match_order \"8\",\n;; :loser_name \"Benjamin Becker\",\n;; :winner_player_id \"sc56\",\n;; ", "end": 9202, "score": 0.9998856782913208, "start": 9187, "tag": "NAME", "value": "Benjamin Becker" }, { "context": "id \"2016-741-sc56-b896\",\n;; :winner_name \"Dudi Sela\",\n;; :winner_games_won 14,\n;; :lo", "end": 9669, "score": 0.9998047947883606, "start": 9660, "tag": "NAME", "value": "Dudi Sela" }, { "context": " :match_order \"59\",\n;; :loser_name \"Diego Schwartzman\",\n;; :winner_player_id \"pc11\",\n;; ", "end": 10252, "score": 0.9998885989189148, "start": 10235, "tag": "NAME", "value": "Diego Schwartzman" }, { "context": "id \"2016-520-pc11-sm37\",\n;; :winner_name \"Guido Pella\",\n;; :winner_games_won 21,\n;; :lo", "end": 10725, "score": 0.9998964071273804, "start": 10714, "tag": "NAME", "value": "Guido Pella" } ]
Chapter07/Exercise7.04/tennis_history.clj
transducer/The-Clojure-Workshop
55
(ns packt-clj.tennis (:require [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.math.numeric-tower :as math] [semantic-csv.core :as sc])) ;;; The first part of this file comes from the tennis_history.clj ;;; from Exercise 5.03. (defn match-probability [player-1-rating player-2-rating] (/ 1 (+ 1 (math/expt 10 (/ (- player-2-rating player-1-rating) 400))))) (defn recalculate-rating [k previous-rating expected-outcome real-outcome] (+ previous-rating (* k (- real-outcome expected-outcome)))) (defn elo-db [csv k] (with-open [r (io/reader csv)] (->> (csv/read-csv r) sc/mappify (sc/cast-with {:winner_sets_won sc/->int :loser_sets_won sc/->int :winner_games_won sc/->int :loser_games_won sc/->int}) (reduce (fn [{:keys [players] :as acc} {:keys [_winner_name winner_slug _loser_name loser_slug] :as match}] (let [winner-rating (get players winner_slug 400) loser-rating (get players loser_slug 400) winner-probability (match-probability winner-rating loser-rating) loser-probability (- 1 winner-probability)] (-> acc (assoc-in [:players winner_slug] (recalculate-rating k winner-rating winner-probability 1)) (assoc-in [:players loser_slug] (recalculate-rating k loser-rating loser-probability 0)) (update :matches (fn [ms] (conj ms (assoc match :winner_rating winner-rating :loser_rating loser-rating))))))) {:players {} :matches []}) :matches reverse))) (def matches (elo-db "match_scores_1991-2016_unindexed_csv.csv" 35)) (defn player-in-match? [{:keys [winner_slug loser_slug]} player-slug] ((hash-set winner_slug loser_slug) player-slug)) (defn match-tree-by-player [matches player-slug] (lazy-seq (cond (empty? matches) '() (player-in-match? (first matches) player-slug) (cons (first matches) (cons [(match-tree-by-player (rest matches) (:winner_slug (first matches))) (match-tree-by-player (rest matches) (:loser_slug (first matches)))] '())) :else (match-tree-by-player (rest matches) player-slug)))) (def federer (match-tree-by-player matches "roger-federer")) ;;; The new functions start here (defn take-matches [limit tree] (cond (zero? limit) '() (= 1 limit) (first tree) :else (cons (first tree) (cons [(take-matches (dec limit) (first (second tree))) (take-matches (dec limit) (second (second tree)))] '())))) (take-matches 0 federer) ;; => () (select-keys (take-matches 1 federer) [:winner_slug :loser_slug]) ;; => {:winner_slug "roger-federer", :loser_slug "guido-pella"} (take-matches 3 federer) ;; => ({:tourney_slug "wimbledon", ;; :loser_slug "guido-pella", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "76(5) 76(3) 63", ;; :loser_sets_won 0, ;; :loser_games_won 15, ;; :tourney_year_id "2016-540", ;; :tourney_order "39", ;; :winner_seed "3", ;; :loser_seed "", ;; :winner_slug "roger-federer", ;; :match_order "3", ;; :loser_name "Guido Pella", ;; :winner_player_id "f324", ;; :match_stats_url_suffix "/en/scores/2016/540/MS080/match-stats", ;; :tourney_url_suffix "/en/scores/archive/wimbledon/540/2016/results", ;; :loser_player_id "pc11", ;; :loser_tiebreaks_won "0", ;; :round_order "7", ;; :winner_rating 1129.178155312036, ;; :tourney_round_name "Round of 128", ;; :match_id "2016-540-f324-pc11", ;; :winner_name "Roger Federer", ;; :winner_games_won 20, ;; :loser_rating 625.3431873490674, ;; :winner_tiebreaks_won "2"} ;; [({:tourney_slug "wimbledon", ;; :loser_slug "marcus-willis", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "60 63 64", ;; :loser_sets_won 0, ;; :loser_games_won 7, ;; :tourney_year_id "2016-540", ;; :tourney_order "39", ;; :winner_seed "3", ;; :loser_seed "Q", ;; :winner_slug "roger-federer", ;; :match_order "3", ;; :loser_name "Marcus Willis", ;; :winner_player_id "f324", ;; :match_stats_url_suffix "/en/scores/2016/540/MS040/match-stats", ;; :tourney_url_suffix "/en/scores/archive/wimbledon/540/2016/results", ;; :loser_player_id "w521", ;; :loser_tiebreaks_won "0", ;; :round_order "6", ;; :winner_rating 1128.703390288765, ;; :tourney_round_name "Round of 64", ;; :match_id "2016-540-f324-w521", ;; :winner_name "Roger Federer", ;; :winner_games_won 18, ;; :loser_rating 384.0402195770708, ;; :winner_tiebreaks_won "0"} ;; [{:tourney_slug "wimbledon", ;; :loser_slug "daniel-evans", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "64 62 62", ;; :loser_sets_won 0, ;; :loser_games_won 8, ;; :tourney_year_id "2016-540", ;; :tourney_order "39", ;; :winner_seed "3", ;; :loser_seed "", ;; :winner_slug "roger-federer", ;; :match_order "3", ;; :loser_name "Daniel Evans", ;; :winner_player_id "f324", ;; :match_stats_url_suffix "/en/scores/2016/540/MS020/match-stats", ;; :tourney_url_suffix "/en/scores/archive/wimbledon/540/2016/results", ;; :loser_player_id "e687", ;; :loser_tiebreaks_won "0", ;; :round_order "5", ;; :winner_rating 1127.06735832767, ;; :tourney_round_name "Round of 32", ;; :match_id "2016-540-f324-e687", ;; :winner_name "Roger Federer", ;; :winner_games_won 18, ;; :loser_rating 603.2729932046952, ;; :winner_tiebreaks_won "0"} ;; {:tourney_slug "marseille", ;; :loser_slug "marcus-willis", ;; :winner_sets_won 2, ;; :match_score_tiebreaks "76(7) 76(2)", ;; :loser_sets_won 0, ;; :loser_games_won 12, ;; :tourney_year_id "2015-496", ;; :tourney_order "14", ;; :winner_seed "5", ;; :loser_seed "", ;; :winner_slug "pierre-hugues-herbert", ;; :match_order "5", ;; :loser_name "Marcus Willis", ;; :winner_player_id "h996", ;; :match_stats_url_suffix "/en/scores/2015/496/QS019/match-stats", ;; :tourney_url_suffix "/en/scores/archive/marseille/496/2015/results", ;; :loser_player_id "w521", ;; :loser_tiebreaks_won "0", ;; :round_order "8", ;; :winner_rating 587.634881154115, ;; :tourney_round_name "1st Round Qualifying", ;; :match_id "2015-496-h996-w521", ;; :winner_name "Pierre-Hugues Herbert", ;; :winner_games_won 14, ;; :loser_rating 392.63430666689504, ;; :winner_tiebreaks_won "2"}]) ;; ({:tourney_slug "eastbourne", ;; :loser_slug "guido-pella", ;; :winner_sets_won 2, ;; :match_score_tiebreaks "36 61 63", ;; :loser_sets_won 1, ;; :loser_games_won 10, ;; :tourney_year_id "2016-741", ;; :tourney_order "38", ;; :winner_seed "", ;; :loser_seed "13", ;; :winner_slug "benjamin-becker", ;; :match_order "13", ;; :loser_name "Guido Pella", ;; :winner_player_id "b896", ;; :match_stats_url_suffix "/en/scores/2016/741/MS021/match-stats", ;; :tourney_url_suffix "/en/scores/archive/eastbourne/741/2016/results", ;; :loser_player_id "pc11", ;; :loser_tiebreaks_won "0", ;; :round_order "5", ;; :winner_rating 638.7921462877312, ;; :tourney_round_name "Round of 32", ;; :match_id "2016-741-b896-pc11", ;; :winner_name "Benjamin Becker", ;; :winner_games_won 15, ;; :loser_rating 643.0580458561587, ;; :winner_tiebreaks_won "0"} ;; [{:tourney_slug "eastbourne", ;; :loser_slug "benjamin-becker", ;; :winner_sets_won 2, ;; :match_score_tiebreaks "63 26 64", ;; :loser_sets_won 1, ;; :loser_games_won 13, ;; :tourney_year_id "2016-741", ;; :tourney_order "38", ;; :winner_seed "", ;; :loser_seed "", ;; :winner_slug "dudi-sela", ;; :match_order "8", ;; :loser_name "Benjamin Becker", ;; :winner_player_id "sc56", ;; :match_stats_url_suffix "/en/scores/2016/741/MS010/match-stats", ;; :tourney_url_suffix "/en/scores/archive/eastbourne/741/2016/results", ;; :loser_player_id "b896", ;; :loser_tiebreaks_won "0", ;; :round_order "4", ;; :winner_rating 560.0126295247488, ;; :tourney_round_name "Round of 16", ;; :match_id "2016-741-sc56-b896", ;; :winner_name "Dudi Sela", ;; :winner_games_won 14, ;; :loser_rating 661.2518854789847, ;; :winner_tiebreaks_won "0"} ;; {:tourney_slug "roland-garros", ;; :loser_slug "diego-schwartzman", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "62 36 62 63", ;; :loser_sets_won 1, ;; :loser_games_won 13, ;; :tourney_year_id "2016-520", ;; :tourney_order "33", ;; :winner_seed "", ;; :loser_seed "", ;; :winner_slug "guido-pella", ;; :match_order "59", ;; :loser_name "Diego Schwartzman", ;; :winner_player_id "pc11", ;; :match_stats_url_suffix "/en/scores/2016/520/MS105/match-stats", ;; :tourney_url_suffix "/en/scores/archive/roland-garros/520/2016/results", ;; :loser_player_id "sm37", ;; :loser_tiebreaks_won "0", ;; :round_order "7", ;; :winner_rating 623.4399911176613, ;; :tourney_round_name "Round of 128", ;; :match_id "2016-520-pc11-sm37", ;; :winner_name "Guido Pella", ;; :winner_games_won 21, ;; :loser_rating 665.6978632936225, ;; :winner_tiebreaks_won "0"}])])
1434
(ns packt-clj.tennis (:require [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.math.numeric-tower :as math] [semantic-csv.core :as sc])) ;;; The first part of this file comes from the tennis_history.clj ;;; from Exercise 5.03. (defn match-probability [player-1-rating player-2-rating] (/ 1 (+ 1 (math/expt 10 (/ (- player-2-rating player-1-rating) 400))))) (defn recalculate-rating [k previous-rating expected-outcome real-outcome] (+ previous-rating (* k (- real-outcome expected-outcome)))) (defn elo-db [csv k] (with-open [r (io/reader csv)] (->> (csv/read-csv r) sc/mappify (sc/cast-with {:winner_sets_won sc/->int :loser_sets_won sc/->int :winner_games_won sc/->int :loser_games_won sc/->int}) (reduce (fn [{:keys [players] :as acc} {:keys [_winner_name winner_slug _loser_name loser_slug] :as match}] (let [winner-rating (get players winner_slug 400) loser-rating (get players loser_slug 400) winner-probability (match-probability winner-rating loser-rating) loser-probability (- 1 winner-probability)] (-> acc (assoc-in [:players winner_slug] (recalculate-rating k winner-rating winner-probability 1)) (assoc-in [:players loser_slug] (recalculate-rating k loser-rating loser-probability 0)) (update :matches (fn [ms] (conj ms (assoc match :winner_rating winner-rating :loser_rating loser-rating))))))) {:players {} :matches []}) :matches reverse))) (def matches (elo-db "match_scores_1991-2016_unindexed_csv.csv" 35)) (defn player-in-match? [{:keys [winner_slug loser_slug]} player-slug] ((hash-set winner_slug loser_slug) player-slug)) (defn match-tree-by-player [matches player-slug] (lazy-seq (cond (empty? matches) '() (player-in-match? (first matches) player-slug) (cons (first matches) (cons [(match-tree-by-player (rest matches) (:winner_slug (first matches))) (match-tree-by-player (rest matches) (:loser_slug (first matches)))] '())) :else (match-tree-by-player (rest matches) player-slug)))) (def federer (match-tree-by-player matches "roger-federer")) ;;; The new functions start here (defn take-matches [limit tree] (cond (zero? limit) '() (= 1 limit) (first tree) :else (cons (first tree) (cons [(take-matches (dec limit) (first (second tree))) (take-matches (dec limit) (second (second tree)))] '())))) (take-matches 0 federer) ;; => () (select-keys (take-matches 1 federer) [:winner_slug :loser_slug]) ;; => {:winner_slug "roger-federer", :loser_slug "guido-pella"} (take-matches 3 federer) ;; => ({:tourney_slug "wimbledon", ;; :loser_slug "guido-pella", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "76(5) 76(3) 63", ;; :loser_sets_won 0, ;; :loser_games_won 15, ;; :tourney_year_id "2016-540", ;; :tourney_order "<NAME>9", ;; :winner_seed "3", ;; :loser_seed "", ;; :winner_slug "roger-federer", ;; :match_order "3", ;; :loser_name "<NAME>", ;; :winner_player_id "f324", ;; :match_stats_url_suffix "/en/scores/2016/540/MS080/match-stats", ;; :tourney_url_suffix "/en/scores/archive/wimbledon/540/2016/results", ;; :loser_player_id "pc11", ;; :loser_tiebreaks_won "0", ;; :round_order "7", ;; :winner_rating 1129.178155312036, ;; :tourney_round_name "Round of 128", ;; :match_id "2016-540-f324-pc11", ;; :winner_name "<NAME>", ;; :winner_games_won 20, ;; :loser_rating 625.3431873490674, ;; :winner_tiebreaks_won "2"} ;; [({:tourney_slug "wimbledon", ;; :loser_slug "marcus-willis", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "60 63 64", ;; :loser_sets_won 0, ;; :loser_games_won 7, ;; :tourney_year_id "2016-540", ;; :tourney_order "39", ;; :winner_seed "3", ;; :loser_seed "Q", ;; :winner_slug "roger-federer", ;; :match_order "3", ;; :loser_name "<NAME>", ;; :winner_player_id "f324", ;; :match_stats_url_suffix "/en/scores/2016/540/MS040/match-stats", ;; :tourney_url_suffix "/en/scores/archive/wimbledon/540/2016/results", ;; :loser_player_id "w521", ;; :loser_tiebreaks_won "0", ;; :round_order "6", ;; :winner_rating 1128.703390288765, ;; :tourney_round_name "Round of 64", ;; :match_id "2016-540-f324-w521", ;; :winner_name "<NAME>", ;; :winner_games_won 18, ;; :loser_rating 384.0402195770708, ;; :winner_tiebreaks_won "0"} ;; [{:tourney_slug "wimbledon", ;; :loser_slug "daniel-evans", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "64 62 62", ;; :loser_sets_won 0, ;; :loser_games_won 8, ;; :tourney_year_id "2016-540", ;; :tourney_order "39", ;; :winner_seed "3", ;; :loser_seed "", ;; :winner_slug "roger-federer", ;; :match_order "3", ;; :loser_name "<NAME>", ;; :winner_player_id "f324", ;; :match_stats_url_suffix "/en/scores/2016/540/MS020/match-stats", ;; :tourney_url_suffix "/en/scores/archive/wimbledon/540/2016/results", ;; :loser_player_id "e687", ;; :loser_tiebreaks_won "0", ;; :round_order "5", ;; :winner_rating 1127.06735832767, ;; :tourney_round_name "Round of 32", ;; :match_id "2016-540-f324-e687", ;; :winner_name "<NAME>", ;; :winner_games_won 18, ;; :loser_rating 603.2729932046952, ;; :winner_tiebreaks_won "0"} ;; {:tourney_slug "marseille", ;; :loser_slug "marcus-willis", ;; :winner_sets_won 2, ;; :match_score_tiebreaks "76(7) 76(2)", ;; :loser_sets_won 0, ;; :loser_games_won 12, ;; :tourney_year_id "2015-496", ;; :tourney_order "14", ;; :winner_seed "5", ;; :loser_seed "", ;; :winner_slug "pi<NAME>-<NAME>-<NAME>", ;; :match_order "5", ;; :loser_name "<NAME>", ;; :winner_player_id "h996", ;; :match_stats_url_suffix "/en/scores/2015/496/QS019/match-stats", ;; :tourney_url_suffix "/en/scores/archive/marseille/496/2015/results", ;; :loser_player_id "w521", ;; :loser_tiebreaks_won "0", ;; :round_order "8", ;; :winner_rating 587.634881154115, ;; :tourney_round_name "1st Round Qualifying", ;; :match_id "2015-496-h996-w521", ;; :winner_name "<NAME>", ;; :winner_games_won 14, ;; :loser_rating 392.63430666689504, ;; :winner_tiebreaks_won "2"}]) ;; ({:tourney_slug "eastbourne", ;; :loser_slug "guido-pella", ;; :winner_sets_won 2, ;; :match_score_tiebreaks "36 61 63", ;; :loser_sets_won 1, ;; :loser_games_won 10, ;; :tourney_year_id "2016-741", ;; :tourney_order "38", ;; :winner_seed "", ;; :loser_seed "13", ;; :winner_slug "benjamin-becker", ;; :match_order "13", ;; :loser_name "<NAME>", ;; :winner_player_id "b896", ;; :match_stats_url_suffix "/en/scores/2016/741/MS021/match-stats", ;; :tourney_url_suffix "/en/scores/archive/eastbourne/741/2016/results", ;; :loser_player_id "pc11", ;; :loser_tiebreaks_won "0", ;; :round_order "5", ;; :winner_rating 638.7921462877312, ;; :tourney_round_name "Round of 32", ;; :match_id "2016-741-b896-pc11", ;; :winner_name "<NAME>", ;; :winner_games_won 15, ;; :loser_rating 643.0580458561587, ;; :winner_tiebreaks_won "0"} ;; [{:tourney_slug "eastbourne", ;; :loser_slug "benjamin-becker", ;; :winner_sets_won 2, ;; :match_score_tiebreaks "63 26 64", ;; :loser_sets_won 1, ;; :loser_games_won 13, ;; :tourney_year_id "2016-741", ;; :tourney_order "38", ;; :winner_seed "", ;; :loser_seed "", ;; :winner_slug "dudi-sela", ;; :match_order "8", ;; :loser_name "<NAME>", ;; :winner_player_id "sc56", ;; :match_stats_url_suffix "/en/scores/2016/741/MS010/match-stats", ;; :tourney_url_suffix "/en/scores/archive/eastbourne/741/2016/results", ;; :loser_player_id "b896", ;; :loser_tiebreaks_won "0", ;; :round_order "4", ;; :winner_rating 560.0126295247488, ;; :tourney_round_name "Round of 16", ;; :match_id "2016-741-sc56-b896", ;; :winner_name "<NAME>", ;; :winner_games_won 14, ;; :loser_rating 661.2518854789847, ;; :winner_tiebreaks_won "0"} ;; {:tourney_slug "roland-garros", ;; :loser_slug "diego-schwartzman", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "62 36 62 63", ;; :loser_sets_won 1, ;; :loser_games_won 13, ;; :tourney_year_id "2016-520", ;; :tourney_order "33", ;; :winner_seed "", ;; :loser_seed "", ;; :winner_slug "guido-pella", ;; :match_order "59", ;; :loser_name "<NAME>", ;; :winner_player_id "pc11", ;; :match_stats_url_suffix "/en/scores/2016/520/MS105/match-stats", ;; :tourney_url_suffix "/en/scores/archive/roland-garros/520/2016/results", ;; :loser_player_id "sm37", ;; :loser_tiebreaks_won "0", ;; :round_order "7", ;; :winner_rating 623.4399911176613, ;; :tourney_round_name "Round of 128", ;; :match_id "2016-520-pc11-sm37", ;; :winner_name "<NAME>", ;; :winner_games_won 21, ;; :loser_rating 665.6978632936225, ;; :winner_tiebreaks_won "0"}])])
true
(ns packt-clj.tennis (:require [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.math.numeric-tower :as math] [semantic-csv.core :as sc])) ;;; The first part of this file comes from the tennis_history.clj ;;; from Exercise 5.03. (defn match-probability [player-1-rating player-2-rating] (/ 1 (+ 1 (math/expt 10 (/ (- player-2-rating player-1-rating) 400))))) (defn recalculate-rating [k previous-rating expected-outcome real-outcome] (+ previous-rating (* k (- real-outcome expected-outcome)))) (defn elo-db [csv k] (with-open [r (io/reader csv)] (->> (csv/read-csv r) sc/mappify (sc/cast-with {:winner_sets_won sc/->int :loser_sets_won sc/->int :winner_games_won sc/->int :loser_games_won sc/->int}) (reduce (fn [{:keys [players] :as acc} {:keys [_winner_name winner_slug _loser_name loser_slug] :as match}] (let [winner-rating (get players winner_slug 400) loser-rating (get players loser_slug 400) winner-probability (match-probability winner-rating loser-rating) loser-probability (- 1 winner-probability)] (-> acc (assoc-in [:players winner_slug] (recalculate-rating k winner-rating winner-probability 1)) (assoc-in [:players loser_slug] (recalculate-rating k loser-rating loser-probability 0)) (update :matches (fn [ms] (conj ms (assoc match :winner_rating winner-rating :loser_rating loser-rating))))))) {:players {} :matches []}) :matches reverse))) (def matches (elo-db "match_scores_1991-2016_unindexed_csv.csv" 35)) (defn player-in-match? [{:keys [winner_slug loser_slug]} player-slug] ((hash-set winner_slug loser_slug) player-slug)) (defn match-tree-by-player [matches player-slug] (lazy-seq (cond (empty? matches) '() (player-in-match? (first matches) player-slug) (cons (first matches) (cons [(match-tree-by-player (rest matches) (:winner_slug (first matches))) (match-tree-by-player (rest matches) (:loser_slug (first matches)))] '())) :else (match-tree-by-player (rest matches) player-slug)))) (def federer (match-tree-by-player matches "roger-federer")) ;;; The new functions start here (defn take-matches [limit tree] (cond (zero? limit) '() (= 1 limit) (first tree) :else (cons (first tree) (cons [(take-matches (dec limit) (first (second tree))) (take-matches (dec limit) (second (second tree)))] '())))) (take-matches 0 federer) ;; => () (select-keys (take-matches 1 federer) [:winner_slug :loser_slug]) ;; => {:winner_slug "roger-federer", :loser_slug "guido-pella"} (take-matches 3 federer) ;; => ({:tourney_slug "wimbledon", ;; :loser_slug "guido-pella", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "76(5) 76(3) 63", ;; :loser_sets_won 0, ;; :loser_games_won 15, ;; :tourney_year_id "2016-540", ;; :tourney_order "PI:NAME:<NAME>END_PI9", ;; :winner_seed "3", ;; :loser_seed "", ;; :winner_slug "roger-federer", ;; :match_order "3", ;; :loser_name "PI:NAME:<NAME>END_PI", ;; :winner_player_id "f324", ;; :match_stats_url_suffix "/en/scores/2016/540/MS080/match-stats", ;; :tourney_url_suffix "/en/scores/archive/wimbledon/540/2016/results", ;; :loser_player_id "pc11", ;; :loser_tiebreaks_won "0", ;; :round_order "7", ;; :winner_rating 1129.178155312036, ;; :tourney_round_name "Round of 128", ;; :match_id "2016-540-f324-pc11", ;; :winner_name "PI:NAME:<NAME>END_PI", ;; :winner_games_won 20, ;; :loser_rating 625.3431873490674, ;; :winner_tiebreaks_won "2"} ;; [({:tourney_slug "wimbledon", ;; :loser_slug "marcus-willis", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "60 63 64", ;; :loser_sets_won 0, ;; :loser_games_won 7, ;; :tourney_year_id "2016-540", ;; :tourney_order "39", ;; :winner_seed "3", ;; :loser_seed "Q", ;; :winner_slug "roger-federer", ;; :match_order "3", ;; :loser_name "PI:NAME:<NAME>END_PI", ;; :winner_player_id "f324", ;; :match_stats_url_suffix "/en/scores/2016/540/MS040/match-stats", ;; :tourney_url_suffix "/en/scores/archive/wimbledon/540/2016/results", ;; :loser_player_id "w521", ;; :loser_tiebreaks_won "0", ;; :round_order "6", ;; :winner_rating 1128.703390288765, ;; :tourney_round_name "Round of 64", ;; :match_id "2016-540-f324-w521", ;; :winner_name "PI:NAME:<NAME>END_PI", ;; :winner_games_won 18, ;; :loser_rating 384.0402195770708, ;; :winner_tiebreaks_won "0"} ;; [{:tourney_slug "wimbledon", ;; :loser_slug "daniel-evans", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "64 62 62", ;; :loser_sets_won 0, ;; :loser_games_won 8, ;; :tourney_year_id "2016-540", ;; :tourney_order "39", ;; :winner_seed "3", ;; :loser_seed "", ;; :winner_slug "roger-federer", ;; :match_order "3", ;; :loser_name "PI:NAME:<NAME>END_PI", ;; :winner_player_id "f324", ;; :match_stats_url_suffix "/en/scores/2016/540/MS020/match-stats", ;; :tourney_url_suffix "/en/scores/archive/wimbledon/540/2016/results", ;; :loser_player_id "e687", ;; :loser_tiebreaks_won "0", ;; :round_order "5", ;; :winner_rating 1127.06735832767, ;; :tourney_round_name "Round of 32", ;; :match_id "2016-540-f324-e687", ;; :winner_name "PI:NAME:<NAME>END_PI", ;; :winner_games_won 18, ;; :loser_rating 603.2729932046952, ;; :winner_tiebreaks_won "0"} ;; {:tourney_slug "marseille", ;; :loser_slug "marcus-willis", ;; :winner_sets_won 2, ;; :match_score_tiebreaks "76(7) 76(2)", ;; :loser_sets_won 0, ;; :loser_games_won 12, ;; :tourney_year_id "2015-496", ;; :tourney_order "14", ;; :winner_seed "5", ;; :loser_seed "", ;; :winner_slug "piPI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI", ;; :match_order "5", ;; :loser_name "PI:NAME:<NAME>END_PI", ;; :winner_player_id "h996", ;; :match_stats_url_suffix "/en/scores/2015/496/QS019/match-stats", ;; :tourney_url_suffix "/en/scores/archive/marseille/496/2015/results", ;; :loser_player_id "w521", ;; :loser_tiebreaks_won "0", ;; :round_order "8", ;; :winner_rating 587.634881154115, ;; :tourney_round_name "1st Round Qualifying", ;; :match_id "2015-496-h996-w521", ;; :winner_name "PI:NAME:<NAME>END_PI", ;; :winner_games_won 14, ;; :loser_rating 392.63430666689504, ;; :winner_tiebreaks_won "2"}]) ;; ({:tourney_slug "eastbourne", ;; :loser_slug "guido-pella", ;; :winner_sets_won 2, ;; :match_score_tiebreaks "36 61 63", ;; :loser_sets_won 1, ;; :loser_games_won 10, ;; :tourney_year_id "2016-741", ;; :tourney_order "38", ;; :winner_seed "", ;; :loser_seed "13", ;; :winner_slug "benjamin-becker", ;; :match_order "13", ;; :loser_name "PI:NAME:<NAME>END_PI", ;; :winner_player_id "b896", ;; :match_stats_url_suffix "/en/scores/2016/741/MS021/match-stats", ;; :tourney_url_suffix "/en/scores/archive/eastbourne/741/2016/results", ;; :loser_player_id "pc11", ;; :loser_tiebreaks_won "0", ;; :round_order "5", ;; :winner_rating 638.7921462877312, ;; :tourney_round_name "Round of 32", ;; :match_id "2016-741-b896-pc11", ;; :winner_name "PI:NAME:<NAME>END_PI", ;; :winner_games_won 15, ;; :loser_rating 643.0580458561587, ;; :winner_tiebreaks_won "0"} ;; [{:tourney_slug "eastbourne", ;; :loser_slug "benjamin-becker", ;; :winner_sets_won 2, ;; :match_score_tiebreaks "63 26 64", ;; :loser_sets_won 1, ;; :loser_games_won 13, ;; :tourney_year_id "2016-741", ;; :tourney_order "38", ;; :winner_seed "", ;; :loser_seed "", ;; :winner_slug "dudi-sela", ;; :match_order "8", ;; :loser_name "PI:NAME:<NAME>END_PI", ;; :winner_player_id "sc56", ;; :match_stats_url_suffix "/en/scores/2016/741/MS010/match-stats", ;; :tourney_url_suffix "/en/scores/archive/eastbourne/741/2016/results", ;; :loser_player_id "b896", ;; :loser_tiebreaks_won "0", ;; :round_order "4", ;; :winner_rating 560.0126295247488, ;; :tourney_round_name "Round of 16", ;; :match_id "2016-741-sc56-b896", ;; :winner_name "PI:NAME:<NAME>END_PI", ;; :winner_games_won 14, ;; :loser_rating 661.2518854789847, ;; :winner_tiebreaks_won "0"} ;; {:tourney_slug "roland-garros", ;; :loser_slug "diego-schwartzman", ;; :winner_sets_won 3, ;; :match_score_tiebreaks "62 36 62 63", ;; :loser_sets_won 1, ;; :loser_games_won 13, ;; :tourney_year_id "2016-520", ;; :tourney_order "33", ;; :winner_seed "", ;; :loser_seed "", ;; :winner_slug "guido-pella", ;; :match_order "59", ;; :loser_name "PI:NAME:<NAME>END_PI", ;; :winner_player_id "pc11", ;; :match_stats_url_suffix "/en/scores/2016/520/MS105/match-stats", ;; :tourney_url_suffix "/en/scores/archive/roland-garros/520/2016/results", ;; :loser_player_id "sm37", ;; :loser_tiebreaks_won "0", ;; :round_order "7", ;; :winner_rating 623.4399911176613, ;; :tourney_round_name "Round of 128", ;; :match_id "2016-520-pc11-sm37", ;; :winner_name "PI:NAME:<NAME>END_PI", ;; :winner_games_won 21, ;; :loser_rating 665.6978632936225, ;; :winner_tiebreaks_won "0"}])])
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998738765716553, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "tice, or any other, from this software.\n\n; Author: Frantisek Sodomka\n\n\n(ns clojure.test-clojure.other-functions\n (:us", "end": 491, "score": 0.9998877048492432, "start": 474, "tag": "NAME", "value": "Frantisek Sodomka" } ]
ThirdParty/clojure-1.1.0/test/clojure/test_clojure/other_functions.clj
allertonm/Couverjure
3
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Author: Frantisek Sodomka (ns clojure.test-clojure.other-functions (:use clojure.test)) ; http://clojure.org/other_functions ; [= not= (tests in data_structures.clj and elsewhere)] (deftest test-identity ; exactly 1 argument needed (is (thrown? IllegalArgumentException (identity))) (is (thrown? IllegalArgumentException (identity 1 2))) (are [x] (= (identity x) x) nil false true 0 42 0.0 3.14 2/3 0M 1M \c "" "abc" 'sym :kw () '(1 2) [] [1 2] {} {:a 1 :b 2} #{} #{1 2} ) ; evaluation (are [x y] (= (identity x) y) (+ 1 2) 3 (> 5 0) true )) ; time assert comment doc ; partial ; comp ; complement ; constantly ; Printing ; pr prn print println newline ; pr-str prn-str print-str println-str [with-out-str (vars.clj)] ; Regex Support ; re-matcher re-find re-matches re-groups re-seq
96526
; 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.other-functions (:use clojure.test)) ; http://clojure.org/other_functions ; [= not= (tests in data_structures.clj and elsewhere)] (deftest test-identity ; exactly 1 argument needed (is (thrown? IllegalArgumentException (identity))) (is (thrown? IllegalArgumentException (identity 1 2))) (are [x] (= (identity x) x) nil false true 0 42 0.0 3.14 2/3 0M 1M \c "" "abc" 'sym :kw () '(1 2) [] [1 2] {} {:a 1 :b 2} #{} #{1 2} ) ; evaluation (are [x y] (= (identity x) y) (+ 1 2) 3 (> 5 0) true )) ; time assert comment doc ; partial ; comp ; complement ; constantly ; Printing ; pr prn print println newline ; pr-str prn-str print-str println-str [with-out-str (vars.clj)] ; Regex Support ; re-matcher re-find re-matches re-groups re-seq
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.other-functions (:use clojure.test)) ; http://clojure.org/other_functions ; [= not= (tests in data_structures.clj and elsewhere)] (deftest test-identity ; exactly 1 argument needed (is (thrown? IllegalArgumentException (identity))) (is (thrown? IllegalArgumentException (identity 1 2))) (are [x] (= (identity x) x) nil false true 0 42 0.0 3.14 2/3 0M 1M \c "" "abc" 'sym :kw () '(1 2) [] [1 2] {} {:a 1 :b 2} #{} #{1 2} ) ; evaluation (are [x y] (= (identity x) y) (+ 1 2) 3 (> 5 0) true )) ; time assert comment doc ; partial ; comp ; complement ; constantly ; Printing ; pr prn print println newline ; pr-str prn-str print-str println-str [with-out-str (vars.clj)] ; Regex Support ; re-matcher re-find re-matches re-groups re-seq
[ { "context": "(ns ^{:author \"Bruno Bonacci (@BrunoBonacci)\"\n :doc\n \"\nLogging libra", "end": 28, "score": 0.9998576045036316, "start": 15, "tag": "NAME", "value": "Bruno Bonacci" }, { "context": "(ns ^{:author \"Bruno Bonacci (@BrunoBonacci)\"\n :doc\n \"\nLogging library designed to ", "end": 43, "score": 0.9996744990348816, "start": 29, "tag": "USERNAME", "value": "(@BrunoBonacci" }, { "context": "ore information, please visit: https://github.com/BrunoBonacci/mulog\n\"}\n com.brunobonacci.mulog\n (:require [com", "end": 1651, "score": 0.9991356730461121, "start": 1639, "tag": "USERNAME", "value": "BrunoBonacci" }, { "context": " own publishers please check\n https://github.com/BrunoBonacci/mulog#publishers\n\n \"\n ([config]\n (start-publi", "end": 4970, "score": 0.9822201728820801, "start": 4958, "tag": "USERNAME", "value": "BrunoBonacci" }, { "context": " :mulog/namespace \\\"your-ns\\\",\n ;; :app-name \\\"mulog-demo\\\",\n ;; :version \\\"0.1.0\\\",\n ;; :env \\\"local\\\"", "end": 8280, "score": 0.620111882686615, "start": 8270, "tag": "USERNAME", "value": "mulog-demo" } ]
mulog-core/src/com/brunobonacci/mulog.clj
updcon/mulog
0
(ns ^{:author "Bruno Bonacci (@BrunoBonacci)" :doc " Logging library designed to log data events instead of plain words. This namespace provides the core functions of ***μ/log***. The purpose of ***μ/log*** is provide the ability to generate events directly from your code. The instrumentation process is very simple and similar to add a traditional log line, but instead of logging a message which hardly anyone will ever read, your can log an event, a data point, with all the attributes and properties which make sense for that particular event and let the machine use it in a later time. ***μ/log*** provides the functions to instrument your code with minimal impact to performances (few nanoseconds), to buffer events and manage the overflow, the dispatching of the stored events to downstream systems where they can be processed, indexed, organized and queried to provide rich information (quantitative and qualitative) about your system. Once you start using event-based metrics you will not want to use traditional metrics any more. Additionally, ***μ/log*** offer the possibility to trace execution with a micro-tracing function called **μ/trace**. It provides in app distributed tracing capabilities with the same simplicity. The publisher sub-system makes extremely easy to write new publishers for new downstream system. ***μ/log*** manages the hard parts like: the buffering, the retries, the memory buffers and the publisher's state. It is often required only a dozen lines of code to write a new powerful custom publisher and use it in your system. For more information, please visit: https://github.com/BrunoBonacci/mulog "} com.brunobonacci.mulog (:require [com.brunobonacci.mulog.core :as core] [com.brunobonacci.mulog.utils :refer [defalias fast-map-merge thread-local-binding]] [com.brunobonacci.mulog.flakes :refer [flake]])) ;; create var alias in local namespace (defalias log* core/log*) (defmacro log "Event logging function. Given an event name and an (inline) sequence of event's attribute key/values, it enqueues the event in the the buffer and returns nil. Asynchronous process will take care to send the content of the buffer to the registered publishers. Use this function similarly to how you would use a message logging library to log important events, but rather than logging words, add data points. To log a new event this is the format: ``` clojure (μ/log event-name, key1 value1, key2 value2, ... keyN valueN) ``` Where: - `event-name` should be a keyword or string (preferably namespaced) - `key1 value1` is a key/value pair which provides additional information about the event. This can be used later to further refine your query of aggregate on. For example should you want to log the event of a your login, you could add: ``` clojure (μ/log ::user-logged, :user-id \"1234567\", :remote-ip \"1.2.3.4\", :auth-method :password-login) ``` Logging an event is extremely cheap (less 300 nanos), so you can log plenty without impacting the application performances. " [event-name & pairs] `(core/log* core/*default-logger* ~event-name (list :mulog/namespace ~(str *ns*) ~@pairs))) (defn start-publisher! "It loads and starts a event's publisher. Publisher, asynchronously, send events to downstream systems for processing, indexing, aggregation, alerting and querying. There are a number of built-in publishers you can use. Each publisher has its own configuration properties. For example to print the events to the standard output you can use the `:console` publisher The `start-publisher!` function returns a zero-argument function which can be used to stop the publisher. ``` clojure (def stop (μ/start-publisher! {:type :console})) (μ/log ::hi) ;; prints something like: ;; {:mulog/timestamp 1572709206048, :mulog/event-name :user/hi, :mulog/namespace \"user\"} ;; stop the publisher (stop) ``` The console publisher is really only intended for development purposes. There are other publishers which are more suitable for modern cloud-based, distributed systems. Another built-in publisher is the `:simple-file` publisher which just outputs events to a file in EDN format. ``` clojure (μ/start-publisher! {:type :simple-file :filename \"/tmp/mulog/events.log\"}) ``` You can also have multiple publishers defined in one place using the `:multi` publisher configuration: ``` clojure (μ/start-publisher! {:type :multi :publishers [{:type :console} {:type :simple-file :filename \"/tmp/disk1/mulog/events1.log\"} {:type :simple-file :filename \"/tmp/disk2/mulog/events2.log\"}]}) ``` which it will start all the defined publishers all at once. For more information about available publishers and their configuration as well as how to write your own publishers please check https://github.com/BrunoBonacci/mulog#publishers " ([config] (start-publisher! core/*default-logger* config)) ([logger {:keys [type publishers] :as config}] (if (= :multi type) ;; if multi publisher then start them all (->> publishers (map (partial core/start-publisher! logger)) (doall) ((fn [sf] (fn [] (run! #(%) sf))))) ;; otherwise start the single publisher (core/start-publisher! logger config)))) (defn global-context "Return the current value of the `global-context`. The global logging context is used to add properties which are valid for all subsequent log events. This is typically set once at the beginning of the process with information like the app-name, version, environment, the pid and other similar info." [] @core/global-context) (defn set-global-context! "Adding events which are rich in attributes and dimensions is extremely useful, however it is not easy to have all the attributes and dimensions at your disposal everywhere in the code. To get around this problem ***μ/log*** supports the use of context. There are two levels of context, a global level and a local one. The global context allows you to define properties and values which will be added to all the events logged afterwards. Typically, you will set the global context once in your main function at the starting of your application with properties which are valid for all events emitted by the process. Use `set-global-context!` to specify a given value, or `update-global-context!` with a update function to change some of the values. Examples of properties you should consider adding in the global context are `app-name`, `version`, `environment`, `process-id`, `host-ip`, `os-type`, `jvm-version` etc etc You might find some useful function in the `com.brunobonacci.mulog.utils` namespace. " [context] (reset! core/global-context context)) (defn update-global-context! "If you want to atomically update the global context, use `update-global-context!` similarly of how you would use `clojure.core/update` function. " [f & args] (apply swap! core/global-context f args)) (defn local-context "Returns the current `local-context`. The local context is local to the current thread, therefore all the subsequent call to log withing the given context will have the properties added as well. It is typically used to add information regarding the current processing in the current thread. For example who is the user issuing the request and so on." [] @core/local-context) (defmacro with-context " The (thread) local context it can be used to inject information about the current processing and all the events withing the scope of the context will inherit the properties and their values. For example the following line will contain all the properties of the *global context*, all the properties of the *local context* and all *inline properties*. ``` clojure (μ/with-context {:order \"abc123\"} (μ/log ::item-processed :item-id \"sku-123\" :qt 2)) ;; {:mulog/trace-id #mulog/flake \"4VIKxhMPB2eS0uc1EV9M9a5G7MYn3TMs\", ;; :mulog/event-name :your-ns/item-processed, ;; :mulog/timestamp 1572711123826, ;; :mulog/namespace \"your-ns\", ;; :app-name \"mulog-demo\", ;; :version \"0.1.0\", ;; :env \"local\", ;; :order \"abc123\", ;; :item-id \"sku-123\", ;; :qt 2} ``` The local context can be nested and ti will be inherited by all the ***μ/log*** calls within nested functions as long as they are in the same execution thread and which the scope of the block. " {:style/indent 1} [context-map & body] `(thread-local-binding [core/local-context (fast-map-merge @core/local-context ~context-map)] ~@body)) (defmacro trace "Traces the execution of an operation with the outcome and the time taken in nanoseconds. ### Track duration and outcome (errors) ***μ/trace*** will generate a trace object which can be understood by distributed tracing systems. It computes the duration in nanoseconds of the current trace/span and it links via the context to the parent trace and root traces. It tracks the `:outcome` of the evaluation of the `body`. If the evaluation it throws an exception `:outcome` will be `:error` otherwise it will be `:ok` The trace information will be tracked across function calls as long as the execution is in the same thread. If the execution spans more threads or more processes the context must be passed forward. Example of usage: ``` Clojure (u/trace ::availability [:product-id product-id, :order order-id, :user user-id] (product-availability product-id)) ``` Will produce an event as follow: ``` Clojure {:mulog/trace-id #mulog/flake \"4VIKxhMPB2eS0uc1EV9M9a5G7MYn3TMs\", :mulog/event-name :your-ns/availability, :mulog/timestamp 1586804894278, :mulog/duration 253303600, :mulog/namespace \"your-ns\", :mulog/outcome :ok, :mulog/root-trace #mulog/flake \"4VILF82cx_mFKlbKN-PUTezsRdsn8XOY\", :mulog/parent-trace #mulog/flake \"4VILL47ifjeHTaaG3kAWtZoELvk9AGY9\", :order \"34896-34556\", :product-id \"2345-23-545\", :user \"709-6567567\"} ``` Note the `:mulog/duration` and `:mulog/outcome` reporting respectively the duration of the execution of `product-availablity` in **nanoseconds** as well as the outcome (`:ok` or `:error`). If an exception is raised within the body an additional field is added `:exception` with the exception raised. The `:pairs` present in the vector are added in the event, but they are not propagated to nested traces, use `with-context` for that. Finally, `:mulog/trace-id`, `:mulog/parent-trace` and `:mulog/root-trace` identify respectively this trace, the outer trace wrapping this trace if present otherwise `nil` and the `:mulog/root-trace` is the outer-most trace with not parents. Keep in mind that *parent-trace* and *root-trace* might come from another system and they are propagated by the context. ### Capture evaluation result Sometimes it is useful to add to the trace pairs which come from the result of the body's evaluation. For example to capture the http response status or other valuable metrics from the response. ***μ/trace*** offers the possibility to pass a function to capture such info from the evaluation result. To achieve this, instead of passing a simple vector of pairs you need to provide a map which contains a `:capture` function in addition to the `:pairs`. The `capture` function is a function which takes one argument, *the result* of the evaluation and returns a map of key-value pairs which need to be added to the trace. The `capture` function will only run when the `:mulog/outcome :ok` Example of usage: ``` Clojure (u/trace ::availability {:pairs [:product-id product-id, :order order-id, :user user-id] :capture (fn [r] {:http-status (:status r) :etag (get-in r [:headers \"etag\"])}) (product-availability product-id)) ``` Will produce an event as follow: ``` Clojure {:mulog/trace-id #mulog/flake \"4VIKxhMPB2eS0uc1EV9M9a5G7MYn3TMs\", :mulog/event-name :your-ns/availability, :mulog/timestamp 1586804894278, :mulog/duration 253303600, :mulog/namespace \"your-ns\", :mulog/outcome :ok, :mulog/root-trace #mulog/flake \"4VILF82cx_mFKlbKN-PUTezsRdsn8XOY\", :mulog/parent-trace #mulog/flake \"4VILL47ifjeHTaaG3kAWtZoELvk9AGY9\", :order \"34896-34556\", :product-id \"2345-23-545\", :user \"709-6567567\", :http-status 200, :etag \"1dfb-2686-4cba2686fb8b1\"} ``` Note that in addition to the pairs like in the previous example this one contains `:http-status` and `:etag` which where extracted from the http response of `product-availability` evaluation. Should the execution of the `capture` function fail for any reason the pair will be added to this trace with `:mulog/capture :error` to signal the execution error. " {:style/indent 1 :arglists '([event-name [k1 v1, k2 v2, ... :as pairs] & body] [event-name {:keys [pairs capture]} & body])} [event-name details & body] `(let [details# ~details pairs# (if (map? details#) (:pairs details#) details#) capture# (if (map? details#) (:capture details#) nil) ;; :mulog/trace-id and :mulog/timestamp are created in here ;; because the log function is called after the evaluation of body ;; is completed, and the timestamp wouldn't be correct ptid# (get @core/local-context :mulog/parent-trace) tid# (flake) ts# (System/currentTimeMillis) ;; start timer to track body execution t0# (System/nanoTime)] ;; setting up the tracing re (with-context {:mulog/root-trace (or (get @core/local-context :mulog/root-trace) tid#) :mulog/parent-trace tid#} (try (let [r# (do ~@body)] (core/log-trace ~event-name tid# ptid# (- (System/nanoTime) t0#) ts# :ok pairs# ;; if there is something to capture form the evaluation result ;; then use the capture function (core/on-error {:mulog/capture :error} (when capture# (capture# r#)))) ;; return the body result r#) ;; If and exception occur, then log the error. (catch Exception x# (core/log-trace ~event-name tid# ptid# (- (System/nanoTime) t0#) ts# :error (list :exception x#) pairs#) (throw x#))))))
19480
(ns ^{:author "<NAME> (@BrunoBonacci)" :doc " Logging library designed to log data events instead of plain words. This namespace provides the core functions of ***μ/log***. The purpose of ***μ/log*** is provide the ability to generate events directly from your code. The instrumentation process is very simple and similar to add a traditional log line, but instead of logging a message which hardly anyone will ever read, your can log an event, a data point, with all the attributes and properties which make sense for that particular event and let the machine use it in a later time. ***μ/log*** provides the functions to instrument your code with minimal impact to performances (few nanoseconds), to buffer events and manage the overflow, the dispatching of the stored events to downstream systems where they can be processed, indexed, organized and queried to provide rich information (quantitative and qualitative) about your system. Once you start using event-based metrics you will not want to use traditional metrics any more. Additionally, ***μ/log*** offer the possibility to trace execution with a micro-tracing function called **μ/trace**. It provides in app distributed tracing capabilities with the same simplicity. The publisher sub-system makes extremely easy to write new publishers for new downstream system. ***μ/log*** manages the hard parts like: the buffering, the retries, the memory buffers and the publisher's state. It is often required only a dozen lines of code to write a new powerful custom publisher and use it in your system. For more information, please visit: https://github.com/BrunoBonacci/mulog "} com.brunobonacci.mulog (:require [com.brunobonacci.mulog.core :as core] [com.brunobonacci.mulog.utils :refer [defalias fast-map-merge thread-local-binding]] [com.brunobonacci.mulog.flakes :refer [flake]])) ;; create var alias in local namespace (defalias log* core/log*) (defmacro log "Event logging function. Given an event name and an (inline) sequence of event's attribute key/values, it enqueues the event in the the buffer and returns nil. Asynchronous process will take care to send the content of the buffer to the registered publishers. Use this function similarly to how you would use a message logging library to log important events, but rather than logging words, add data points. To log a new event this is the format: ``` clojure (μ/log event-name, key1 value1, key2 value2, ... keyN valueN) ``` Where: - `event-name` should be a keyword or string (preferably namespaced) - `key1 value1` is a key/value pair which provides additional information about the event. This can be used later to further refine your query of aggregate on. For example should you want to log the event of a your login, you could add: ``` clojure (μ/log ::user-logged, :user-id \"1234567\", :remote-ip \"1.2.3.4\", :auth-method :password-login) ``` Logging an event is extremely cheap (less 300 nanos), so you can log plenty without impacting the application performances. " [event-name & pairs] `(core/log* core/*default-logger* ~event-name (list :mulog/namespace ~(str *ns*) ~@pairs))) (defn start-publisher! "It loads and starts a event's publisher. Publisher, asynchronously, send events to downstream systems for processing, indexing, aggregation, alerting and querying. There are a number of built-in publishers you can use. Each publisher has its own configuration properties. For example to print the events to the standard output you can use the `:console` publisher The `start-publisher!` function returns a zero-argument function which can be used to stop the publisher. ``` clojure (def stop (μ/start-publisher! {:type :console})) (μ/log ::hi) ;; prints something like: ;; {:mulog/timestamp 1572709206048, :mulog/event-name :user/hi, :mulog/namespace \"user\"} ;; stop the publisher (stop) ``` The console publisher is really only intended for development purposes. There are other publishers which are more suitable for modern cloud-based, distributed systems. Another built-in publisher is the `:simple-file` publisher which just outputs events to a file in EDN format. ``` clojure (μ/start-publisher! {:type :simple-file :filename \"/tmp/mulog/events.log\"}) ``` You can also have multiple publishers defined in one place using the `:multi` publisher configuration: ``` clojure (μ/start-publisher! {:type :multi :publishers [{:type :console} {:type :simple-file :filename \"/tmp/disk1/mulog/events1.log\"} {:type :simple-file :filename \"/tmp/disk2/mulog/events2.log\"}]}) ``` which it will start all the defined publishers all at once. For more information about available publishers and their configuration as well as how to write your own publishers please check https://github.com/BrunoBonacci/mulog#publishers " ([config] (start-publisher! core/*default-logger* config)) ([logger {:keys [type publishers] :as config}] (if (= :multi type) ;; if multi publisher then start them all (->> publishers (map (partial core/start-publisher! logger)) (doall) ((fn [sf] (fn [] (run! #(%) sf))))) ;; otherwise start the single publisher (core/start-publisher! logger config)))) (defn global-context "Return the current value of the `global-context`. The global logging context is used to add properties which are valid for all subsequent log events. This is typically set once at the beginning of the process with information like the app-name, version, environment, the pid and other similar info." [] @core/global-context) (defn set-global-context! "Adding events which are rich in attributes and dimensions is extremely useful, however it is not easy to have all the attributes and dimensions at your disposal everywhere in the code. To get around this problem ***μ/log*** supports the use of context. There are two levels of context, a global level and a local one. The global context allows you to define properties and values which will be added to all the events logged afterwards. Typically, you will set the global context once in your main function at the starting of your application with properties which are valid for all events emitted by the process. Use `set-global-context!` to specify a given value, or `update-global-context!` with a update function to change some of the values. Examples of properties you should consider adding in the global context are `app-name`, `version`, `environment`, `process-id`, `host-ip`, `os-type`, `jvm-version` etc etc You might find some useful function in the `com.brunobonacci.mulog.utils` namespace. " [context] (reset! core/global-context context)) (defn update-global-context! "If you want to atomically update the global context, use `update-global-context!` similarly of how you would use `clojure.core/update` function. " [f & args] (apply swap! core/global-context f args)) (defn local-context "Returns the current `local-context`. The local context is local to the current thread, therefore all the subsequent call to log withing the given context will have the properties added as well. It is typically used to add information regarding the current processing in the current thread. For example who is the user issuing the request and so on." [] @core/local-context) (defmacro with-context " The (thread) local context it can be used to inject information about the current processing and all the events withing the scope of the context will inherit the properties and their values. For example the following line will contain all the properties of the *global context*, all the properties of the *local context* and all *inline properties*. ``` clojure (μ/with-context {:order \"abc123\"} (μ/log ::item-processed :item-id \"sku-123\" :qt 2)) ;; {:mulog/trace-id #mulog/flake \"4VIKxhMPB2eS0uc1EV9M9a5G7MYn3TMs\", ;; :mulog/event-name :your-ns/item-processed, ;; :mulog/timestamp 1572711123826, ;; :mulog/namespace \"your-ns\", ;; :app-name \"mulog-demo\", ;; :version \"0.1.0\", ;; :env \"local\", ;; :order \"abc123\", ;; :item-id \"sku-123\", ;; :qt 2} ``` The local context can be nested and ti will be inherited by all the ***μ/log*** calls within nested functions as long as they are in the same execution thread and which the scope of the block. " {:style/indent 1} [context-map & body] `(thread-local-binding [core/local-context (fast-map-merge @core/local-context ~context-map)] ~@body)) (defmacro trace "Traces the execution of an operation with the outcome and the time taken in nanoseconds. ### Track duration and outcome (errors) ***μ/trace*** will generate a trace object which can be understood by distributed tracing systems. It computes the duration in nanoseconds of the current trace/span and it links via the context to the parent trace and root traces. It tracks the `:outcome` of the evaluation of the `body`. If the evaluation it throws an exception `:outcome` will be `:error` otherwise it will be `:ok` The trace information will be tracked across function calls as long as the execution is in the same thread. If the execution spans more threads or more processes the context must be passed forward. Example of usage: ``` Clojure (u/trace ::availability [:product-id product-id, :order order-id, :user user-id] (product-availability product-id)) ``` Will produce an event as follow: ``` Clojure {:mulog/trace-id #mulog/flake \"4VIKxhMPB2eS0uc1EV9M9a5G7MYn3TMs\", :mulog/event-name :your-ns/availability, :mulog/timestamp 1586804894278, :mulog/duration 253303600, :mulog/namespace \"your-ns\", :mulog/outcome :ok, :mulog/root-trace #mulog/flake \"4VILF82cx_mFKlbKN-PUTezsRdsn8XOY\", :mulog/parent-trace #mulog/flake \"4VILL47ifjeHTaaG3kAWtZoELvk9AGY9\", :order \"34896-34556\", :product-id \"2345-23-545\", :user \"709-6567567\"} ``` Note the `:mulog/duration` and `:mulog/outcome` reporting respectively the duration of the execution of `product-availablity` in **nanoseconds** as well as the outcome (`:ok` or `:error`). If an exception is raised within the body an additional field is added `:exception` with the exception raised. The `:pairs` present in the vector are added in the event, but they are not propagated to nested traces, use `with-context` for that. Finally, `:mulog/trace-id`, `:mulog/parent-trace` and `:mulog/root-trace` identify respectively this trace, the outer trace wrapping this trace if present otherwise `nil` and the `:mulog/root-trace` is the outer-most trace with not parents. Keep in mind that *parent-trace* and *root-trace* might come from another system and they are propagated by the context. ### Capture evaluation result Sometimes it is useful to add to the trace pairs which come from the result of the body's evaluation. For example to capture the http response status or other valuable metrics from the response. ***μ/trace*** offers the possibility to pass a function to capture such info from the evaluation result. To achieve this, instead of passing a simple vector of pairs you need to provide a map which contains a `:capture` function in addition to the `:pairs`. The `capture` function is a function which takes one argument, *the result* of the evaluation and returns a map of key-value pairs which need to be added to the trace. The `capture` function will only run when the `:mulog/outcome :ok` Example of usage: ``` Clojure (u/trace ::availability {:pairs [:product-id product-id, :order order-id, :user user-id] :capture (fn [r] {:http-status (:status r) :etag (get-in r [:headers \"etag\"])}) (product-availability product-id)) ``` Will produce an event as follow: ``` Clojure {:mulog/trace-id #mulog/flake \"4VIKxhMPB2eS0uc1EV9M9a5G7MYn3TMs\", :mulog/event-name :your-ns/availability, :mulog/timestamp 1586804894278, :mulog/duration 253303600, :mulog/namespace \"your-ns\", :mulog/outcome :ok, :mulog/root-trace #mulog/flake \"4VILF82cx_mFKlbKN-PUTezsRdsn8XOY\", :mulog/parent-trace #mulog/flake \"4VILL47ifjeHTaaG3kAWtZoELvk9AGY9\", :order \"34896-34556\", :product-id \"2345-23-545\", :user \"709-6567567\", :http-status 200, :etag \"1dfb-2686-4cba2686fb8b1\"} ``` Note that in addition to the pairs like in the previous example this one contains `:http-status` and `:etag` which where extracted from the http response of `product-availability` evaluation. Should the execution of the `capture` function fail for any reason the pair will be added to this trace with `:mulog/capture :error` to signal the execution error. " {:style/indent 1 :arglists '([event-name [k1 v1, k2 v2, ... :as pairs] & body] [event-name {:keys [pairs capture]} & body])} [event-name details & body] `(let [details# ~details pairs# (if (map? details#) (:pairs details#) details#) capture# (if (map? details#) (:capture details#) nil) ;; :mulog/trace-id and :mulog/timestamp are created in here ;; because the log function is called after the evaluation of body ;; is completed, and the timestamp wouldn't be correct ptid# (get @core/local-context :mulog/parent-trace) tid# (flake) ts# (System/currentTimeMillis) ;; start timer to track body execution t0# (System/nanoTime)] ;; setting up the tracing re (with-context {:mulog/root-trace (or (get @core/local-context :mulog/root-trace) tid#) :mulog/parent-trace tid#} (try (let [r# (do ~@body)] (core/log-trace ~event-name tid# ptid# (- (System/nanoTime) t0#) ts# :ok pairs# ;; if there is something to capture form the evaluation result ;; then use the capture function (core/on-error {:mulog/capture :error} (when capture# (capture# r#)))) ;; return the body result r#) ;; If and exception occur, then log the error. (catch Exception x# (core/log-trace ~event-name tid# ptid# (- (System/nanoTime) t0#) ts# :error (list :exception x#) pairs#) (throw x#))))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI (@BrunoBonacci)" :doc " Logging library designed to log data events instead of plain words. This namespace provides the core functions of ***μ/log***. The purpose of ***μ/log*** is provide the ability to generate events directly from your code. The instrumentation process is very simple and similar to add a traditional log line, but instead of logging a message which hardly anyone will ever read, your can log an event, a data point, with all the attributes and properties which make sense for that particular event and let the machine use it in a later time. ***μ/log*** provides the functions to instrument your code with minimal impact to performances (few nanoseconds), to buffer events and manage the overflow, the dispatching of the stored events to downstream systems where they can be processed, indexed, organized and queried to provide rich information (quantitative and qualitative) about your system. Once you start using event-based metrics you will not want to use traditional metrics any more. Additionally, ***μ/log*** offer the possibility to trace execution with a micro-tracing function called **μ/trace**. It provides in app distributed tracing capabilities with the same simplicity. The publisher sub-system makes extremely easy to write new publishers for new downstream system. ***μ/log*** manages the hard parts like: the buffering, the retries, the memory buffers and the publisher's state. It is often required only a dozen lines of code to write a new powerful custom publisher and use it in your system. For more information, please visit: https://github.com/BrunoBonacci/mulog "} com.brunobonacci.mulog (:require [com.brunobonacci.mulog.core :as core] [com.brunobonacci.mulog.utils :refer [defalias fast-map-merge thread-local-binding]] [com.brunobonacci.mulog.flakes :refer [flake]])) ;; create var alias in local namespace (defalias log* core/log*) (defmacro log "Event logging function. Given an event name and an (inline) sequence of event's attribute key/values, it enqueues the event in the the buffer and returns nil. Asynchronous process will take care to send the content of the buffer to the registered publishers. Use this function similarly to how you would use a message logging library to log important events, but rather than logging words, add data points. To log a new event this is the format: ``` clojure (μ/log event-name, key1 value1, key2 value2, ... keyN valueN) ``` Where: - `event-name` should be a keyword or string (preferably namespaced) - `key1 value1` is a key/value pair which provides additional information about the event. This can be used later to further refine your query of aggregate on. For example should you want to log the event of a your login, you could add: ``` clojure (μ/log ::user-logged, :user-id \"1234567\", :remote-ip \"1.2.3.4\", :auth-method :password-login) ``` Logging an event is extremely cheap (less 300 nanos), so you can log plenty without impacting the application performances. " [event-name & pairs] `(core/log* core/*default-logger* ~event-name (list :mulog/namespace ~(str *ns*) ~@pairs))) (defn start-publisher! "It loads and starts a event's publisher. Publisher, asynchronously, send events to downstream systems for processing, indexing, aggregation, alerting and querying. There are a number of built-in publishers you can use. Each publisher has its own configuration properties. For example to print the events to the standard output you can use the `:console` publisher The `start-publisher!` function returns a zero-argument function which can be used to stop the publisher. ``` clojure (def stop (μ/start-publisher! {:type :console})) (μ/log ::hi) ;; prints something like: ;; {:mulog/timestamp 1572709206048, :mulog/event-name :user/hi, :mulog/namespace \"user\"} ;; stop the publisher (stop) ``` The console publisher is really only intended for development purposes. There are other publishers which are more suitable for modern cloud-based, distributed systems. Another built-in publisher is the `:simple-file` publisher which just outputs events to a file in EDN format. ``` clojure (μ/start-publisher! {:type :simple-file :filename \"/tmp/mulog/events.log\"}) ``` You can also have multiple publishers defined in one place using the `:multi` publisher configuration: ``` clojure (μ/start-publisher! {:type :multi :publishers [{:type :console} {:type :simple-file :filename \"/tmp/disk1/mulog/events1.log\"} {:type :simple-file :filename \"/tmp/disk2/mulog/events2.log\"}]}) ``` which it will start all the defined publishers all at once. For more information about available publishers and their configuration as well as how to write your own publishers please check https://github.com/BrunoBonacci/mulog#publishers " ([config] (start-publisher! core/*default-logger* config)) ([logger {:keys [type publishers] :as config}] (if (= :multi type) ;; if multi publisher then start them all (->> publishers (map (partial core/start-publisher! logger)) (doall) ((fn [sf] (fn [] (run! #(%) sf))))) ;; otherwise start the single publisher (core/start-publisher! logger config)))) (defn global-context "Return the current value of the `global-context`. The global logging context is used to add properties which are valid for all subsequent log events. This is typically set once at the beginning of the process with information like the app-name, version, environment, the pid and other similar info." [] @core/global-context) (defn set-global-context! "Adding events which are rich in attributes and dimensions is extremely useful, however it is not easy to have all the attributes and dimensions at your disposal everywhere in the code. To get around this problem ***μ/log*** supports the use of context. There are two levels of context, a global level and a local one. The global context allows you to define properties and values which will be added to all the events logged afterwards. Typically, you will set the global context once in your main function at the starting of your application with properties which are valid for all events emitted by the process. Use `set-global-context!` to specify a given value, or `update-global-context!` with a update function to change some of the values. Examples of properties you should consider adding in the global context are `app-name`, `version`, `environment`, `process-id`, `host-ip`, `os-type`, `jvm-version` etc etc You might find some useful function in the `com.brunobonacci.mulog.utils` namespace. " [context] (reset! core/global-context context)) (defn update-global-context! "If you want to atomically update the global context, use `update-global-context!` similarly of how you would use `clojure.core/update` function. " [f & args] (apply swap! core/global-context f args)) (defn local-context "Returns the current `local-context`. The local context is local to the current thread, therefore all the subsequent call to log withing the given context will have the properties added as well. It is typically used to add information regarding the current processing in the current thread. For example who is the user issuing the request and so on." [] @core/local-context) (defmacro with-context " The (thread) local context it can be used to inject information about the current processing and all the events withing the scope of the context will inherit the properties and their values. For example the following line will contain all the properties of the *global context*, all the properties of the *local context* and all *inline properties*. ``` clojure (μ/with-context {:order \"abc123\"} (μ/log ::item-processed :item-id \"sku-123\" :qt 2)) ;; {:mulog/trace-id #mulog/flake \"4VIKxhMPB2eS0uc1EV9M9a5G7MYn3TMs\", ;; :mulog/event-name :your-ns/item-processed, ;; :mulog/timestamp 1572711123826, ;; :mulog/namespace \"your-ns\", ;; :app-name \"mulog-demo\", ;; :version \"0.1.0\", ;; :env \"local\", ;; :order \"abc123\", ;; :item-id \"sku-123\", ;; :qt 2} ``` The local context can be nested and ti will be inherited by all the ***μ/log*** calls within nested functions as long as they are in the same execution thread and which the scope of the block. " {:style/indent 1} [context-map & body] `(thread-local-binding [core/local-context (fast-map-merge @core/local-context ~context-map)] ~@body)) (defmacro trace "Traces the execution of an operation with the outcome and the time taken in nanoseconds. ### Track duration and outcome (errors) ***μ/trace*** will generate a trace object which can be understood by distributed tracing systems. It computes the duration in nanoseconds of the current trace/span and it links via the context to the parent trace and root traces. It tracks the `:outcome` of the evaluation of the `body`. If the evaluation it throws an exception `:outcome` will be `:error` otherwise it will be `:ok` The trace information will be tracked across function calls as long as the execution is in the same thread. If the execution spans more threads or more processes the context must be passed forward. Example of usage: ``` Clojure (u/trace ::availability [:product-id product-id, :order order-id, :user user-id] (product-availability product-id)) ``` Will produce an event as follow: ``` Clojure {:mulog/trace-id #mulog/flake \"4VIKxhMPB2eS0uc1EV9M9a5G7MYn3TMs\", :mulog/event-name :your-ns/availability, :mulog/timestamp 1586804894278, :mulog/duration 253303600, :mulog/namespace \"your-ns\", :mulog/outcome :ok, :mulog/root-trace #mulog/flake \"4VILF82cx_mFKlbKN-PUTezsRdsn8XOY\", :mulog/parent-trace #mulog/flake \"4VILL47ifjeHTaaG3kAWtZoELvk9AGY9\", :order \"34896-34556\", :product-id \"2345-23-545\", :user \"709-6567567\"} ``` Note the `:mulog/duration` and `:mulog/outcome` reporting respectively the duration of the execution of `product-availablity` in **nanoseconds** as well as the outcome (`:ok` or `:error`). If an exception is raised within the body an additional field is added `:exception` with the exception raised. The `:pairs` present in the vector are added in the event, but they are not propagated to nested traces, use `with-context` for that. Finally, `:mulog/trace-id`, `:mulog/parent-trace` and `:mulog/root-trace` identify respectively this trace, the outer trace wrapping this trace if present otherwise `nil` and the `:mulog/root-trace` is the outer-most trace with not parents. Keep in mind that *parent-trace* and *root-trace* might come from another system and they are propagated by the context. ### Capture evaluation result Sometimes it is useful to add to the trace pairs which come from the result of the body's evaluation. For example to capture the http response status or other valuable metrics from the response. ***μ/trace*** offers the possibility to pass a function to capture such info from the evaluation result. To achieve this, instead of passing a simple vector of pairs you need to provide a map which contains a `:capture` function in addition to the `:pairs`. The `capture` function is a function which takes one argument, *the result* of the evaluation and returns a map of key-value pairs which need to be added to the trace. The `capture` function will only run when the `:mulog/outcome :ok` Example of usage: ``` Clojure (u/trace ::availability {:pairs [:product-id product-id, :order order-id, :user user-id] :capture (fn [r] {:http-status (:status r) :etag (get-in r [:headers \"etag\"])}) (product-availability product-id)) ``` Will produce an event as follow: ``` Clojure {:mulog/trace-id #mulog/flake \"4VIKxhMPB2eS0uc1EV9M9a5G7MYn3TMs\", :mulog/event-name :your-ns/availability, :mulog/timestamp 1586804894278, :mulog/duration 253303600, :mulog/namespace \"your-ns\", :mulog/outcome :ok, :mulog/root-trace #mulog/flake \"4VILF82cx_mFKlbKN-PUTezsRdsn8XOY\", :mulog/parent-trace #mulog/flake \"4VILL47ifjeHTaaG3kAWtZoELvk9AGY9\", :order \"34896-34556\", :product-id \"2345-23-545\", :user \"709-6567567\", :http-status 200, :etag \"1dfb-2686-4cba2686fb8b1\"} ``` Note that in addition to the pairs like in the previous example this one contains `:http-status` and `:etag` which where extracted from the http response of `product-availability` evaluation. Should the execution of the `capture` function fail for any reason the pair will be added to this trace with `:mulog/capture :error` to signal the execution error. " {:style/indent 1 :arglists '([event-name [k1 v1, k2 v2, ... :as pairs] & body] [event-name {:keys [pairs capture]} & body])} [event-name details & body] `(let [details# ~details pairs# (if (map? details#) (:pairs details#) details#) capture# (if (map? details#) (:capture details#) nil) ;; :mulog/trace-id and :mulog/timestamp are created in here ;; because the log function is called after the evaluation of body ;; is completed, and the timestamp wouldn't be correct ptid# (get @core/local-context :mulog/parent-trace) tid# (flake) ts# (System/currentTimeMillis) ;; start timer to track body execution t0# (System/nanoTime)] ;; setting up the tracing re (with-context {:mulog/root-trace (or (get @core/local-context :mulog/root-trace) tid#) :mulog/parent-trace tid#} (try (let [r# (do ~@body)] (core/log-trace ~event-name tid# ptid# (- (System/nanoTime) t0#) ts# :ok pairs# ;; if there is something to capture form the evaluation result ;; then use the capture function (core/on-error {:mulog/capture :error} (when capture# (capture# r#)))) ;; return the body result r#) ;; If and exception occur, then log the error. (catch Exception x# (core/log-trace ~event-name tid# ptid# (- (System/nanoTime) t0#) ts# :error (list :exception x#) pairs#) (throw x#))))))
[ { "context": " (jwt/sign {:h \"hi\"} secret )\n (jwt/unsign\n\n \"eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJmaXJzdF9uYW1lIjoidXNlciIsImxhc3RfbmFtZSI6Imxhc3RuYW1lIiwiZW1haWwiOiJ1c2VyQGdtYWlsLmNvbSIsImFkbWluIjpmYWxzZX0.VRfUKLtuYmIMZOYBXwhp9gg39xM5RviM48-r3UgvqxA\"\n secret )\n (wrap-jwt-authentication (fn [req", "end": 1227, "score": 0.9997738003730774, "start": 1039, "tag": "KEY", "value": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJmaXJzdF9uYW1lIjoidXNlciIsImxhc3RfbmFtZSI6Imxhc3RuYW1lIiwiZW1haWwiOiJ1c2VyQGdtYWlsLmNvbSIsImFkbWluIjpmYWxzZX0.VRfUKLtuYmIMZOYBXwhp9gg39xM5RviM48-r3UgvqxA" }, { "context": "n handler backend))\n\n(comment\n\n (def token-auth \"eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJmaXJzdF9uYW1lIjoidXNlciIsImxhc3RfbmFtZSI6Imxhc3RuYW1lIiwiZW1haWwiOiJ1c2VyQGdtYWlsLmNvbSIsImFkbWluIjpmYWxzZSwiZXhwIjoiMTYzODc3ODg4NCJ9.hIkaNZ9ckZ3IMqjkBOEz7UtgCdRAoURgfojxkku7pxA\")\n\n (def token (last (clojure.string/split (str", "end": 1768, "score": 0.9997490644454956, "start": 1555, "tag": "KEY", "value": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJmaXJzdF9uYW1lIjoidXNlciIsImxhc3RfbmFtZSI6Imxhc3RuYW1lIiwiZW1haWwiOiJ1c2VyQGdtYWlsLmNvbSIsImFkbWluIjpmYWxzZSwiZXhwIjoiMTYzODc3ODg4NCJ9.hIkaNZ9ckZ3IMqjkBOEz7UtgCdRAoURgfojxkku7pxA" } ]
workspace/moviebookingappv5datomicgraphql/src/clj/moviebookingappv5datomicgraphql/users/jwt_util.clj
muthuishere/clojure-web-fundamentals
0
(ns moviebookingappv5datomicgraphql.users.jwt-util (:require [buddy.auth :refer [authenticated?]] [buddy.sign.jwt :as jwt] [clj-time.core :as time] [buddy.sign.util :as util] [buddy.auth.backends :as backends] [buddy.auth.middleware :refer [wrap-authentication]] ) ) (def secret "mysecret") ;Authorization Header should ;(def backend (backends/jws {:secret secret})) (def backend (backends/jws {:secret secret :token-name "Bearer"})) (defn get-expiration [] ;5 hours from now (time/plus (time/now) (time/hours 5)) ;(time/plus (time/now) (time/seconds 2)) ) (comment (create-token! "x1" "user") (time/now) (time/plus (time/now) (time/seconds 5)) ) (defn create-token! "Creates an auth token in the database for the given user and puts it in the database" [claims] (let [ token (jwt/sign (merge claims {:exp (get-expiration) } ) secret ) ] (println token) (println claims) token ) ) (comment (jwt/sign {:h "hi"} secret ) (jwt/unsign "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJmaXJzdF9uYW1lIjoidXNlciIsImxhc3RfbmFtZSI6Imxhc3RuYW1lIiwiZW1haWwiOiJ1c2VyQGdtYWlsLmNvbSIsImFkbWluIjpmYWxzZX0.VRfUKLtuYmIMZOYBXwhp9gg39xM5RviM48-r3UgvqxA" secret ) (wrap-jwt-authentication (fn [request] (println (request) ) ) ) ) (comment ) (defn wrap-jwt-authentication [handler] (println "handler" handler) (wrap-authentication handler backend)) (comment (def token-auth "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJmaXJzdF9uYW1lIjoidXNlciIsImxhc3RfbmFtZSI6Imxhc3RuYW1lIiwiZW1haWwiOiJ1c2VyQGdtYWlsLmNvbSIsImFkbWluIjpmYWxzZSwiZXhwIjoiMTYzODc3ODg4NCJ9.hIkaNZ9ckZ3IMqjkBOEz7UtgCdRAoURgfojxkku7pxA") (def token (last (clojure.string/split (str "Token " token-auth ) #" " ))) (type token) (jwt/unsign token secret) ) (defn restrict-authenticated [handler] (fn [request] ;(println "restrict-authenticated handler" handler) ;(println request) ;(println "keys" (keys (request :headers)) ) ;(println "Authorization" ((request :headers) "authorization") ) (if (authenticated? request) (handler request) {:status 401 :body {:error "Unauthorized"}}))) (comment (let [{:keys [identity] } {:identity {:id 1 }} ] (println (get identity :id )) (println (get identity :isd false)) ) ) (defn is-admin [{:keys [identity] } ] (get identity :admin false) ) (defn restrict-admin [handler] (fn [request] ;(println "restrict-authenticated handler" handler) ;(println request) ;(println "keys" (keys (request :headers)) ) ;(println "Authorization" ((request :headers) "authorization") ) (if (and (authenticated? request) (is-admin request)) (handler request) {:status 401 :body {:error "User is not admin"}})))
107554
(ns moviebookingappv5datomicgraphql.users.jwt-util (:require [buddy.auth :refer [authenticated?]] [buddy.sign.jwt :as jwt] [clj-time.core :as time] [buddy.sign.util :as util] [buddy.auth.backends :as backends] [buddy.auth.middleware :refer [wrap-authentication]] ) ) (def secret "mysecret") ;Authorization Header should ;(def backend (backends/jws {:secret secret})) (def backend (backends/jws {:secret secret :token-name "Bearer"})) (defn get-expiration [] ;5 hours from now (time/plus (time/now) (time/hours 5)) ;(time/plus (time/now) (time/seconds 2)) ) (comment (create-token! "x1" "user") (time/now) (time/plus (time/now) (time/seconds 5)) ) (defn create-token! "Creates an auth token in the database for the given user and puts it in the database" [claims] (let [ token (jwt/sign (merge claims {:exp (get-expiration) } ) secret ) ] (println token) (println claims) token ) ) (comment (jwt/sign {:h "hi"} secret ) (jwt/unsign "<KEY>" secret ) (wrap-jwt-authentication (fn [request] (println (request) ) ) ) ) (comment ) (defn wrap-jwt-authentication [handler] (println "handler" handler) (wrap-authentication handler backend)) (comment (def token-auth "<KEY>") (def token (last (clojure.string/split (str "Token " token-auth ) #" " ))) (type token) (jwt/unsign token secret) ) (defn restrict-authenticated [handler] (fn [request] ;(println "restrict-authenticated handler" handler) ;(println request) ;(println "keys" (keys (request :headers)) ) ;(println "Authorization" ((request :headers) "authorization") ) (if (authenticated? request) (handler request) {:status 401 :body {:error "Unauthorized"}}))) (comment (let [{:keys [identity] } {:identity {:id 1 }} ] (println (get identity :id )) (println (get identity :isd false)) ) ) (defn is-admin [{:keys [identity] } ] (get identity :admin false) ) (defn restrict-admin [handler] (fn [request] ;(println "restrict-authenticated handler" handler) ;(println request) ;(println "keys" (keys (request :headers)) ) ;(println "Authorization" ((request :headers) "authorization") ) (if (and (authenticated? request) (is-admin request)) (handler request) {:status 401 :body {:error "User is not admin"}})))
true
(ns moviebookingappv5datomicgraphql.users.jwt-util (:require [buddy.auth :refer [authenticated?]] [buddy.sign.jwt :as jwt] [clj-time.core :as time] [buddy.sign.util :as util] [buddy.auth.backends :as backends] [buddy.auth.middleware :refer [wrap-authentication]] ) ) (def secret "mysecret") ;Authorization Header should ;(def backend (backends/jws {:secret secret})) (def backend (backends/jws {:secret secret :token-name "Bearer"})) (defn get-expiration [] ;5 hours from now (time/plus (time/now) (time/hours 5)) ;(time/plus (time/now) (time/seconds 2)) ) (comment (create-token! "x1" "user") (time/now) (time/plus (time/now) (time/seconds 5)) ) (defn create-token! "Creates an auth token in the database for the given user and puts it in the database" [claims] (let [ token (jwt/sign (merge claims {:exp (get-expiration) } ) secret ) ] (println token) (println claims) token ) ) (comment (jwt/sign {:h "hi"} secret ) (jwt/unsign "PI:KEY:<KEY>END_PI" secret ) (wrap-jwt-authentication (fn [request] (println (request) ) ) ) ) (comment ) (defn wrap-jwt-authentication [handler] (println "handler" handler) (wrap-authentication handler backend)) (comment (def token-auth "PI:KEY:<KEY>END_PI") (def token (last (clojure.string/split (str "Token " token-auth ) #" " ))) (type token) (jwt/unsign token secret) ) (defn restrict-authenticated [handler] (fn [request] ;(println "restrict-authenticated handler" handler) ;(println request) ;(println "keys" (keys (request :headers)) ) ;(println "Authorization" ((request :headers) "authorization") ) (if (authenticated? request) (handler request) {:status 401 :body {:error "Unauthorized"}}))) (comment (let [{:keys [identity] } {:identity {:id 1 }} ] (println (get identity :id )) (println (get identity :isd false)) ) ) (defn is-admin [{:keys [identity] } ] (get identity :admin false) ) (defn restrict-admin [handler] (fn [request] ;(println "restrict-authenticated handler" handler) ;(println request) ;(println "keys" (keys (request :headers)) ) ;(println "Authorization" ((request :headers) "authorization") ) (if (and (authenticated? request) (is-admin request)) (handler request) {:status 401 :body {:error "User is not admin"}})))
[ { "context": "middle-forearm\" :size 3}\n {:name \"abdomen\" :size 6}\n {:name \"middle-kidney\"", "end": 3316, "score": 0.7153250575065613, "start": 3309, "tag": "NAME", "value": "abdomen" }, { "context": "rm\" :size 3}\n {:name \"abdomen\" :size 6}\n {:name \"mi", "end": 5608, "score": 0.5435130000114441, "start": 5601, "tag": "USERNAME", "value": "abdomen" }, { "context": "forearm\" :size 3}\n {:name \"abdomen\" :size 6}\n {:name \"1-kid", "end": 8611, "score": 0.6687602996826172, "start": 8606, "tag": "NAME", "value": "abdom" }, { "context": "\" :size 3}\n {:name \"abdomen\" :size 6}\n {:name \"", "end": 10429, "score": 0.7311573028564453, "start": 10426, "tag": "NAME", "value": "dom" } ]
test/brave_clojure/chapter3_test.clj
trilliput/brave-clojure-on-aws
0
(ns brave-clojure.chapter3-test "Tests for the exercises from Chapter 3" (:require [clojure.test :refer [deftest is testing]] [brave-clojure.chapter3 :as sut] [clojure.data])) (defn is-no-diff "Test, that the diff between a and b is nil, otherwise print out things-only-in-a things-only-in-b" [expected actual] (let [actual-vs-expected-diff (clojure.data/diff expected actual)] (is (= nil (actual-vs-expected-diff 0) (actual-vs-expected-diff 1))))) (deftest exercise-1-test (testing "Returns foo" (is (= {:str "Just a simple string." :vector ["a" "b" "c"] :list '(1 "a" "b" 2 "a" :end) :hash-map {:key "value"} :hash-set #{"a" "b" "c"}} (sut/-handler {:exercise-number 1 :arguments []}))))) (deftest exercise-2-test (testing "Adds 100 to 0" (is (= 100 (sut/-handler {:exercise-number 2 :arguments [0]})))) (testing "Adds 100 to a negative number" (is (= 0 (sut/-handler {:exercise-number 2 :arguments [-100]}))) (is (= 1 (sut/-handler {:exercise-number 2 :arguments [-99]})))) (testing "Adds 100 to a positive number" (is (= 101 (sut/-handler {:exercise-number 2 :arguments [1]}))) (is (= 201 (sut/-handler {:exercise-number 2 :arguments [101]}))) (is (= 1201 (sut/-handler {:exercise-number 2 :arguments [1101]})))) (testing "Adds 100 to a float number" (is (= 220.1 (sut/-handler {:exercise-number 2 :arguments [120.1]}))) (is (= 99.9 (sut/-handler {:exercise-number 2 :arguments [-0.1]}))))) (deftest exercise-3-test (testing "Makes a function, which decrements by 1" (let [decrement-by-1 (sut/-handler {:exercise-number 3 :arguments [1]})] (is (= 0 (decrement-by-1 1))) (is (= -1 (decrement-by-1 0))) (is (= 9 (decrement-by-1 10))))) (testing "Makes a function, which decrements by 0" (let [decrement-by-0 (sut/-handler {:exercise-number 3 :arguments [0]})] (is (= 1 (decrement-by-0 1))) (is (= 0 (decrement-by-0 0))) (is (= 10 (decrement-by-0 10))))) (testing "Makes a function, which decrements by -1" (let [decrement-by-minus-1 (sut/-handler {:exercise-number 3 :arguments [-1]})] (is (= 2 (decrement-by-minus-1 1))) (is (= 1 (decrement-by-minus-1 0))) (is (= 11 (decrement-by-minus-1 10)))))) (deftest exercise-4-test (testing "Straightforward successful path" (is (= #{2 3} (sut/-handler {:exercise-number 4 :arguments [inc [1 2]]}))))) (deftest exercise-5-test (testing "Adds 4 additional body parts to every one starting with middle-" (let [input [{:name "head" :size 3} {:name "middle-eye" :size 1} {:name "middle-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "middle-shoulder" :size 3} {:name "middle-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "middle-forearm" :size 3} {:name "abdomen" :size 6} {:name "middle-kidney" :size 1} {:name "middle-hand" :size 2} {:name "middle-knee" :size 2} {:name "middle-thigh" :size 4} {:name "middle-leg" :size 3} {:name "middle-achilles" :size 3} {:name "middle-foot" :size 2}] expected (hash-set {:name "head" :size 3} {:name "middle-eye" :size 1} {:name "right-upper-eye" :size 1} {:name "right-lower-eye" :size 1} {:name "left-lower-eye" :size 1} {:name "left-upper-eye" :size 1} {:name "middle-ear" :size 1} {:name "right-upper-ear" :size 1} {:name "right-lower-ear" :size 1} {:name "left-lower-ear" :size 1} {:name "left-upper-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "middle-shoulder" :size 3} {:name "right-upper-shoulder" :size 3} {:name "right-lower-shoulder" :size 3} {:name "left-lower-shoulder" :size 3} {:name "left-upper-shoulder" :size 3} {:name "middle-arm" :size 3} {:name "right-upper-arm" :size 3} {:name "right-lower-arm" :size 3} {:name "left-lower-arm" :size 3} {:name "left-upper-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "middle-forearm" :size 3} {:name "right-upper-forearm" :size 3} {:name "right-lower-forearm" :size 3} {:name "left-lower-forearm" :size 3} {:name "left-upper-forearm" :size 3} {:name "abdomen" :size 6} {:name "middle-kidney" :size 1} {:name "right-upper-kidney" :size 1} {:name "right-lower-kidney" :size 1} {:name "left-lower-kidney" :size 1} {:name "left-upper-kidney" :size 1} {:name "middle-hand" :size 2} {:name "right-upper-hand" :size 2} {:name "right-lower-hand" :size 2} {:name "left-lower-hand" :size 2} {:name "left-upper-hand" :size 2} {:name "middle-knee" :size 2} {:name "right-upper-knee" :size 2} {:name "right-lower-knee" :size 2} {:name "left-lower-knee" :size 2} {:name "left-upper-knee" :size 2} {:name "middle-thigh" :size 4} {:name "right-upper-thigh" :size 4} {:name "right-lower-thigh" :size 4} {:name "left-lower-thigh" :size 4} {:name "left-upper-thigh" :size 4} {:name "middle-leg" :size 3} {:name "right-upper-leg" :size 3} {:name "right-lower-leg" :size 3} {:name "left-lower-leg" :size 3} {:name "left-upper-leg" :size 3} {:name "middle-achilles" :size 3} {:name "right-upper-achilles" :size 3} {:name "right-lower-achilles" :size 3} {:name "left-lower-achilles" :size 3} {:name "left-upper-achilles" :size 3} {:name "middle-foot" :size 2} {:name "right-upper-foot" :size 2} {:name "right-lower-foot" :size 2} {:name "left-lower-foot" :size 2} {:name "left-upper-foot" :size 2})] (is-no-diff expected (sut/-handler {:exercise-number 5 :arguments [input]}))))) (deftest exercise-6-test (testing "Adds a given number additional body parts to every one starting with 1-" (let [arguments [3 [{:name "head" :size 3} {:name "1-eye" :size 1} {:name "1-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "1-shoulder" :size 3} {:name "1-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "1-forearm" :size 3} {:name "abdomen" :size 6} {:name "1-kidney" :size 1} {:name "1-hand" :size 2} {:name "1-knee" :size 2} {:name "1-thigh" :size 4} {:name "1-leg" :size 3} {:name "1-achilles" :size 3} {:name "1-foot" :size 2}]] expected (hash-set {:name "head" :size 3} {:name "1-eye" :size 1} {:name "2-eye" :size 1} {:name "3-eye" :size 1} {:name "4-eye" :size 1} {:name "1-ear" :size 1} {:name "2-ear" :size 1} {:name "3-ear" :size 1} {:name "4-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "1-shoulder" :size 3} {:name "2-shoulder" :size 3} {:name "3-shoulder" :size 3} {:name "4-shoulder" :size 3} {:name "1-arm" :size 3} {:name "2-arm" :size 3} {:name "3-arm" :size 3} {:name "4-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "1-forearm" :size 3} {:name "2-forearm" :size 3} {:name "3-forearm" :size 3} {:name "4-forearm" :size 3} {:name "abdomen" :size 6} {:name "1-kidney" :size 1} {:name "2-kidney" :size 1} {:name "3-kidney" :size 1} {:name "4-kidney" :size 1} {:name "1-hand" :size 2} {:name "2-hand" :size 2} {:name "3-hand" :size 2} {:name "4-hand" :size 2} {:name "1-knee" :size 2} {:name "2-knee" :size 2} {:name "3-knee" :size 2} {:name "4-knee" :size 2} {:name "1-thigh" :size 4} {:name "2-thigh" :size 4} {:name "3-thigh" :size 4} {:name "4-thigh" :size 4} {:name "1-leg" :size 3} {:name "2-leg" :size 3} {:name "3-leg" :size 3} {:name "4-leg" :size 3} {:name "1-achilles" :size 3} {:name "2-achilles" :size 3} {:name "3-achilles" :size 3} {:name "4-achilles" :size 3} {:name "1-foot" :size 2} {:name "2-foot" :size 2} {:name "3-foot" :size 2} {:name "4-foot" :size 2})] (is-no-diff expected (sut/-handler {:exercise-number 6 :arguments arguments})))))
105670
(ns brave-clojure.chapter3-test "Tests for the exercises from Chapter 3" (:require [clojure.test :refer [deftest is testing]] [brave-clojure.chapter3 :as sut] [clojure.data])) (defn is-no-diff "Test, that the diff between a and b is nil, otherwise print out things-only-in-a things-only-in-b" [expected actual] (let [actual-vs-expected-diff (clojure.data/diff expected actual)] (is (= nil (actual-vs-expected-diff 0) (actual-vs-expected-diff 1))))) (deftest exercise-1-test (testing "Returns foo" (is (= {:str "Just a simple string." :vector ["a" "b" "c"] :list '(1 "a" "b" 2 "a" :end) :hash-map {:key "value"} :hash-set #{"a" "b" "c"}} (sut/-handler {:exercise-number 1 :arguments []}))))) (deftest exercise-2-test (testing "Adds 100 to 0" (is (= 100 (sut/-handler {:exercise-number 2 :arguments [0]})))) (testing "Adds 100 to a negative number" (is (= 0 (sut/-handler {:exercise-number 2 :arguments [-100]}))) (is (= 1 (sut/-handler {:exercise-number 2 :arguments [-99]})))) (testing "Adds 100 to a positive number" (is (= 101 (sut/-handler {:exercise-number 2 :arguments [1]}))) (is (= 201 (sut/-handler {:exercise-number 2 :arguments [101]}))) (is (= 1201 (sut/-handler {:exercise-number 2 :arguments [1101]})))) (testing "Adds 100 to a float number" (is (= 220.1 (sut/-handler {:exercise-number 2 :arguments [120.1]}))) (is (= 99.9 (sut/-handler {:exercise-number 2 :arguments [-0.1]}))))) (deftest exercise-3-test (testing "Makes a function, which decrements by 1" (let [decrement-by-1 (sut/-handler {:exercise-number 3 :arguments [1]})] (is (= 0 (decrement-by-1 1))) (is (= -1 (decrement-by-1 0))) (is (= 9 (decrement-by-1 10))))) (testing "Makes a function, which decrements by 0" (let [decrement-by-0 (sut/-handler {:exercise-number 3 :arguments [0]})] (is (= 1 (decrement-by-0 1))) (is (= 0 (decrement-by-0 0))) (is (= 10 (decrement-by-0 10))))) (testing "Makes a function, which decrements by -1" (let [decrement-by-minus-1 (sut/-handler {:exercise-number 3 :arguments [-1]})] (is (= 2 (decrement-by-minus-1 1))) (is (= 1 (decrement-by-minus-1 0))) (is (= 11 (decrement-by-minus-1 10)))))) (deftest exercise-4-test (testing "Straightforward successful path" (is (= #{2 3} (sut/-handler {:exercise-number 4 :arguments [inc [1 2]]}))))) (deftest exercise-5-test (testing "Adds 4 additional body parts to every one starting with middle-" (let [input [{:name "head" :size 3} {:name "middle-eye" :size 1} {:name "middle-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "middle-shoulder" :size 3} {:name "middle-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "middle-forearm" :size 3} {:name "<NAME>" :size 6} {:name "middle-kidney" :size 1} {:name "middle-hand" :size 2} {:name "middle-knee" :size 2} {:name "middle-thigh" :size 4} {:name "middle-leg" :size 3} {:name "middle-achilles" :size 3} {:name "middle-foot" :size 2}] expected (hash-set {:name "head" :size 3} {:name "middle-eye" :size 1} {:name "right-upper-eye" :size 1} {:name "right-lower-eye" :size 1} {:name "left-lower-eye" :size 1} {:name "left-upper-eye" :size 1} {:name "middle-ear" :size 1} {:name "right-upper-ear" :size 1} {:name "right-lower-ear" :size 1} {:name "left-lower-ear" :size 1} {:name "left-upper-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "middle-shoulder" :size 3} {:name "right-upper-shoulder" :size 3} {:name "right-lower-shoulder" :size 3} {:name "left-lower-shoulder" :size 3} {:name "left-upper-shoulder" :size 3} {:name "middle-arm" :size 3} {:name "right-upper-arm" :size 3} {:name "right-lower-arm" :size 3} {:name "left-lower-arm" :size 3} {:name "left-upper-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "middle-forearm" :size 3} {:name "right-upper-forearm" :size 3} {:name "right-lower-forearm" :size 3} {:name "left-lower-forearm" :size 3} {:name "left-upper-forearm" :size 3} {:name "abdomen" :size 6} {:name "middle-kidney" :size 1} {:name "right-upper-kidney" :size 1} {:name "right-lower-kidney" :size 1} {:name "left-lower-kidney" :size 1} {:name "left-upper-kidney" :size 1} {:name "middle-hand" :size 2} {:name "right-upper-hand" :size 2} {:name "right-lower-hand" :size 2} {:name "left-lower-hand" :size 2} {:name "left-upper-hand" :size 2} {:name "middle-knee" :size 2} {:name "right-upper-knee" :size 2} {:name "right-lower-knee" :size 2} {:name "left-lower-knee" :size 2} {:name "left-upper-knee" :size 2} {:name "middle-thigh" :size 4} {:name "right-upper-thigh" :size 4} {:name "right-lower-thigh" :size 4} {:name "left-lower-thigh" :size 4} {:name "left-upper-thigh" :size 4} {:name "middle-leg" :size 3} {:name "right-upper-leg" :size 3} {:name "right-lower-leg" :size 3} {:name "left-lower-leg" :size 3} {:name "left-upper-leg" :size 3} {:name "middle-achilles" :size 3} {:name "right-upper-achilles" :size 3} {:name "right-lower-achilles" :size 3} {:name "left-lower-achilles" :size 3} {:name "left-upper-achilles" :size 3} {:name "middle-foot" :size 2} {:name "right-upper-foot" :size 2} {:name "right-lower-foot" :size 2} {:name "left-lower-foot" :size 2} {:name "left-upper-foot" :size 2})] (is-no-diff expected (sut/-handler {:exercise-number 5 :arguments [input]}))))) (deftest exercise-6-test (testing "Adds a given number additional body parts to every one starting with 1-" (let [arguments [3 [{:name "head" :size 3} {:name "1-eye" :size 1} {:name "1-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "1-shoulder" :size 3} {:name "1-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "1-forearm" :size 3} {:name "<NAME>en" :size 6} {:name "1-kidney" :size 1} {:name "1-hand" :size 2} {:name "1-knee" :size 2} {:name "1-thigh" :size 4} {:name "1-leg" :size 3} {:name "1-achilles" :size 3} {:name "1-foot" :size 2}]] expected (hash-set {:name "head" :size 3} {:name "1-eye" :size 1} {:name "2-eye" :size 1} {:name "3-eye" :size 1} {:name "4-eye" :size 1} {:name "1-ear" :size 1} {:name "2-ear" :size 1} {:name "3-ear" :size 1} {:name "4-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "1-shoulder" :size 3} {:name "2-shoulder" :size 3} {:name "3-shoulder" :size 3} {:name "4-shoulder" :size 3} {:name "1-arm" :size 3} {:name "2-arm" :size 3} {:name "3-arm" :size 3} {:name "4-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "1-forearm" :size 3} {:name "2-forearm" :size 3} {:name "3-forearm" :size 3} {:name "4-forearm" :size 3} {:name "ab<NAME>en" :size 6} {:name "1-kidney" :size 1} {:name "2-kidney" :size 1} {:name "3-kidney" :size 1} {:name "4-kidney" :size 1} {:name "1-hand" :size 2} {:name "2-hand" :size 2} {:name "3-hand" :size 2} {:name "4-hand" :size 2} {:name "1-knee" :size 2} {:name "2-knee" :size 2} {:name "3-knee" :size 2} {:name "4-knee" :size 2} {:name "1-thigh" :size 4} {:name "2-thigh" :size 4} {:name "3-thigh" :size 4} {:name "4-thigh" :size 4} {:name "1-leg" :size 3} {:name "2-leg" :size 3} {:name "3-leg" :size 3} {:name "4-leg" :size 3} {:name "1-achilles" :size 3} {:name "2-achilles" :size 3} {:name "3-achilles" :size 3} {:name "4-achilles" :size 3} {:name "1-foot" :size 2} {:name "2-foot" :size 2} {:name "3-foot" :size 2} {:name "4-foot" :size 2})] (is-no-diff expected (sut/-handler {:exercise-number 6 :arguments arguments})))))
true
(ns brave-clojure.chapter3-test "Tests for the exercises from Chapter 3" (:require [clojure.test :refer [deftest is testing]] [brave-clojure.chapter3 :as sut] [clojure.data])) (defn is-no-diff "Test, that the diff between a and b is nil, otherwise print out things-only-in-a things-only-in-b" [expected actual] (let [actual-vs-expected-diff (clojure.data/diff expected actual)] (is (= nil (actual-vs-expected-diff 0) (actual-vs-expected-diff 1))))) (deftest exercise-1-test (testing "Returns foo" (is (= {:str "Just a simple string." :vector ["a" "b" "c"] :list '(1 "a" "b" 2 "a" :end) :hash-map {:key "value"} :hash-set #{"a" "b" "c"}} (sut/-handler {:exercise-number 1 :arguments []}))))) (deftest exercise-2-test (testing "Adds 100 to 0" (is (= 100 (sut/-handler {:exercise-number 2 :arguments [0]})))) (testing "Adds 100 to a negative number" (is (= 0 (sut/-handler {:exercise-number 2 :arguments [-100]}))) (is (= 1 (sut/-handler {:exercise-number 2 :arguments [-99]})))) (testing "Adds 100 to a positive number" (is (= 101 (sut/-handler {:exercise-number 2 :arguments [1]}))) (is (= 201 (sut/-handler {:exercise-number 2 :arguments [101]}))) (is (= 1201 (sut/-handler {:exercise-number 2 :arguments [1101]})))) (testing "Adds 100 to a float number" (is (= 220.1 (sut/-handler {:exercise-number 2 :arguments [120.1]}))) (is (= 99.9 (sut/-handler {:exercise-number 2 :arguments [-0.1]}))))) (deftest exercise-3-test (testing "Makes a function, which decrements by 1" (let [decrement-by-1 (sut/-handler {:exercise-number 3 :arguments [1]})] (is (= 0 (decrement-by-1 1))) (is (= -1 (decrement-by-1 0))) (is (= 9 (decrement-by-1 10))))) (testing "Makes a function, which decrements by 0" (let [decrement-by-0 (sut/-handler {:exercise-number 3 :arguments [0]})] (is (= 1 (decrement-by-0 1))) (is (= 0 (decrement-by-0 0))) (is (= 10 (decrement-by-0 10))))) (testing "Makes a function, which decrements by -1" (let [decrement-by-minus-1 (sut/-handler {:exercise-number 3 :arguments [-1]})] (is (= 2 (decrement-by-minus-1 1))) (is (= 1 (decrement-by-minus-1 0))) (is (= 11 (decrement-by-minus-1 10)))))) (deftest exercise-4-test (testing "Straightforward successful path" (is (= #{2 3} (sut/-handler {:exercise-number 4 :arguments [inc [1 2]]}))))) (deftest exercise-5-test (testing "Adds 4 additional body parts to every one starting with middle-" (let [input [{:name "head" :size 3} {:name "middle-eye" :size 1} {:name "middle-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "middle-shoulder" :size 3} {:name "middle-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "middle-forearm" :size 3} {:name "PI:NAME:<NAME>END_PI" :size 6} {:name "middle-kidney" :size 1} {:name "middle-hand" :size 2} {:name "middle-knee" :size 2} {:name "middle-thigh" :size 4} {:name "middle-leg" :size 3} {:name "middle-achilles" :size 3} {:name "middle-foot" :size 2}] expected (hash-set {:name "head" :size 3} {:name "middle-eye" :size 1} {:name "right-upper-eye" :size 1} {:name "right-lower-eye" :size 1} {:name "left-lower-eye" :size 1} {:name "left-upper-eye" :size 1} {:name "middle-ear" :size 1} {:name "right-upper-ear" :size 1} {:name "right-lower-ear" :size 1} {:name "left-lower-ear" :size 1} {:name "left-upper-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "middle-shoulder" :size 3} {:name "right-upper-shoulder" :size 3} {:name "right-lower-shoulder" :size 3} {:name "left-lower-shoulder" :size 3} {:name "left-upper-shoulder" :size 3} {:name "middle-arm" :size 3} {:name "right-upper-arm" :size 3} {:name "right-lower-arm" :size 3} {:name "left-lower-arm" :size 3} {:name "left-upper-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "middle-forearm" :size 3} {:name "right-upper-forearm" :size 3} {:name "right-lower-forearm" :size 3} {:name "left-lower-forearm" :size 3} {:name "left-upper-forearm" :size 3} {:name "abdomen" :size 6} {:name "middle-kidney" :size 1} {:name "right-upper-kidney" :size 1} {:name "right-lower-kidney" :size 1} {:name "left-lower-kidney" :size 1} {:name "left-upper-kidney" :size 1} {:name "middle-hand" :size 2} {:name "right-upper-hand" :size 2} {:name "right-lower-hand" :size 2} {:name "left-lower-hand" :size 2} {:name "left-upper-hand" :size 2} {:name "middle-knee" :size 2} {:name "right-upper-knee" :size 2} {:name "right-lower-knee" :size 2} {:name "left-lower-knee" :size 2} {:name "left-upper-knee" :size 2} {:name "middle-thigh" :size 4} {:name "right-upper-thigh" :size 4} {:name "right-lower-thigh" :size 4} {:name "left-lower-thigh" :size 4} {:name "left-upper-thigh" :size 4} {:name "middle-leg" :size 3} {:name "right-upper-leg" :size 3} {:name "right-lower-leg" :size 3} {:name "left-lower-leg" :size 3} {:name "left-upper-leg" :size 3} {:name "middle-achilles" :size 3} {:name "right-upper-achilles" :size 3} {:name "right-lower-achilles" :size 3} {:name "left-lower-achilles" :size 3} {:name "left-upper-achilles" :size 3} {:name "middle-foot" :size 2} {:name "right-upper-foot" :size 2} {:name "right-lower-foot" :size 2} {:name "left-lower-foot" :size 2} {:name "left-upper-foot" :size 2})] (is-no-diff expected (sut/-handler {:exercise-number 5 :arguments [input]}))))) (deftest exercise-6-test (testing "Adds a given number additional body parts to every one starting with 1-" (let [arguments [3 [{:name "head" :size 3} {:name "1-eye" :size 1} {:name "1-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "1-shoulder" :size 3} {:name "1-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "1-forearm" :size 3} {:name "PI:NAME:<NAME>END_PIen" :size 6} {:name "1-kidney" :size 1} {:name "1-hand" :size 2} {:name "1-knee" :size 2} {:name "1-thigh" :size 4} {:name "1-leg" :size 3} {:name "1-achilles" :size 3} {:name "1-foot" :size 2}]] expected (hash-set {:name "head" :size 3} {:name "1-eye" :size 1} {:name "2-eye" :size 1} {:name "3-eye" :size 1} {:name "4-eye" :size 1} {:name "1-ear" :size 1} {:name "2-ear" :size 1} {:name "3-ear" :size 1} {:name "4-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "1-shoulder" :size 3} {:name "2-shoulder" :size 3} {:name "3-shoulder" :size 3} {:name "4-shoulder" :size 3} {:name "1-arm" :size 3} {:name "2-arm" :size 3} {:name "3-arm" :size 3} {:name "4-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "1-forearm" :size 3} {:name "2-forearm" :size 3} {:name "3-forearm" :size 3} {:name "4-forearm" :size 3} {:name "abPI:NAME:<NAME>END_PIen" :size 6} {:name "1-kidney" :size 1} {:name "2-kidney" :size 1} {:name "3-kidney" :size 1} {:name "4-kidney" :size 1} {:name "1-hand" :size 2} {:name "2-hand" :size 2} {:name "3-hand" :size 2} {:name "4-hand" :size 2} {:name "1-knee" :size 2} {:name "2-knee" :size 2} {:name "3-knee" :size 2} {:name "4-knee" :size 2} {:name "1-thigh" :size 4} {:name "2-thigh" :size 4} {:name "3-thigh" :size 4} {:name "4-thigh" :size 4} {:name "1-leg" :size 3} {:name "2-leg" :size 3} {:name "3-leg" :size 3} {:name "4-leg" :size 3} {:name "1-achilles" :size 3} {:name "2-achilles" :size 3} {:name "3-achilles" :size 3} {:name "4-achilles" :size 3} {:name "1-foot" :size 2} {:name "2-foot" :size 2} {:name "3-foot" :size 2} {:name "4-foot" :size 2})] (is-no-diff expected (sut/-handler {:exercise-number 6 :arguments arguments})))))
[ { "context": ")\n :password (describe s/Str \"User password\")\n :admin (describe s/Bool", "end": 1499, "score": 0.991656482219696, "start": 1486, "tag": "PASSWORD", "value": "User password" } ]
src/copa/http/schemas.clj
hjrnunes/copa
2
(ns copa.http.schemas (:require [schema.core :as s] [schema.coerce :as sc] [ring.swagger.schema :as rs :refer [describe]])) (s/defschema BaseEntity {(s/optional-key :recipe_id) (describe s/Str "Database id")}) (s/defschema Measurement (merge BaseEntity {:ingredient (describe s/Str "Measurement ingredient") (s/optional-key :quantity) (describe Double "Measurement quantity") (s/optional-key :unit) (describe s/Str "Measurement unit")})) (s/defschema Recipe (merge BaseEntity {:name (describe s/Str "Recipe's name") (s/optional-key :description) (describe s/Str "Recipe's description") (s/optional-key :portions) (describe s/Str "Recipe's portions") (s/optional-key :source) (describe s/Str "Recipe's source") (s/optional-key :duration) (describe s/Str "Recipe's duration") :preparation (describe s/Str "Recipe's preparation") (s/optional-key :categories) (describe [s/Str] "Recipe's categories") :measurements (describe [Measurement] "Recipe's measurements") :user (describe s/Str "Recipe's user")})) (s/defschema User (merge BaseEntity {:username (describe s/Str "User name") :password (describe s/Str "User password") :admin (describe s/Bool "Is the user an admin?")})) (s/defschema UserLang (merge BaseEntity {:username (describe s/Str "User name") :lang (describe s/Str "Language preference")})) (s/defschema UserPassword (merge BaseEntity {:username (describe s/Str "User name") :current (describe s/Str "Current password") :new (describe s/Str "New password") :confirm (describe s/Str "New password confirmation")}))
33009
(ns copa.http.schemas (:require [schema.core :as s] [schema.coerce :as sc] [ring.swagger.schema :as rs :refer [describe]])) (s/defschema BaseEntity {(s/optional-key :recipe_id) (describe s/Str "Database id")}) (s/defschema Measurement (merge BaseEntity {:ingredient (describe s/Str "Measurement ingredient") (s/optional-key :quantity) (describe Double "Measurement quantity") (s/optional-key :unit) (describe s/Str "Measurement unit")})) (s/defschema Recipe (merge BaseEntity {:name (describe s/Str "Recipe's name") (s/optional-key :description) (describe s/Str "Recipe's description") (s/optional-key :portions) (describe s/Str "Recipe's portions") (s/optional-key :source) (describe s/Str "Recipe's source") (s/optional-key :duration) (describe s/Str "Recipe's duration") :preparation (describe s/Str "Recipe's preparation") (s/optional-key :categories) (describe [s/Str] "Recipe's categories") :measurements (describe [Measurement] "Recipe's measurements") :user (describe s/Str "Recipe's user")})) (s/defschema User (merge BaseEntity {:username (describe s/Str "User name") :password (describe s/Str "<PASSWORD>") :admin (describe s/Bool "Is the user an admin?")})) (s/defschema UserLang (merge BaseEntity {:username (describe s/Str "User name") :lang (describe s/Str "Language preference")})) (s/defschema UserPassword (merge BaseEntity {:username (describe s/Str "User name") :current (describe s/Str "Current password") :new (describe s/Str "New password") :confirm (describe s/Str "New password confirmation")}))
true
(ns copa.http.schemas (:require [schema.core :as s] [schema.coerce :as sc] [ring.swagger.schema :as rs :refer [describe]])) (s/defschema BaseEntity {(s/optional-key :recipe_id) (describe s/Str "Database id")}) (s/defschema Measurement (merge BaseEntity {:ingredient (describe s/Str "Measurement ingredient") (s/optional-key :quantity) (describe Double "Measurement quantity") (s/optional-key :unit) (describe s/Str "Measurement unit")})) (s/defschema Recipe (merge BaseEntity {:name (describe s/Str "Recipe's name") (s/optional-key :description) (describe s/Str "Recipe's description") (s/optional-key :portions) (describe s/Str "Recipe's portions") (s/optional-key :source) (describe s/Str "Recipe's source") (s/optional-key :duration) (describe s/Str "Recipe's duration") :preparation (describe s/Str "Recipe's preparation") (s/optional-key :categories) (describe [s/Str] "Recipe's categories") :measurements (describe [Measurement] "Recipe's measurements") :user (describe s/Str "Recipe's user")})) (s/defschema User (merge BaseEntity {:username (describe s/Str "User name") :password (describe s/Str "PI:PASSWORD:<PASSWORD>END_PI") :admin (describe s/Bool "Is the user an admin?")})) (s/defschema UserLang (merge BaseEntity {:username (describe s/Str "User name") :lang (describe s/Str "Language preference")})) (s/defschema UserPassword (merge BaseEntity {:username (describe s/Str "User name") :current (describe s/Str "Current password") :new (describe s/Str "New password") :confirm (describe s/Str "New password confirmation")}))
[ { "context": "int (meta (database/create \"test-DB\" [{:username \"test-user\"}])))\n (cla-core/set-default-db! \"test-DB\"))\n\n(", "end": 328, "score": 0.9992924332618713, "start": 319, "tag": "USERNAME", "value": "test-user" }, { "context": "eyword k) v]) data)))\n\n(def test-user {:username \"username\" :passwd \"secret\"})\n\n(deftest user-test\n (testin", "end": 628, "score": 0.9957863688468933, "start": 620, "tag": "USERNAME", "value": "username" }, { "context": "xist\"\n (is (false? (cla-user/exists? (:username test-user)))))\n\n (testing \"Create a new user with minimum ", "end": 766, "score": 0.9881634712219238, "start": 757, "tag": "USERNAME", "value": "test-user" }, { "context": "[result (to-map (cla-user/create {:user (:username test-user)}))]\n (is (= (:username test-user) (:user re", "end": 913, "score": 0.9933724403381348, "start": 904, "tag": "USERNAME", "value": "test-user" }, { "context": " (:username test-user)}))]\n (is (= (:username test-user) (:user result)))))\n\n (testing \"User exists ...\"", "end": 952, "score": 0.9968693256378174, "start": 943, "tag": "USERNAME", "value": "test-user" }, { "context": "s ...\"\n (is (true? (cla-user/exists? (:username test-user)))))\n\n (testing \"User is set to active == true b", "end": 1056, "score": 0.9907670021057129, "start": 1047, "tag": "USERNAME", "value": "test-user" }, { "context": "esult (to-map (cla-user/get-by-username (:username test-user)))]\n (is (= true (:active result)))))\n\n (te", "end": 1192, "score": 0.9968765377998352, "start": 1183, "tag": "USERNAME", "value": "test-user" }, { "context": " (let [result (to-map (cla-user/get-by-username (:username test-user)))]\n (is (= (:username test-user) ", "end": 1358, "score": 0.7151595950126648, "start": 1350, "tag": "USERNAME", "value": "username" }, { "context": "esult (to-map (cla-user/get-by-username (:username test-user)))]\n (is (= (:username test-user) (:user res", "end": 1368, "score": 0.9964384436607361, "start": 1359, "tag": "USERNAME", "value": "test-user" }, { "context": "e (:username test-user)))]\n (is (= (:username test-user) (:user result)))))\n\n (testing \"Extras user data", "end": 1406, "score": 0.9984369874000549, "start": 1397, "tag": "USERNAME", "value": "test-user" }, { "context": "a {:bio \"Loves Spongebob Squarepants\"}} (:username test-user)))]\n (is (= \"Loves Spongebob Squarepants\" ((", "end": 1616, "score": 0.99679034948349, "start": 1607, "tag": "USERNAME", "value": "test-user" }, { "context": "o-map (cla-user/update-by-username {:extra {:bio \"Loves Spongebob Squarepants. Prefers Adventure Time\"}} (:username test-user))", "end": 1855, "score": 0.6794542074203491, "start": 1828, "tag": "NAME", "value": "Loves Spongebob Squarepants" }, { "context": " Squarepants. Prefers Adventure Time\"}} (:username test-user)))]\n (is (= \"Loves Spongebob Squarepants. Pr", "end": 1903, "score": 0.999708890914917, "start": 1894, "tag": "USERNAME", "value": "test-user" }, { "context": "re Time\"}} (:username test-user)))]\n (is (= \"Loves Spongebob Squarepants. Prefers Adventure Time\" ((:extra result) \"bio\"))", "end": 1949, "score": 0.7855695486068726, "start": 1922, "tag": "NAME", "value": "Loves Spongebob Squarepants" }, { "context": "lt (to-map (cla-user/delete-by-username (:username test-user)))]\n (is (= 202 (:code delete-result)))))\n\n ", "end": 2151, "score": 0.9997020363807678, "start": 2142, "tag": "USERNAME", "value": "test-user" }, { "context": "ists\"\n (is (false? (cla-user/exists? (:username test-user))))))\n", "end": 2289, "score": 0.9996740818023682, "start": 2280, "tag": "USERNAME", "value": "test-user" } ]
test/clarango/test/user.clj
Lepetere/clarango
25
(ns clarango.test.user (:require [clojure.test :refer :all] [clarango.core :as cla-core] [clarango.database :as database] [clarango.user :as cla-user]) (:use clojure.pprint)) (defn setup [] (cla-core/set-connection!) (pprint (meta (database/create "test-DB" [{:username "test-user"}]))) (cla-core/set-default-db! "test-DB")) (defn teardown [] (pprint (database/delete "test-DB"))) (defn fixture [f] (setup) (f) (teardown)) (use-fixtures :once fixture) (defn to-map [data] (into {} (map (fn [[k v]] [(keyword k) v]) data))) (def test-user {:username "username" :passwd "secret"}) (deftest user-test (testing "User does not currently exist" (is (false? (cla-user/exists? (:username test-user))))) (testing "Create a new user with minimum required fields (name) ..." (let [result (to-map (cla-user/create {:user (:username test-user)}))] (is (= (:username test-user) (:user result))))) (testing "User exists ..." (is (true? (cla-user/exists? (:username test-user))))) (testing "User is set to active == true by default ..." (let [result (to-map (cla-user/get-by-username (:username test-user)))] (is (= true (:active result))))) (testing "User can be found by username once created ..." (let [result (to-map (cla-user/get-by-username (:username test-user)))] (is (= (:username test-user) (:user result))))) (testing "Extras user data can be set after initial creation ..." (let [result (to-map (cla-user/update-by-username {:extra {:bio "Loves Spongebob Squarepants"}} (:username test-user)))] (is (= "Loves Spongebob Squarepants" ((:extra result) "bio"))))) (testing "Extras user data can be replaced after being set ..." (let [result (to-map (cla-user/update-by-username {:extra {:bio "Loves Spongebob Squarepants. Prefers Adventure Time"}} (:username test-user)))] (is (= "Loves Spongebob Squarepants. Prefers Adventure Time" ((:extra result) "bio"))))) (testing "User can be deleted once created (returns :code 202)" (let [delete-result (to-map (cla-user/delete-by-username (:username test-user)))] (is (= 202 (:code delete-result))))) (testing "User no longer exists" (is (false? (cla-user/exists? (:username test-user))))))
121617
(ns clarango.test.user (:require [clojure.test :refer :all] [clarango.core :as cla-core] [clarango.database :as database] [clarango.user :as cla-user]) (:use clojure.pprint)) (defn setup [] (cla-core/set-connection!) (pprint (meta (database/create "test-DB" [{:username "test-user"}]))) (cla-core/set-default-db! "test-DB")) (defn teardown [] (pprint (database/delete "test-DB"))) (defn fixture [f] (setup) (f) (teardown)) (use-fixtures :once fixture) (defn to-map [data] (into {} (map (fn [[k v]] [(keyword k) v]) data))) (def test-user {:username "username" :passwd "secret"}) (deftest user-test (testing "User does not currently exist" (is (false? (cla-user/exists? (:username test-user))))) (testing "Create a new user with minimum required fields (name) ..." (let [result (to-map (cla-user/create {:user (:username test-user)}))] (is (= (:username test-user) (:user result))))) (testing "User exists ..." (is (true? (cla-user/exists? (:username test-user))))) (testing "User is set to active == true by default ..." (let [result (to-map (cla-user/get-by-username (:username test-user)))] (is (= true (:active result))))) (testing "User can be found by username once created ..." (let [result (to-map (cla-user/get-by-username (:username test-user)))] (is (= (:username test-user) (:user result))))) (testing "Extras user data can be set after initial creation ..." (let [result (to-map (cla-user/update-by-username {:extra {:bio "Loves Spongebob Squarepants"}} (:username test-user)))] (is (= "Loves Spongebob Squarepants" ((:extra result) "bio"))))) (testing "Extras user data can be replaced after being set ..." (let [result (to-map (cla-user/update-by-username {:extra {:bio "<NAME>. Prefers Adventure Time"}} (:username test-user)))] (is (= "<NAME>. Prefers Adventure Time" ((:extra result) "bio"))))) (testing "User can be deleted once created (returns :code 202)" (let [delete-result (to-map (cla-user/delete-by-username (:username test-user)))] (is (= 202 (:code delete-result))))) (testing "User no longer exists" (is (false? (cla-user/exists? (:username test-user))))))
true
(ns clarango.test.user (:require [clojure.test :refer :all] [clarango.core :as cla-core] [clarango.database :as database] [clarango.user :as cla-user]) (:use clojure.pprint)) (defn setup [] (cla-core/set-connection!) (pprint (meta (database/create "test-DB" [{:username "test-user"}]))) (cla-core/set-default-db! "test-DB")) (defn teardown [] (pprint (database/delete "test-DB"))) (defn fixture [f] (setup) (f) (teardown)) (use-fixtures :once fixture) (defn to-map [data] (into {} (map (fn [[k v]] [(keyword k) v]) data))) (def test-user {:username "username" :passwd "secret"}) (deftest user-test (testing "User does not currently exist" (is (false? (cla-user/exists? (:username test-user))))) (testing "Create a new user with minimum required fields (name) ..." (let [result (to-map (cla-user/create {:user (:username test-user)}))] (is (= (:username test-user) (:user result))))) (testing "User exists ..." (is (true? (cla-user/exists? (:username test-user))))) (testing "User is set to active == true by default ..." (let [result (to-map (cla-user/get-by-username (:username test-user)))] (is (= true (:active result))))) (testing "User can be found by username once created ..." (let [result (to-map (cla-user/get-by-username (:username test-user)))] (is (= (:username test-user) (:user result))))) (testing "Extras user data can be set after initial creation ..." (let [result (to-map (cla-user/update-by-username {:extra {:bio "Loves Spongebob Squarepants"}} (:username test-user)))] (is (= "Loves Spongebob Squarepants" ((:extra result) "bio"))))) (testing "Extras user data can be replaced after being set ..." (let [result (to-map (cla-user/update-by-username {:extra {:bio "PI:NAME:<NAME>END_PI. Prefers Adventure Time"}} (:username test-user)))] (is (= "PI:NAME:<NAME>END_PI. Prefers Adventure Time" ((:extra result) "bio"))))) (testing "User can be deleted once created (returns :code 202)" (let [delete-result (to-map (cla-user/delete-by-username (:username test-user)))] (is (= 202 (:code delete-result))))) (testing "User no longer exists" (is (false? (cla-user/exists? (:username test-user))))))
[ { "context": " db-name \"postgres\", user \"postgres\", password \"postgres\"\n params [\"-E\" \"SQL_ASCII\" \"--locale=C\" ", "end": 1065, "score": 0.9995735883712769, "start": 1057, "tag": "PASSWORD", "value": "postgres" } ]
examples/pg/src/embedded_pg.clj
dm3/everest
4
(ns embedded-pg (:import [ru.yandex.qatools.embed.postgresql EmbeddedPostgres] [de.flapdoodle.embed.process.distribution IVersion] [ru.yandex.qatools.embed.postgresql.util SocketUtil])) (defn- ->iversion [version] (if (instance? IVersion version) version (reify IVersion (asInDownloadPath [_] (str version))))) (defn ^EmbeddedPostgres make "See [IVersion definitions](https://github.com/yandex-qatools/postgresql-embedded/blob/master/src/main/java/ru/yandex/qatools/embed/postgresql/distribution/Version.java) for more info. * version - a version string or an IVersion, e.g. 9.5.7-1 * data-dir - name of the directory e.g. /tmp/data" [{:keys [version data-dir]}] (EmbeddedPostgres. (->iversion version) data-dir)) (defn start! [^EmbeddedPostgres pg {:keys [runtime-config host port db-name user password params] :or {runtime-config (EmbeddedPostgres/defaultRuntimeConfig) host "localhost", port (SocketUtil/findFreePort) db-name "postgres", user "postgres", password "postgres" params ["-E" "SQL_ASCII" "--locale=C" "--lc-collate=C" "--lc-ctype=C"]}}] (.start pg host port db-name user password params)) (defn stop! [^EmbeddedPostgres pg] (.stop pg))
120311
(ns embedded-pg (:import [ru.yandex.qatools.embed.postgresql EmbeddedPostgres] [de.flapdoodle.embed.process.distribution IVersion] [ru.yandex.qatools.embed.postgresql.util SocketUtil])) (defn- ->iversion [version] (if (instance? IVersion version) version (reify IVersion (asInDownloadPath [_] (str version))))) (defn ^EmbeddedPostgres make "See [IVersion definitions](https://github.com/yandex-qatools/postgresql-embedded/blob/master/src/main/java/ru/yandex/qatools/embed/postgresql/distribution/Version.java) for more info. * version - a version string or an IVersion, e.g. 9.5.7-1 * data-dir - name of the directory e.g. /tmp/data" [{:keys [version data-dir]}] (EmbeddedPostgres. (->iversion version) data-dir)) (defn start! [^EmbeddedPostgres pg {:keys [runtime-config host port db-name user password params] :or {runtime-config (EmbeddedPostgres/defaultRuntimeConfig) host "localhost", port (SocketUtil/findFreePort) db-name "postgres", user "postgres", password "<PASSWORD>" params ["-E" "SQL_ASCII" "--locale=C" "--lc-collate=C" "--lc-ctype=C"]}}] (.start pg host port db-name user password params)) (defn stop! [^EmbeddedPostgres pg] (.stop pg))
true
(ns embedded-pg (:import [ru.yandex.qatools.embed.postgresql EmbeddedPostgres] [de.flapdoodle.embed.process.distribution IVersion] [ru.yandex.qatools.embed.postgresql.util SocketUtil])) (defn- ->iversion [version] (if (instance? IVersion version) version (reify IVersion (asInDownloadPath [_] (str version))))) (defn ^EmbeddedPostgres make "See [IVersion definitions](https://github.com/yandex-qatools/postgresql-embedded/blob/master/src/main/java/ru/yandex/qatools/embed/postgresql/distribution/Version.java) for more info. * version - a version string or an IVersion, e.g. 9.5.7-1 * data-dir - name of the directory e.g. /tmp/data" [{:keys [version data-dir]}] (EmbeddedPostgres. (->iversion version) data-dir)) (defn start! [^EmbeddedPostgres pg {:keys [runtime-config host port db-name user password params] :or {runtime-config (EmbeddedPostgres/defaultRuntimeConfig) host "localhost", port (SocketUtil/findFreePort) db-name "postgres", user "postgres", password "PI:PASSWORD:<PASSWORD>END_PI" params ["-E" "SQL_ASCII" "--locale=C" "--lc-collate=C" "--lc-ctype=C"]}}] (.start pg host port db-name user password params)) (defn stop! [^EmbeddedPostgres pg] (.stop pg))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998728632926941, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "tice, or any other, from this software.\n\n; Author: Stuart Halloway, Daniel Solano Gómez\n\n(ns clojure.test-clojure.ve", "end": 489, "score": 0.9998846054077148, "start": 474, "tag": "NAME", "value": "Stuart Halloway" }, { "context": "r, from this software.\n\n; Author: Stuart Halloway, Daniel Solano Gómez\n\n(ns clojure.test-clojure.vectors\n (:use clojure", "end": 510, "score": 0.9998695254325867, "start": 491, "tag": "NAME", "value": "Daniel Solano Gómez" } ]
Chapter 07 Code/niko/clojure/test/clojure/test_clojure/vectors.clj
PacktPublishing/Clojure-Programming-Cookbook
14
; 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: Stuart Halloway, Daniel Solano Gómez (ns clojure.test-clojure.vectors (:use clojure.test)) (deftest test-reversed-vec (let [r (range 6) v (into (vector-of :int) r) reversed (.rseq v)] (testing "returns the right impl" (is (= clojure.lang.APersistentVector$RSeq (class reversed)))) (testing "RSeq methods" (is (= [5 4 3 2 1 0] reversed)) (is (= 5 (.index reversed))) (is (= 5 (.first reversed))) (is (= [4 3 2 1 0] (.next reversed))) (is (= [3 2 1 0] (.. reversed next next))) (is (= 6 (.count reversed)))) (testing "clojure calling through" (is (= 5 (first reversed))) (is (= 5 (nth reversed 0)))) (testing "empty reverses to nil" (is (nil? (.. v empty rseq)))))) (deftest test-vecseq (let [r (range 100) vs (into (vector-of :int) r) vs-1 (next vs) vs-32 (.chunkedNext (seq vs))] (testing "=" (are [a b] (= a b) vs vs vs-1 vs-1 vs-32 vs-32) (are [a b] (not= a b) vs vs-1 vs-1 vs vs vs-32 vs-32 vs)) (testing "IPersistentCollection.empty" (are [a] (identical? clojure.lang.PersistentList/EMPTY (.empty (seq a))) vs vs-1 vs-32)) (testing "IPersistentCollection.cons" (are [result input] (= result (.cons input :foo)) [:foo 1] (seq (into (vector-of :int) [1])))) (testing "IPersistentCollection.count" (are [ct s] (= ct (.count (seq s))) 100 vs 99 vs-1 68 vs-32) ;; can't manufacture this scenario: ASeq defers to Counted, but ;; LazySeq doesn't, so Counted never gets checked on reified seq below #_(testing "hops to counted when available" (is (= 200 (.count (concat (seq vs) (reify clojure.lang.ISeq (seq [this] this) clojure.lang.Counted (count [_] 100)))))))) (testing "IPersistentCollection.equiv" (are [a b] (true? (.equiv a b)) vs vs vs-1 vs-1 vs-32 vs-32 vs r) (are [a b] (false? (.equiv a b)) vs vs-1 vs-1 vs vs vs-32 vs-32 vs vs nil)) (testing "internal-reduce" (is (= [99] (into [] (drop 99 vs))))))) (deftest test-primitive-subvector-reduce ;; regression test for CLJ-1082 (is (== 60 (let [prim-vec (into (vector-of :long) (range 1000))] (reduce + (subvec prim-vec 10 15)))))) (deftest test-vec-compare (let [nums (range 1 100) ; randomly replaces a single item with the given value rand-replace (fn[val] (let [r (rand-int 99)] (concat (take r nums) [val] (drop (inc r) nums)))) ; all num sequences in map num-seqs {:standard nums :empty '() ; different lengths :longer (concat nums [100]) :shorter (drop-last nums) ; greater by value :first-greater (concat [100] (next nums)) :last-greater (concat (drop-last nums) [100]) :rand-greater-1 (rand-replace 100) :rand-greater-2 (rand-replace 100) :rand-greater-3 (rand-replace 100) ; lesser by value :first-lesser (concat [0] (next nums)) :last-lesser (concat (drop-last nums) [0]) :rand-lesser-1 (rand-replace 0) :rand-lesser-2 (rand-replace 0) :rand-lesser-3 (rand-replace 0)} ; a way to create compare values based on num-seqs create-vals (fn[base-val] (zipmap (keys num-seqs) (map #(into base-val %1) (vals num-seqs)))) ; Vecs made of int primitives int-vecs (create-vals (vector-of :int)) ; Vecs made of long primitives long-vecs (create-vals (vector-of :long)) ; standard boxing vectors regular-vecs (create-vals []) ; the standard int Vec for comparisons int-vec (:standard int-vecs)] (testing "compare" (testing "identical" (is (= 0 (compare int-vec int-vec)))) (testing "equivalent" (are [x y] (= 0 (compare x y)) ; standard int-vec (:standard long-vecs) (:standard long-vecs) int-vec int-vec (:standard regular-vecs) (:standard regular-vecs) int-vec ; empty (:empty int-vecs) (:empty long-vecs) (:empty long-vecs) (:empty int-vecs))) (testing "lesser" (are [x] (= -1 (compare int-vec x)) (:longer int-vecs) (:longer long-vecs) (:longer regular-vecs) (:first-greater int-vecs) (:first-greater long-vecs) (:first-greater regular-vecs) (:last-greater int-vecs) (:last-greater long-vecs) (:last-greater regular-vecs) (:rand-greater-1 int-vecs) (:rand-greater-1 long-vecs) (:rand-greater-1 regular-vecs) (:rand-greater-2 int-vecs) (:rand-greater-2 long-vecs) (:rand-greater-2 regular-vecs) (:rand-greater-3 int-vecs) (:rand-greater-3 long-vecs) (:rand-greater-3 regular-vecs)) (are [x] (= -1 (compare x int-vec)) nil (:empty int-vecs) (:empty long-vecs) (:empty regular-vecs) (:shorter int-vecs) (:shorter long-vecs) (:shorter regular-vecs) (:first-lesser int-vecs) (:first-lesser long-vecs) (:first-lesser regular-vecs) (:last-lesser int-vecs) (:last-lesser long-vecs) (:last-lesser regular-vecs) (:rand-lesser-1 int-vecs) (:rand-lesser-1 long-vecs) (:rand-lesser-1 regular-vecs) (:rand-lesser-2 int-vecs) (:rand-lesser-2 long-vecs) (:rand-lesser-2 regular-vecs) (:rand-lesser-3 int-vecs) (:rand-lesser-3 long-vecs) (:rand-lesser-3 regular-vecs))) (testing "greater" (are [x] (= 1 (compare int-vec x)) nil (:empty int-vecs) (:empty long-vecs) (:empty regular-vecs) (:shorter int-vecs) (:shorter long-vecs) (:shorter regular-vecs) (:first-lesser int-vecs) (:first-lesser long-vecs) (:first-lesser regular-vecs) (:last-lesser int-vecs) (:last-lesser long-vecs) (:last-lesser regular-vecs) (:rand-lesser-1 int-vecs) (:rand-lesser-1 long-vecs) (:rand-lesser-1 regular-vecs) (:rand-lesser-2 int-vecs) (:rand-lesser-2 long-vecs) (:rand-lesser-2 regular-vecs) (:rand-lesser-3 int-vecs) (:rand-lesser-3 long-vecs) (:rand-lesser-3 regular-vecs)) (are [x] (= 1 (compare x int-vec)) (:longer int-vecs) (:longer long-vecs) (:longer regular-vecs) (:first-greater int-vecs) (:first-greater long-vecs) (:first-greater regular-vecs) (:last-greater int-vecs) (:last-greater long-vecs) (:last-greater regular-vecs) (:rand-greater-1 int-vecs) (:rand-greater-1 long-vecs) (:rand-greater-1 regular-vecs) (:rand-greater-2 int-vecs) (:rand-greater-2 long-vecs) (:rand-greater-2 regular-vecs) (:rand-greater-3 int-vecs) (:rand-greater-3 long-vecs) (:rand-greater-3 regular-vecs)))) (testing "Comparable.compareTo" (testing "incompatible" (is (thrown? NullPointerException (.compareTo int-vec nil))) (are [x] (thrown? ClassCastException (.compareTo int-vec x)) '() {} #{} (sorted-set) (sorted-map) nums 1)) (testing "identical" (is (= 0 (.compareTo int-vec int-vec)))) (testing "equivalent" (are [x] (= 0 (.compareTo int-vec x)) (:standard long-vecs) (:standard regular-vecs))) (testing "lesser" (are [x] (= -1 (.compareTo int-vec x)) (:longer int-vecs) (:longer long-vecs) (:longer regular-vecs) (:first-greater int-vecs) (:first-greater long-vecs) (:first-greater regular-vecs) (:last-greater int-vecs) (:last-greater long-vecs) (:last-greater regular-vecs) (:rand-greater-1 int-vecs) (:rand-greater-1 long-vecs) (:rand-greater-1 regular-vecs) (:rand-greater-2 int-vecs) (:rand-greater-2 long-vecs) (:rand-greater-2 regular-vecs) (:rand-greater-3 int-vecs) (:rand-greater-3 long-vecs) (:rand-greater-3 regular-vecs))) (testing "greater" (are [x] (= 1 (.compareTo int-vec x)) (:empty int-vecs) (:empty long-vecs) (:empty regular-vecs) (:shorter int-vecs) (:shorter long-vecs) (:shorter regular-vecs) (:first-lesser int-vecs) (:first-lesser long-vecs) (:first-lesser regular-vecs) (:last-lesser int-vecs) (:last-lesser long-vecs) (:last-lesser regular-vecs) (:rand-lesser-1 int-vecs) (:rand-lesser-1 long-vecs) (:rand-lesser-1 regular-vecs) (:rand-lesser-2 int-vecs) (:rand-lesser-2 long-vecs) (:rand-lesser-2 regular-vecs) (:rand-lesser-3 int-vecs) (:rand-lesser-3 long-vecs) (:rand-lesser-3 regular-vecs)))))) (deftest test-vec-associative (let [empty-v (vector-of :long) v (into empty-v (range 1 6))] (testing "Associative.containsKey" (are [x] (.containsKey v x) 0 1 2 3 4) (are [x] (not (.containsKey v x)) -1 -100 nil [] "" #"" #{} 5 100) (are [x] (not (.containsKey empty-v x)) 0 1)) (testing "contains?" (are [x] (contains? v x) 0 2 4) (are [x] (not (contains? v x)) -1 -100 nil "" 5 100) (are [x] (not (contains? empty-v x)) 0 1)) (testing "Associative.entryAt" (are [idx val] (= (clojure.lang.MapEntry. idx val) (.entryAt v idx)) 0 1 2 3 4 5) (are [idx] (nil? (.entryAt v idx)) -5 -1 5 10 nil "") (are [idx] (nil? (.entryAt empty-v idx)) 0 1)))) (deftest test-vec-creation (testing "Plain (vector-of :type)" (are [x] (and (empty? x) (instance? clojure.core.Vec x)) (vector-of :boolean) (vector-of :byte) (vector-of :short) (vector-of :int) (vector-of :long) (vector-of :float) (vector-of :double) (vector-of :char)) (testing "with invalid type argument" (are [x] (thrown? NullPointerException x) (vector-of nil) (vector-of Float/TYPE) (vector-of 'int) (vector-of "")))) (testing "vector-like (vector-of :type x1 x2 x3 … xn)" (are [vec gvec] (and (instance? clojure.core.Vec gvec) (= (into (vector-of :int) vec) gvec) (= vec gvec) (= (hash vec) (hash gvec))) [1] (vector-of :int 1) [1 2] (vector-of :int 1 2) [1 2 3] (vector-of :int 1 2 3) [1 2 3 4] (vector-of :int 1 2 3 4) [1 2 3 4 5] (vector-of :int 1 2 3 4 5) [1 2 3 4 5 6] (vector-of :int 1 2 3 4 5 6) (apply vector (range 1000)) (apply vector-of :int (range 1000)) [1 2 3] (vector-of :int 1M 2.0 3.1) [97 98 99] (vector-of :int \a \b \c)) (testing "with null values" (are [x] (thrown? NullPointerException x) (vector-of :int nil) (vector-of :int 1 nil) (vector-of :int 1 2 nil) (vector-of :int 1 2 3 nil) (vector-of :int 1 2 3 4 nil) (vector-of :int 1 2 3 4 5 nil) (vector-of :int 1 2 3 4 5 6 nil))) (testing "with unsupported values" (are [x] (thrown? ClassCastException x) (vector-of :int true) (vector-of :int 1 2 3 4 5 false) (vector-of :int {:a 1 :b 2}) (vector-of :int [1 2 3 4] [5 6]) (vector-of :int '(1 2 3 4)) (vector-of :int #{1 2 3 4}) (vector-of :int (sorted-set 1 2 3 4)) (vector-of :int 1 2 "3") (vector-of :int "1" "2" "3"))))) (deftest empty-vector-equality (let [colls [[] (vector-of :long) '()]] (doseq [c1 colls, c2 colls] (is (= c1 c2)) (is (.equals c1 c2))))) (defn =vec [expected v] (and (vector? v) (= expected v))) (deftest test-mapv (are [r c1] (=vec r (mapv + c1)) [1 2 3] [1 2 3]) (are [r c1 c2] (=vec r (mapv + c1 c2)) [2 3 4] [1 2 3] (repeat 1)) (are [r c1 c2 c3] (=vec r (mapv + c1 c2 c3)) [3 4 5] [1 2 3] (repeat 1) (repeat 1)) (are [r c1 c2 c3 c4] (=vec r (mapv + c1 c2 c3 c4)) [4 5 6] [1 2 3] [1 1 1] [1 1 1] [1 1 1])) (deftest test-filterv (are [r c1] (=vec r (filterv even? c1)) [] [1 3 5] [2 4] [1 2 3 4 5])) (deftest test-subvec (let [v1 (vec (range 100)) v2 (subvec v1 50 57)] (is (thrown? IndexOutOfBoundsException (v2 -1))) (is (thrown? IndexOutOfBoundsException (v2 7))) (is (= (v1 50) (v2 0))) (is (= (v1 56) (v2 6))))) (deftest test-vec (is (= [1 2] (vec (first {1 2})))) (is (= [0 1 2 3] (vec [0 1 2 3]))) (is (= [0 1 2 3] (vec (list 0 1 2 3)))) (is (= [0 1 2 3] (vec (sorted-set 0 1 2 3)))) (is (= [[1 2] [3 4]] (vec (sorted-map 1 2 3 4)))) (is (= [0 1 2 3] (vec (range 4)))) (is (= [\a \b \c \d] (vec "abcd"))) (is (= [0 1 2 3] (vec (object-array (range 4))))) (is (= [1 2 3 4] (vec (eduction (map inc) (range 4))))) (is (= [0 1 2 3] (vec (reify clojure.lang.IReduceInit (reduce [_ f start] (reduce f start (range 4))))))))
51995
; 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>, <NAME> (ns clojure.test-clojure.vectors (:use clojure.test)) (deftest test-reversed-vec (let [r (range 6) v (into (vector-of :int) r) reversed (.rseq v)] (testing "returns the right impl" (is (= clojure.lang.APersistentVector$RSeq (class reversed)))) (testing "RSeq methods" (is (= [5 4 3 2 1 0] reversed)) (is (= 5 (.index reversed))) (is (= 5 (.first reversed))) (is (= [4 3 2 1 0] (.next reversed))) (is (= [3 2 1 0] (.. reversed next next))) (is (= 6 (.count reversed)))) (testing "clojure calling through" (is (= 5 (first reversed))) (is (= 5 (nth reversed 0)))) (testing "empty reverses to nil" (is (nil? (.. v empty rseq)))))) (deftest test-vecseq (let [r (range 100) vs (into (vector-of :int) r) vs-1 (next vs) vs-32 (.chunkedNext (seq vs))] (testing "=" (are [a b] (= a b) vs vs vs-1 vs-1 vs-32 vs-32) (are [a b] (not= a b) vs vs-1 vs-1 vs vs vs-32 vs-32 vs)) (testing "IPersistentCollection.empty" (are [a] (identical? clojure.lang.PersistentList/EMPTY (.empty (seq a))) vs vs-1 vs-32)) (testing "IPersistentCollection.cons" (are [result input] (= result (.cons input :foo)) [:foo 1] (seq (into (vector-of :int) [1])))) (testing "IPersistentCollection.count" (are [ct s] (= ct (.count (seq s))) 100 vs 99 vs-1 68 vs-32) ;; can't manufacture this scenario: ASeq defers to Counted, but ;; LazySeq doesn't, so Counted never gets checked on reified seq below #_(testing "hops to counted when available" (is (= 200 (.count (concat (seq vs) (reify clojure.lang.ISeq (seq [this] this) clojure.lang.Counted (count [_] 100)))))))) (testing "IPersistentCollection.equiv" (are [a b] (true? (.equiv a b)) vs vs vs-1 vs-1 vs-32 vs-32 vs r) (are [a b] (false? (.equiv a b)) vs vs-1 vs-1 vs vs vs-32 vs-32 vs vs nil)) (testing "internal-reduce" (is (= [99] (into [] (drop 99 vs))))))) (deftest test-primitive-subvector-reduce ;; regression test for CLJ-1082 (is (== 60 (let [prim-vec (into (vector-of :long) (range 1000))] (reduce + (subvec prim-vec 10 15)))))) (deftest test-vec-compare (let [nums (range 1 100) ; randomly replaces a single item with the given value rand-replace (fn[val] (let [r (rand-int 99)] (concat (take r nums) [val] (drop (inc r) nums)))) ; all num sequences in map num-seqs {:standard nums :empty '() ; different lengths :longer (concat nums [100]) :shorter (drop-last nums) ; greater by value :first-greater (concat [100] (next nums)) :last-greater (concat (drop-last nums) [100]) :rand-greater-1 (rand-replace 100) :rand-greater-2 (rand-replace 100) :rand-greater-3 (rand-replace 100) ; lesser by value :first-lesser (concat [0] (next nums)) :last-lesser (concat (drop-last nums) [0]) :rand-lesser-1 (rand-replace 0) :rand-lesser-2 (rand-replace 0) :rand-lesser-3 (rand-replace 0)} ; a way to create compare values based on num-seqs create-vals (fn[base-val] (zipmap (keys num-seqs) (map #(into base-val %1) (vals num-seqs)))) ; Vecs made of int primitives int-vecs (create-vals (vector-of :int)) ; Vecs made of long primitives long-vecs (create-vals (vector-of :long)) ; standard boxing vectors regular-vecs (create-vals []) ; the standard int Vec for comparisons int-vec (:standard int-vecs)] (testing "compare" (testing "identical" (is (= 0 (compare int-vec int-vec)))) (testing "equivalent" (are [x y] (= 0 (compare x y)) ; standard int-vec (:standard long-vecs) (:standard long-vecs) int-vec int-vec (:standard regular-vecs) (:standard regular-vecs) int-vec ; empty (:empty int-vecs) (:empty long-vecs) (:empty long-vecs) (:empty int-vecs))) (testing "lesser" (are [x] (= -1 (compare int-vec x)) (:longer int-vecs) (:longer long-vecs) (:longer regular-vecs) (:first-greater int-vecs) (:first-greater long-vecs) (:first-greater regular-vecs) (:last-greater int-vecs) (:last-greater long-vecs) (:last-greater regular-vecs) (:rand-greater-1 int-vecs) (:rand-greater-1 long-vecs) (:rand-greater-1 regular-vecs) (:rand-greater-2 int-vecs) (:rand-greater-2 long-vecs) (:rand-greater-2 regular-vecs) (:rand-greater-3 int-vecs) (:rand-greater-3 long-vecs) (:rand-greater-3 regular-vecs)) (are [x] (= -1 (compare x int-vec)) nil (:empty int-vecs) (:empty long-vecs) (:empty regular-vecs) (:shorter int-vecs) (:shorter long-vecs) (:shorter regular-vecs) (:first-lesser int-vecs) (:first-lesser long-vecs) (:first-lesser regular-vecs) (:last-lesser int-vecs) (:last-lesser long-vecs) (:last-lesser regular-vecs) (:rand-lesser-1 int-vecs) (:rand-lesser-1 long-vecs) (:rand-lesser-1 regular-vecs) (:rand-lesser-2 int-vecs) (:rand-lesser-2 long-vecs) (:rand-lesser-2 regular-vecs) (:rand-lesser-3 int-vecs) (:rand-lesser-3 long-vecs) (:rand-lesser-3 regular-vecs))) (testing "greater" (are [x] (= 1 (compare int-vec x)) nil (:empty int-vecs) (:empty long-vecs) (:empty regular-vecs) (:shorter int-vecs) (:shorter long-vecs) (:shorter regular-vecs) (:first-lesser int-vecs) (:first-lesser long-vecs) (:first-lesser regular-vecs) (:last-lesser int-vecs) (:last-lesser long-vecs) (:last-lesser regular-vecs) (:rand-lesser-1 int-vecs) (:rand-lesser-1 long-vecs) (:rand-lesser-1 regular-vecs) (:rand-lesser-2 int-vecs) (:rand-lesser-2 long-vecs) (:rand-lesser-2 regular-vecs) (:rand-lesser-3 int-vecs) (:rand-lesser-3 long-vecs) (:rand-lesser-3 regular-vecs)) (are [x] (= 1 (compare x int-vec)) (:longer int-vecs) (:longer long-vecs) (:longer regular-vecs) (:first-greater int-vecs) (:first-greater long-vecs) (:first-greater regular-vecs) (:last-greater int-vecs) (:last-greater long-vecs) (:last-greater regular-vecs) (:rand-greater-1 int-vecs) (:rand-greater-1 long-vecs) (:rand-greater-1 regular-vecs) (:rand-greater-2 int-vecs) (:rand-greater-2 long-vecs) (:rand-greater-2 regular-vecs) (:rand-greater-3 int-vecs) (:rand-greater-3 long-vecs) (:rand-greater-3 regular-vecs)))) (testing "Comparable.compareTo" (testing "incompatible" (is (thrown? NullPointerException (.compareTo int-vec nil))) (are [x] (thrown? ClassCastException (.compareTo int-vec x)) '() {} #{} (sorted-set) (sorted-map) nums 1)) (testing "identical" (is (= 0 (.compareTo int-vec int-vec)))) (testing "equivalent" (are [x] (= 0 (.compareTo int-vec x)) (:standard long-vecs) (:standard regular-vecs))) (testing "lesser" (are [x] (= -1 (.compareTo int-vec x)) (:longer int-vecs) (:longer long-vecs) (:longer regular-vecs) (:first-greater int-vecs) (:first-greater long-vecs) (:first-greater regular-vecs) (:last-greater int-vecs) (:last-greater long-vecs) (:last-greater regular-vecs) (:rand-greater-1 int-vecs) (:rand-greater-1 long-vecs) (:rand-greater-1 regular-vecs) (:rand-greater-2 int-vecs) (:rand-greater-2 long-vecs) (:rand-greater-2 regular-vecs) (:rand-greater-3 int-vecs) (:rand-greater-3 long-vecs) (:rand-greater-3 regular-vecs))) (testing "greater" (are [x] (= 1 (.compareTo int-vec x)) (:empty int-vecs) (:empty long-vecs) (:empty regular-vecs) (:shorter int-vecs) (:shorter long-vecs) (:shorter regular-vecs) (:first-lesser int-vecs) (:first-lesser long-vecs) (:first-lesser regular-vecs) (:last-lesser int-vecs) (:last-lesser long-vecs) (:last-lesser regular-vecs) (:rand-lesser-1 int-vecs) (:rand-lesser-1 long-vecs) (:rand-lesser-1 regular-vecs) (:rand-lesser-2 int-vecs) (:rand-lesser-2 long-vecs) (:rand-lesser-2 regular-vecs) (:rand-lesser-3 int-vecs) (:rand-lesser-3 long-vecs) (:rand-lesser-3 regular-vecs)))))) (deftest test-vec-associative (let [empty-v (vector-of :long) v (into empty-v (range 1 6))] (testing "Associative.containsKey" (are [x] (.containsKey v x) 0 1 2 3 4) (are [x] (not (.containsKey v x)) -1 -100 nil [] "" #"" #{} 5 100) (are [x] (not (.containsKey empty-v x)) 0 1)) (testing "contains?" (are [x] (contains? v x) 0 2 4) (are [x] (not (contains? v x)) -1 -100 nil "" 5 100) (are [x] (not (contains? empty-v x)) 0 1)) (testing "Associative.entryAt" (are [idx val] (= (clojure.lang.MapEntry. idx val) (.entryAt v idx)) 0 1 2 3 4 5) (are [idx] (nil? (.entryAt v idx)) -5 -1 5 10 nil "") (are [idx] (nil? (.entryAt empty-v idx)) 0 1)))) (deftest test-vec-creation (testing "Plain (vector-of :type)" (are [x] (and (empty? x) (instance? clojure.core.Vec x)) (vector-of :boolean) (vector-of :byte) (vector-of :short) (vector-of :int) (vector-of :long) (vector-of :float) (vector-of :double) (vector-of :char)) (testing "with invalid type argument" (are [x] (thrown? NullPointerException x) (vector-of nil) (vector-of Float/TYPE) (vector-of 'int) (vector-of "")))) (testing "vector-like (vector-of :type x1 x2 x3 … xn)" (are [vec gvec] (and (instance? clojure.core.Vec gvec) (= (into (vector-of :int) vec) gvec) (= vec gvec) (= (hash vec) (hash gvec))) [1] (vector-of :int 1) [1 2] (vector-of :int 1 2) [1 2 3] (vector-of :int 1 2 3) [1 2 3 4] (vector-of :int 1 2 3 4) [1 2 3 4 5] (vector-of :int 1 2 3 4 5) [1 2 3 4 5 6] (vector-of :int 1 2 3 4 5 6) (apply vector (range 1000)) (apply vector-of :int (range 1000)) [1 2 3] (vector-of :int 1M 2.0 3.1) [97 98 99] (vector-of :int \a \b \c)) (testing "with null values" (are [x] (thrown? NullPointerException x) (vector-of :int nil) (vector-of :int 1 nil) (vector-of :int 1 2 nil) (vector-of :int 1 2 3 nil) (vector-of :int 1 2 3 4 nil) (vector-of :int 1 2 3 4 5 nil) (vector-of :int 1 2 3 4 5 6 nil))) (testing "with unsupported values" (are [x] (thrown? ClassCastException x) (vector-of :int true) (vector-of :int 1 2 3 4 5 false) (vector-of :int {:a 1 :b 2}) (vector-of :int [1 2 3 4] [5 6]) (vector-of :int '(1 2 3 4)) (vector-of :int #{1 2 3 4}) (vector-of :int (sorted-set 1 2 3 4)) (vector-of :int 1 2 "3") (vector-of :int "1" "2" "3"))))) (deftest empty-vector-equality (let [colls [[] (vector-of :long) '()]] (doseq [c1 colls, c2 colls] (is (= c1 c2)) (is (.equals c1 c2))))) (defn =vec [expected v] (and (vector? v) (= expected v))) (deftest test-mapv (are [r c1] (=vec r (mapv + c1)) [1 2 3] [1 2 3]) (are [r c1 c2] (=vec r (mapv + c1 c2)) [2 3 4] [1 2 3] (repeat 1)) (are [r c1 c2 c3] (=vec r (mapv + c1 c2 c3)) [3 4 5] [1 2 3] (repeat 1) (repeat 1)) (are [r c1 c2 c3 c4] (=vec r (mapv + c1 c2 c3 c4)) [4 5 6] [1 2 3] [1 1 1] [1 1 1] [1 1 1])) (deftest test-filterv (are [r c1] (=vec r (filterv even? c1)) [] [1 3 5] [2 4] [1 2 3 4 5])) (deftest test-subvec (let [v1 (vec (range 100)) v2 (subvec v1 50 57)] (is (thrown? IndexOutOfBoundsException (v2 -1))) (is (thrown? IndexOutOfBoundsException (v2 7))) (is (= (v1 50) (v2 0))) (is (= (v1 56) (v2 6))))) (deftest test-vec (is (= [1 2] (vec (first {1 2})))) (is (= [0 1 2 3] (vec [0 1 2 3]))) (is (= [0 1 2 3] (vec (list 0 1 2 3)))) (is (= [0 1 2 3] (vec (sorted-set 0 1 2 3)))) (is (= [[1 2] [3 4]] (vec (sorted-map 1 2 3 4)))) (is (= [0 1 2 3] (vec (range 4)))) (is (= [\a \b \c \d] (vec "abcd"))) (is (= [0 1 2 3] (vec (object-array (range 4))))) (is (= [1 2 3 4] (vec (eduction (map inc) (range 4))))) (is (= [0 1 2 3] (vec (reify clojure.lang.IReduceInit (reduce [_ f start] (reduce f start (range 4))))))))
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, PI:NAME:<NAME>END_PI (ns clojure.test-clojure.vectors (:use clojure.test)) (deftest test-reversed-vec (let [r (range 6) v (into (vector-of :int) r) reversed (.rseq v)] (testing "returns the right impl" (is (= clojure.lang.APersistentVector$RSeq (class reversed)))) (testing "RSeq methods" (is (= [5 4 3 2 1 0] reversed)) (is (= 5 (.index reversed))) (is (= 5 (.first reversed))) (is (= [4 3 2 1 0] (.next reversed))) (is (= [3 2 1 0] (.. reversed next next))) (is (= 6 (.count reversed)))) (testing "clojure calling through" (is (= 5 (first reversed))) (is (= 5 (nth reversed 0)))) (testing "empty reverses to nil" (is (nil? (.. v empty rseq)))))) (deftest test-vecseq (let [r (range 100) vs (into (vector-of :int) r) vs-1 (next vs) vs-32 (.chunkedNext (seq vs))] (testing "=" (are [a b] (= a b) vs vs vs-1 vs-1 vs-32 vs-32) (are [a b] (not= a b) vs vs-1 vs-1 vs vs vs-32 vs-32 vs)) (testing "IPersistentCollection.empty" (are [a] (identical? clojure.lang.PersistentList/EMPTY (.empty (seq a))) vs vs-1 vs-32)) (testing "IPersistentCollection.cons" (are [result input] (= result (.cons input :foo)) [:foo 1] (seq (into (vector-of :int) [1])))) (testing "IPersistentCollection.count" (are [ct s] (= ct (.count (seq s))) 100 vs 99 vs-1 68 vs-32) ;; can't manufacture this scenario: ASeq defers to Counted, but ;; LazySeq doesn't, so Counted never gets checked on reified seq below #_(testing "hops to counted when available" (is (= 200 (.count (concat (seq vs) (reify clojure.lang.ISeq (seq [this] this) clojure.lang.Counted (count [_] 100)))))))) (testing "IPersistentCollection.equiv" (are [a b] (true? (.equiv a b)) vs vs vs-1 vs-1 vs-32 vs-32 vs r) (are [a b] (false? (.equiv a b)) vs vs-1 vs-1 vs vs vs-32 vs-32 vs vs nil)) (testing "internal-reduce" (is (= [99] (into [] (drop 99 vs))))))) (deftest test-primitive-subvector-reduce ;; regression test for CLJ-1082 (is (== 60 (let [prim-vec (into (vector-of :long) (range 1000))] (reduce + (subvec prim-vec 10 15)))))) (deftest test-vec-compare (let [nums (range 1 100) ; randomly replaces a single item with the given value rand-replace (fn[val] (let [r (rand-int 99)] (concat (take r nums) [val] (drop (inc r) nums)))) ; all num sequences in map num-seqs {:standard nums :empty '() ; different lengths :longer (concat nums [100]) :shorter (drop-last nums) ; greater by value :first-greater (concat [100] (next nums)) :last-greater (concat (drop-last nums) [100]) :rand-greater-1 (rand-replace 100) :rand-greater-2 (rand-replace 100) :rand-greater-3 (rand-replace 100) ; lesser by value :first-lesser (concat [0] (next nums)) :last-lesser (concat (drop-last nums) [0]) :rand-lesser-1 (rand-replace 0) :rand-lesser-2 (rand-replace 0) :rand-lesser-3 (rand-replace 0)} ; a way to create compare values based on num-seqs create-vals (fn[base-val] (zipmap (keys num-seqs) (map #(into base-val %1) (vals num-seqs)))) ; Vecs made of int primitives int-vecs (create-vals (vector-of :int)) ; Vecs made of long primitives long-vecs (create-vals (vector-of :long)) ; standard boxing vectors regular-vecs (create-vals []) ; the standard int Vec for comparisons int-vec (:standard int-vecs)] (testing "compare" (testing "identical" (is (= 0 (compare int-vec int-vec)))) (testing "equivalent" (are [x y] (= 0 (compare x y)) ; standard int-vec (:standard long-vecs) (:standard long-vecs) int-vec int-vec (:standard regular-vecs) (:standard regular-vecs) int-vec ; empty (:empty int-vecs) (:empty long-vecs) (:empty long-vecs) (:empty int-vecs))) (testing "lesser" (are [x] (= -1 (compare int-vec x)) (:longer int-vecs) (:longer long-vecs) (:longer regular-vecs) (:first-greater int-vecs) (:first-greater long-vecs) (:first-greater regular-vecs) (:last-greater int-vecs) (:last-greater long-vecs) (:last-greater regular-vecs) (:rand-greater-1 int-vecs) (:rand-greater-1 long-vecs) (:rand-greater-1 regular-vecs) (:rand-greater-2 int-vecs) (:rand-greater-2 long-vecs) (:rand-greater-2 regular-vecs) (:rand-greater-3 int-vecs) (:rand-greater-3 long-vecs) (:rand-greater-3 regular-vecs)) (are [x] (= -1 (compare x int-vec)) nil (:empty int-vecs) (:empty long-vecs) (:empty regular-vecs) (:shorter int-vecs) (:shorter long-vecs) (:shorter regular-vecs) (:first-lesser int-vecs) (:first-lesser long-vecs) (:first-lesser regular-vecs) (:last-lesser int-vecs) (:last-lesser long-vecs) (:last-lesser regular-vecs) (:rand-lesser-1 int-vecs) (:rand-lesser-1 long-vecs) (:rand-lesser-1 regular-vecs) (:rand-lesser-2 int-vecs) (:rand-lesser-2 long-vecs) (:rand-lesser-2 regular-vecs) (:rand-lesser-3 int-vecs) (:rand-lesser-3 long-vecs) (:rand-lesser-3 regular-vecs))) (testing "greater" (are [x] (= 1 (compare int-vec x)) nil (:empty int-vecs) (:empty long-vecs) (:empty regular-vecs) (:shorter int-vecs) (:shorter long-vecs) (:shorter regular-vecs) (:first-lesser int-vecs) (:first-lesser long-vecs) (:first-lesser regular-vecs) (:last-lesser int-vecs) (:last-lesser long-vecs) (:last-lesser regular-vecs) (:rand-lesser-1 int-vecs) (:rand-lesser-1 long-vecs) (:rand-lesser-1 regular-vecs) (:rand-lesser-2 int-vecs) (:rand-lesser-2 long-vecs) (:rand-lesser-2 regular-vecs) (:rand-lesser-3 int-vecs) (:rand-lesser-3 long-vecs) (:rand-lesser-3 regular-vecs)) (are [x] (= 1 (compare x int-vec)) (:longer int-vecs) (:longer long-vecs) (:longer regular-vecs) (:first-greater int-vecs) (:first-greater long-vecs) (:first-greater regular-vecs) (:last-greater int-vecs) (:last-greater long-vecs) (:last-greater regular-vecs) (:rand-greater-1 int-vecs) (:rand-greater-1 long-vecs) (:rand-greater-1 regular-vecs) (:rand-greater-2 int-vecs) (:rand-greater-2 long-vecs) (:rand-greater-2 regular-vecs) (:rand-greater-3 int-vecs) (:rand-greater-3 long-vecs) (:rand-greater-3 regular-vecs)))) (testing "Comparable.compareTo" (testing "incompatible" (is (thrown? NullPointerException (.compareTo int-vec nil))) (are [x] (thrown? ClassCastException (.compareTo int-vec x)) '() {} #{} (sorted-set) (sorted-map) nums 1)) (testing "identical" (is (= 0 (.compareTo int-vec int-vec)))) (testing "equivalent" (are [x] (= 0 (.compareTo int-vec x)) (:standard long-vecs) (:standard regular-vecs))) (testing "lesser" (are [x] (= -1 (.compareTo int-vec x)) (:longer int-vecs) (:longer long-vecs) (:longer regular-vecs) (:first-greater int-vecs) (:first-greater long-vecs) (:first-greater regular-vecs) (:last-greater int-vecs) (:last-greater long-vecs) (:last-greater regular-vecs) (:rand-greater-1 int-vecs) (:rand-greater-1 long-vecs) (:rand-greater-1 regular-vecs) (:rand-greater-2 int-vecs) (:rand-greater-2 long-vecs) (:rand-greater-2 regular-vecs) (:rand-greater-3 int-vecs) (:rand-greater-3 long-vecs) (:rand-greater-3 regular-vecs))) (testing "greater" (are [x] (= 1 (.compareTo int-vec x)) (:empty int-vecs) (:empty long-vecs) (:empty regular-vecs) (:shorter int-vecs) (:shorter long-vecs) (:shorter regular-vecs) (:first-lesser int-vecs) (:first-lesser long-vecs) (:first-lesser regular-vecs) (:last-lesser int-vecs) (:last-lesser long-vecs) (:last-lesser regular-vecs) (:rand-lesser-1 int-vecs) (:rand-lesser-1 long-vecs) (:rand-lesser-1 regular-vecs) (:rand-lesser-2 int-vecs) (:rand-lesser-2 long-vecs) (:rand-lesser-2 regular-vecs) (:rand-lesser-3 int-vecs) (:rand-lesser-3 long-vecs) (:rand-lesser-3 regular-vecs)))))) (deftest test-vec-associative (let [empty-v (vector-of :long) v (into empty-v (range 1 6))] (testing "Associative.containsKey" (are [x] (.containsKey v x) 0 1 2 3 4) (are [x] (not (.containsKey v x)) -1 -100 nil [] "" #"" #{} 5 100) (are [x] (not (.containsKey empty-v x)) 0 1)) (testing "contains?" (are [x] (contains? v x) 0 2 4) (are [x] (not (contains? v x)) -1 -100 nil "" 5 100) (are [x] (not (contains? empty-v x)) 0 1)) (testing "Associative.entryAt" (are [idx val] (= (clojure.lang.MapEntry. idx val) (.entryAt v idx)) 0 1 2 3 4 5) (are [idx] (nil? (.entryAt v idx)) -5 -1 5 10 nil "") (are [idx] (nil? (.entryAt empty-v idx)) 0 1)))) (deftest test-vec-creation (testing "Plain (vector-of :type)" (are [x] (and (empty? x) (instance? clojure.core.Vec x)) (vector-of :boolean) (vector-of :byte) (vector-of :short) (vector-of :int) (vector-of :long) (vector-of :float) (vector-of :double) (vector-of :char)) (testing "with invalid type argument" (are [x] (thrown? NullPointerException x) (vector-of nil) (vector-of Float/TYPE) (vector-of 'int) (vector-of "")))) (testing "vector-like (vector-of :type x1 x2 x3 … xn)" (are [vec gvec] (and (instance? clojure.core.Vec gvec) (= (into (vector-of :int) vec) gvec) (= vec gvec) (= (hash vec) (hash gvec))) [1] (vector-of :int 1) [1 2] (vector-of :int 1 2) [1 2 3] (vector-of :int 1 2 3) [1 2 3 4] (vector-of :int 1 2 3 4) [1 2 3 4 5] (vector-of :int 1 2 3 4 5) [1 2 3 4 5 6] (vector-of :int 1 2 3 4 5 6) (apply vector (range 1000)) (apply vector-of :int (range 1000)) [1 2 3] (vector-of :int 1M 2.0 3.1) [97 98 99] (vector-of :int \a \b \c)) (testing "with null values" (are [x] (thrown? NullPointerException x) (vector-of :int nil) (vector-of :int 1 nil) (vector-of :int 1 2 nil) (vector-of :int 1 2 3 nil) (vector-of :int 1 2 3 4 nil) (vector-of :int 1 2 3 4 5 nil) (vector-of :int 1 2 3 4 5 6 nil))) (testing "with unsupported values" (are [x] (thrown? ClassCastException x) (vector-of :int true) (vector-of :int 1 2 3 4 5 false) (vector-of :int {:a 1 :b 2}) (vector-of :int [1 2 3 4] [5 6]) (vector-of :int '(1 2 3 4)) (vector-of :int #{1 2 3 4}) (vector-of :int (sorted-set 1 2 3 4)) (vector-of :int 1 2 "3") (vector-of :int "1" "2" "3"))))) (deftest empty-vector-equality (let [colls [[] (vector-of :long) '()]] (doseq [c1 colls, c2 colls] (is (= c1 c2)) (is (.equals c1 c2))))) (defn =vec [expected v] (and (vector? v) (= expected v))) (deftest test-mapv (are [r c1] (=vec r (mapv + c1)) [1 2 3] [1 2 3]) (are [r c1 c2] (=vec r (mapv + c1 c2)) [2 3 4] [1 2 3] (repeat 1)) (are [r c1 c2 c3] (=vec r (mapv + c1 c2 c3)) [3 4 5] [1 2 3] (repeat 1) (repeat 1)) (are [r c1 c2 c3 c4] (=vec r (mapv + c1 c2 c3 c4)) [4 5 6] [1 2 3] [1 1 1] [1 1 1] [1 1 1])) (deftest test-filterv (are [r c1] (=vec r (filterv even? c1)) [] [1 3 5] [2 4] [1 2 3 4 5])) (deftest test-subvec (let [v1 (vec (range 100)) v2 (subvec v1 50 57)] (is (thrown? IndexOutOfBoundsException (v2 -1))) (is (thrown? IndexOutOfBoundsException (v2 7))) (is (= (v1 50) (v2 0))) (is (= (v1 56) (v2 6))))) (deftest test-vec (is (= [1 2] (vec (first {1 2})))) (is (= [0 1 2 3] (vec [0 1 2 3]))) (is (= [0 1 2 3] (vec (list 0 1 2 3)))) (is (= [0 1 2 3] (vec (sorted-set 0 1 2 3)))) (is (= [[1 2] [3 4]] (vec (sorted-map 1 2 3 4)))) (is (= [0 1 2 3] (vec (range 4)))) (is (= [\a \b \c \d] (vec "abcd"))) (is (= [0 1 2 3] (vec (object-array (range 4))))) (is (= [1 2 3 4] (vec (eduction (map inc) (range 4))))) (is (= [0 1 2 3] (vec (reify clojure.lang.IReduceInit (reduce [_ f start] (reduce f start (range 4))))))))
[ { "context": "tion/json\"}\n :body (json/write-str '(\"Curie, Marie, marie.curie@radium.org, orange, 7/7/1867\"))}\n ", "end": 708, "score": 0.9980289340019226, "start": 696, "tag": "NAME", "value": "Curie, Marie" }, { "context": " :body (json/write-str '(\"Curie, Marie, marie.curie@radium.org, orange, 7/7/1867\"))}\n (web/myapp (mock/b", "end": 732, "score": 0.999926745891571, "start": 710, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "myapp (mock/body (mock/request :post \"/records\") \"Curie, Marie, marie.curie@radium.org, orange, 7/7/1867\")))))\n\n", "end": 831, "score": 0.9992218017578125, "start": 819, "tag": "NAME", "value": "Curie, Marie" }, { "context": "ody (mock/request :post \"/records\") \"Curie, Marie, marie.curie@radium.org, orange, 7/7/1867\")))))\n\n(deftest post-pipe-delim", "end": 855, "score": 0.9999231100082397, "start": 833, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "tion/json\"}\n :body (json/write-str '(\"Curie | Marie | marie.curie@radium.org | orange | 7/7/1", "end": 1027, "score": 0.9952155351638794, "start": 1022, "tag": "NAME", "value": "Curie" }, { "context": "on\"}\n :body (json/write-str '(\"Curie | Marie | marie.curie@radium.org | orange | 7/7/1867\"))}\n", "end": 1035, "score": 0.9181029796600342, "start": 1030, "tag": "NAME", "value": "Marie" }, { "context": " :body (json/write-str '(\"Curie | Marie | marie.curie@radium.org | orange | 7/7/1867\"))}\n (web/myapp (mock", "end": 1060, "score": 0.99992835521698, "start": 1038, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "myapp (mock/body (mock/request :post \"/records\") \"Curie | Marie | marie.curie@radium.org | orange | 7/7/186", "end": 1154, "score": 0.9536541104316711, "start": 1149, "tag": "NAME", "value": "Curie" }, { "context": "mock/body (mock/request :post \"/records\") \"Curie | Marie | marie.curie@radium.org | orange | 7/7/1867\"))))", "end": 1162, "score": 0.7951375246047974, "start": 1157, "tag": "NAME", "value": "Marie" }, { "context": "y (mock/request :post \"/records\") \"Curie | Marie | marie.curie@radium.org | orange | 7/7/1867\")))))\n\n(deftest post-ws-delim", "end": 1187, "score": 0.999927818775177, "start": 1165, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "tion/json\"}\n :body (json/write-str '(\"Curie Marie marie.curie@radium.org orange 7/7/1867\"))}\n ", "end": 1365, "score": 0.998954713344574, "start": 1354, "tag": "NAME", "value": "Curie Marie" }, { "context": "\n :body (json/write-str '(\"Curie Marie marie.curie@radium.org orange 7/7/1867\"))}\n (web/myapp (mock/bod", "end": 1388, "score": 0.9999250173568726, "start": 1366, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "myapp (mock/body (mock/request :post \"/records\") \"Curie Marie marie.curie@radium.org orange 7/7/1867\")))))\n\n(de", "end": 1484, "score": 0.9991334676742554, "start": 1473, "tag": "NAME", "value": "Curie Marie" }, { "context": "/body (mock/request :post \"/records\") \"Curie Marie marie.curie@radium.org orange 7/7/1867\")))))\n\n(defn load-data\n []\n (we", "end": 1507, "score": 0.9999286532402039, "start": 1485, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "myapp (mock/body (mock/request :post \"/records\") \"Röntgen|Wilhelm|xray@mail.com|white|3/27/1845\"))\n (web/m", "end": 1616, "score": 0.8371887803077698, "start": 1609, "tag": "NAME", "value": "Röntgen" }, { "context": "ock/body (mock/request :post \"/records\") \"Röntgen|Wilhelm|xray@mail.com|white|3/27/1845\"))\n (web/myapp (mo", "end": 1624, "score": 0.9699367880821228, "start": 1617, "tag": "NAME", "value": "Wilhelm" }, { "context": " (mock/request :post \"/records\") \"Röntgen|Wilhelm|xray@mail.com|white|3/27/1845\"))\n (web/myapp (mock/body (mock/", "end": 1638, "score": 0.9999217391014099, "start": 1625, "tag": "EMAIL", "value": "xray@mail.com" }, { "context": "myapp (mock/body (mock/request :post \"/records\") \"Lorentz | Hendrik | magneto@transform.com | red | 7/18/18", "end": 1722, "score": 0.98993980884552, "start": 1715, "tag": "NAME", "value": "Lorentz" }, { "context": "ck/body (mock/request :post \"/records\") \"Lorentz | Hendrik | magneto@transform.com | red | 7/18/1853\"))\n (w", "end": 1732, "score": 0.9984742999076843, "start": 1725, "tag": "NAME", "value": "Hendrik" }, { "context": "ock/request :post \"/records\") \"Lorentz | Hendrik | magneto@transform.com | red | 7/18/1853\"))\n (web/myapp (mock/body (moc", "end": 1756, "score": 0.9999300837516785, "start": 1735, "tag": "EMAIL", "value": "magneto@transform.com" }, { "context": "myapp (mock/body (mock/request :post \"/records\") \"Zeeman | Pieter | zman@doubledutch.nl | blue | 5/25/1865", "end": 1841, "score": 0.9720671772956848, "start": 1835, "tag": "NAME", "value": "Zeeman" }, { "context": "ock/body (mock/request :post \"/records\") \"Zeeman | Pieter | zman@doubledutch.nl | blue | 5/25/1865\"))\n (we", "end": 1850, "score": 0.9996607899665833, "start": 1844, "tag": "NAME", "value": "Pieter" }, { "context": "(mock/request :post \"/records\") \"Zeeman | Pieter | zman@doubledutch.nl | blue | 5/25/1865\"))\n (web/myapp (mock/body (mo", "end": 1872, "score": 0.9999300241470337, "start": 1853, "tag": "EMAIL", "value": "zman@doubledutch.nl" }, { "context": "myapp (mock/body (mock/request :post \"/records\") \"Curie|Marie|marie.curie@radium.org|orange|7/7/1867\")))\n", "end": 1957, "score": 0.9998412132263184, "start": 1952, "tag": "NAME", "value": "Curie" }, { "context": "(mock/body (mock/request :post \"/records\") \"Curie|Marie|marie.curie@radium.org|orange|7/7/1867\")))\n\n(deft", "end": 1963, "score": 0.9996237754821777, "start": 1958, "tag": "NAME", "value": "Marie" }, { "context": "body (mock/request :post \"/records\") \"Curie|Marie|marie.curie@radium.org|orange|7/7/1867\")))\n\n(deftest get-email-sorted\n ", "end": 1986, "score": 0.99992835521698, "start": 1964, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "\n :body (json/write-str [{:last-name \"Lorentz\" :first-name \"Hendrik\" :email \"magneto@transform.", "end": 2182, "score": 0.9997771978378296, "start": 2175, "tag": "NAME", "value": "Lorentz" }, { "context": "son/write-str [{:last-name \"Lorentz\" :first-name \"Hendrik\" :email \"magneto@transform.com\" :favorite-color \"", "end": 2204, "score": 0.9996482729911804, "start": 2197, "tag": "NAME", "value": "Hendrik" }, { "context": "last-name \"Lorentz\" :first-name \"Hendrik\" :email \"magneto@transform.com\" :favorite-color \"red\" :dob \"7/18/1853\"}\n ", "end": 2235, "score": 0.9999296069145203, "start": 2214, "tag": "EMAIL", "value": "magneto@transform.com" }, { "context": "\n {:last-name \"Curie\" :first-name \"Marie\" :email \"marie.curie@radium.o", "end": 2331, "score": 0.9998006820678711, "start": 2326, "tag": "NAME", "value": "Curie" }, { "context": " {:last-name \"Curie\" :first-name \"Marie\" :email \"marie.curie@radium.org\" :favorite-color ", "end": 2351, "score": 0.999753475189209, "start": 2346, "tag": "NAME", "value": "Marie" }, { "context": " {:last-name \"Curie\" :first-name \"Marie\" :email \"marie.curie@radium.org\" :favorite-color \"orange\" :dob \"7/7/1867\"}\n ", "end": 2383, "score": 0.9999326467514038, "start": 2361, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "\n {:last-name \"Röntgen\" :first-name \"Wilhelm\" :email \"xray@mail.com\" :fa", "end": 2483, "score": 0.9998424053192139, "start": 2476, "tag": "NAME", "value": "Röntgen" }, { "context": " {:last-name \"Röntgen\" :first-name \"Wilhelm\" :email \"xray@mail.com\" :favorite-color \"white\" :", "end": 2505, "score": 0.9997467994689941, "start": 2498, "tag": "NAME", "value": "Wilhelm" }, { "context": "last-name \"Röntgen\" :first-name \"Wilhelm\" :email \"xray@mail.com\" :favorite-color \"white\" :dob \"3/27/1845\"}\n ", "end": 2528, "score": 0.9999115467071533, "start": 2515, "tag": "EMAIL", "value": "xray@mail.com" }, { "context": "\n {:last-name \"Zeeman\" :first-name \"Pieter\" :email \"zman@doubledutch.nl", "end": 2627, "score": 0.9997748732566833, "start": 2621, "tag": "NAME", "value": "Zeeman" }, { "context": " {:last-name \"Zeeman\" :first-name \"Pieter\" :email \"zman@doubledutch.nl\" :favorite-color \"bl", "end": 2648, "score": 0.9997789263725281, "start": 2642, "tag": "NAME", "value": "Pieter" }, { "context": "{:last-name \"Zeeman\" :first-name \"Pieter\" :email \"zman@doubledutch.nl\" :favorite-color \"blue\" :dob \"5/25/1865\"}])}\n ", "end": 2677, "score": 0.9999232292175293, "start": 2658, "tag": "EMAIL", "value": "zman@doubledutch.nl" }, { "context": "\n :body (json/write-str [{:last-name \"Röntgen\" :first-name \"Wilhelm\" :email \"xray@mail.com\" :fa", "end": 2963, "score": 0.999817967414856, "start": 2956, "tag": "NAME", "value": "Röntgen" }, { "context": "son/write-str [{:last-name \"Röntgen\" :first-name \"Wilhelm\" :email \"xray@mail.com\" :favorite-color \"white\" :", "end": 2985, "score": 0.999803364276886, "start": 2978, "tag": "NAME", "value": "Wilhelm" }, { "context": "last-name \"Röntgen\" :first-name \"Wilhelm\" :email \"xray@mail.com\" :favorite-color \"white\" :dob \"3/27/1845\"}\n ", "end": 3008, "score": 0.9999239444732666, "start": 2995, "tag": "EMAIL", "value": "xray@mail.com" }, { "context": "\n {:last-name \"Lorentz\" :first-name \"Hendrik\" :email \"magneto@transform.", "end": 3108, "score": 0.9998278021812439, "start": 3101, "tag": "NAME", "value": "Lorentz" }, { "context": " {:last-name \"Lorentz\" :first-name \"Hendrik\" :email \"magneto@transform.com\" :favorite-color \"", "end": 3130, "score": 0.999812662601471, "start": 3123, "tag": "NAME", "value": "Hendrik" }, { "context": "last-name \"Lorentz\" :first-name \"Hendrik\" :email \"magneto@transform.com\" :favorite-color \"red\" :dob \"7/18/1853\"}\n ", "end": 3161, "score": 0.9999217987060547, "start": 3140, "tag": "EMAIL", "value": "magneto@transform.com" }, { "context": "\n {:last-name \"Zeeman\" :first-name \"Pieter\" :email \"zman@doubledutch.nl", "end": 3258, "score": 0.9998124837875366, "start": 3252, "tag": "NAME", "value": "Zeeman" }, { "context": " {:last-name \"Zeeman\" :first-name \"Pieter\" :email \"zman@doubledutch.nl\" :favorite-color \"bl", "end": 3279, "score": 0.9998194575309753, "start": 3273, "tag": "NAME", "value": "Pieter" }, { "context": "{:last-name \"Zeeman\" :first-name \"Pieter\" :email \"zman@doubledutch.nl\" :favorite-color \"blue\" :dob \"5/25/1865\"}\n ", "end": 3308, "score": 0.9999279975891113, "start": 3289, "tag": "EMAIL", "value": "zman@doubledutch.nl" }, { "context": "\n {:last-name \"Curie\" :first-name \"Marie\" :email \"marie.curie@radium.o", "end": 3405, "score": 0.9997971653938293, "start": 3400, "tag": "NAME", "value": "Curie" }, { "context": " {:last-name \"Curie\" :first-name \"Marie\" :email \"marie.curie@radium.org\" :favorite-color ", "end": 3425, "score": 0.9998100996017456, "start": 3420, "tag": "NAME", "value": "Marie" }, { "context": " {:last-name \"Curie\" :first-name \"Marie\" :email \"marie.curie@radium.org\" :favorite-color \"orange\" :dob \"7/7/1867\"}])}\n ", "end": 3457, "score": 0.9999262690544128, "start": 3435, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "\n :body (json/write-str [{:last-name \"Curie\" :first-name \"Marie\" :email \"marie.curie@radium.o", "end": 3741, "score": 0.9997776746749878, "start": 3736, "tag": "NAME", "value": "Curie" }, { "context": "(json/write-str [{:last-name \"Curie\" :first-name \"Marie\" :email \"marie.curie@radium.org\" :favorite-color ", "end": 3761, "score": 0.9997972249984741, "start": 3756, "tag": "NAME", "value": "Marie" }, { "context": " [{:last-name \"Curie\" :first-name \"Marie\" :email \"marie.curie@radium.org\" :favorite-color \"orange\" :dob \"7/7/1867\"}\n ", "end": 3793, "score": 0.9999293088912964, "start": 3771, "tag": "EMAIL", "value": "marie.curie@radium.org" }, { "context": "\n {:last-name \"Lorentz\" :first-name \"Hendrik\" :email \"magneto@transform.", "end": 3893, "score": 0.9998188018798828, "start": 3886, "tag": "NAME", "value": "Lorentz" }, { "context": " {:last-name \"Lorentz\" :first-name \"Hendrik\" :email \"magneto@transform.com\" :favorite-color \"", "end": 3915, "score": 0.9998068809509277, "start": 3908, "tag": "NAME", "value": "Hendrik" }, { "context": "last-name \"Lorentz\" :first-name \"Hendrik\" :email \"magneto@transform.com\" :favorite-color \"red\" :dob \"7/18/1853\"}\n ", "end": 3946, "score": 0.9999248385429382, "start": 3925, "tag": "EMAIL", "value": "magneto@transform.com" }, { "context": "\n {:last-name \"Röntgen\" :first-name \"Wilhelm\" :email \"xray@mail.com\" :fa", "end": 4044, "score": 0.9998267292976379, "start": 4037, "tag": "NAME", "value": "Röntgen" }, { "context": " {:last-name \"Röntgen\" :first-name \"Wilhelm\" :email \"xray@mail.com\" :favorite-color \"white\" :", "end": 4066, "score": 0.9998214840888977, "start": 4059, "tag": "NAME", "value": "Wilhelm" }, { "context": "last-name \"Röntgen\" :first-name \"Wilhelm\" :email \"xray@mail.com\" :favorite-color \"white\" :dob \"3/27/1845\"}\n ", "end": 4089, "score": 0.9999232292175293, "start": 4076, "tag": "EMAIL", "value": "xray@mail.com" }, { "context": "\n {:last-name \"Zeeman\" :first-name \"Pieter\" :email \"zman@doubledutch.nl", "end": 4188, "score": 0.9997931718826294, "start": 4182, "tag": "NAME", "value": "Zeeman" }, { "context": " {:last-name \"Zeeman\" :first-name \"Pieter\" :email \"zman@doubledutch.nl\" :favorite-color \"bl", "end": 4209, "score": 0.9998020529747009, "start": 4203, "tag": "NAME", "value": "Pieter" }, { "context": "{:last-name \"Zeeman\" :first-name \"Pieter\" :email \"zman@doubledutch.nl\" :favorite-color \"blue\" :dob \"5/25/1865\"}])}\n ", "end": 4238, "score": 0.9999285340309143, "start": 4219, "tag": "EMAIL", "value": "zman@doubledutch.nl" } ]
test/webmain_test.clj
coyotesqrl/rec-sorter
0
(ns webmain-test (:require [clojure.test :refer [are deftest is use-fixtures]] [webmain :as web] [clojure.data.json :as json] [ring.mock.request :as mock])) (defn prep-data [f] (reset! webmain/data '()) (f)) (use-fixtures :each prep-data) (deftest empty-sorts (are [end-point] (= {:status 200 :headers {"Content-Type" "application/json"} :body "[]"} (web/myapp (mock/request :get end-point))) "/records/email" "/records/birthdate" "/records/name")) (deftest post-comma-delim (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str '("Curie, Marie, marie.curie@radium.org, orange, 7/7/1867"))} (web/myapp (mock/body (mock/request :post "/records") "Curie, Marie, marie.curie@radium.org, orange, 7/7/1867"))))) (deftest post-pipe-delim (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str '("Curie | Marie | marie.curie@radium.org | orange | 7/7/1867"))} (web/myapp (mock/body (mock/request :post "/records") "Curie | Marie | marie.curie@radium.org | orange | 7/7/1867"))))) (deftest post-ws-delim (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str '("Curie Marie marie.curie@radium.org orange 7/7/1867"))} (web/myapp (mock/body (mock/request :post "/records") "Curie Marie marie.curie@radium.org orange 7/7/1867"))))) (defn load-data [] (web/myapp (mock/body (mock/request :post "/records") "Röntgen|Wilhelm|xray@mail.com|white|3/27/1845")) (web/myapp (mock/body (mock/request :post "/records") "Lorentz | Hendrik | magneto@transform.com | red | 7/18/1853")) (web/myapp (mock/body (mock/request :post "/records") "Zeeman | Pieter | zman@doubledutch.nl | blue | 5/25/1865")) (web/myapp (mock/body (mock/request :post "/records") "Curie|Marie|marie.curie@radium.org|orange|7/7/1867"))) (deftest get-email-sorted (load-data) (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str [{:last-name "Lorentz" :first-name "Hendrik" :email "magneto@transform.com" :favorite-color "red" :dob "7/18/1853"} {:last-name "Curie" :first-name "Marie" :email "marie.curie@radium.org" :favorite-color "orange" :dob "7/7/1867"} {:last-name "Röntgen" :first-name "Wilhelm" :email "xray@mail.com" :favorite-color "white" :dob "3/27/1845"} {:last-name "Zeeman" :first-name "Pieter" :email "zman@doubledutch.nl" :favorite-color "blue" :dob "5/25/1865"}])} (web/myapp (mock/request :get "/records/email"))))) (deftest get-birthdate-sorted (load-data) (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str [{:last-name "Röntgen" :first-name "Wilhelm" :email "xray@mail.com" :favorite-color "white" :dob "3/27/1845"} {:last-name "Lorentz" :first-name "Hendrik" :email "magneto@transform.com" :favorite-color "red" :dob "7/18/1853"} {:last-name "Zeeman" :first-name "Pieter" :email "zman@doubledutch.nl" :favorite-color "blue" :dob "5/25/1865"} {:last-name "Curie" :first-name "Marie" :email "marie.curie@radium.org" :favorite-color "orange" :dob "7/7/1867"}])} (web/myapp (mock/request :get "/records/birthdate"))))) (deftest get-name-sorted (load-data) (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str [{:last-name "Curie" :first-name "Marie" :email "marie.curie@radium.org" :favorite-color "orange" :dob "7/7/1867"} {:last-name "Lorentz" :first-name "Hendrik" :email "magneto@transform.com" :favorite-color "red" :dob "7/18/1853"} {:last-name "Röntgen" :first-name "Wilhelm" :email "xray@mail.com" :favorite-color "white" :dob "3/27/1845"} {:last-name "Zeeman" :first-name "Pieter" :email "zman@doubledutch.nl" :favorite-color "blue" :dob "5/25/1865"}])} (web/myapp (mock/request :get "/records/name")))))
106069
(ns webmain-test (:require [clojure.test :refer [are deftest is use-fixtures]] [webmain :as web] [clojure.data.json :as json] [ring.mock.request :as mock])) (defn prep-data [f] (reset! webmain/data '()) (f)) (use-fixtures :each prep-data) (deftest empty-sorts (are [end-point] (= {:status 200 :headers {"Content-Type" "application/json"} :body "[]"} (web/myapp (mock/request :get end-point))) "/records/email" "/records/birthdate" "/records/name")) (deftest post-comma-delim (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str '("<NAME>, <EMAIL>, orange, 7/7/1867"))} (web/myapp (mock/body (mock/request :post "/records") "<NAME>, <EMAIL>, orange, 7/7/1867"))))) (deftest post-pipe-delim (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str '("<NAME> | <NAME> | <EMAIL> | orange | 7/7/1867"))} (web/myapp (mock/body (mock/request :post "/records") "<NAME> | <NAME> | <EMAIL> | orange | 7/7/1867"))))) (deftest post-ws-delim (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str '("<NAME> <EMAIL> orange 7/7/1867"))} (web/myapp (mock/body (mock/request :post "/records") "<NAME> <EMAIL> orange 7/7/1867"))))) (defn load-data [] (web/myapp (mock/body (mock/request :post "/records") "<NAME>|<NAME>|<EMAIL>|white|3/27/1845")) (web/myapp (mock/body (mock/request :post "/records") "<NAME> | <NAME> | <EMAIL> | red | 7/18/1853")) (web/myapp (mock/body (mock/request :post "/records") "<NAME> | <NAME> | <EMAIL> | blue | 5/25/1865")) (web/myapp (mock/body (mock/request :post "/records") "<NAME>|<NAME>|<EMAIL>|orange|7/7/1867"))) (deftest get-email-sorted (load-data) (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str [{:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "red" :dob "7/18/1853"} {:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "orange" :dob "7/7/1867"} {:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "white" :dob "3/27/1845"} {:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "blue" :dob "5/25/1865"}])} (web/myapp (mock/request :get "/records/email"))))) (deftest get-birthdate-sorted (load-data) (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str [{:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "white" :dob "3/27/1845"} {:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "red" :dob "7/18/1853"} {:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "blue" :dob "5/25/1865"} {:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "orange" :dob "7/7/1867"}])} (web/myapp (mock/request :get "/records/birthdate"))))) (deftest get-name-sorted (load-data) (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str [{:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "orange" :dob "7/7/1867"} {:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "red" :dob "7/18/1853"} {:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "white" :dob "3/27/1845"} {:last-name "<NAME>" :first-name "<NAME>" :email "<EMAIL>" :favorite-color "blue" :dob "5/25/1865"}])} (web/myapp (mock/request :get "/records/name")))))
true
(ns webmain-test (:require [clojure.test :refer [are deftest is use-fixtures]] [webmain :as web] [clojure.data.json :as json] [ring.mock.request :as mock])) (defn prep-data [f] (reset! webmain/data '()) (f)) (use-fixtures :each prep-data) (deftest empty-sorts (are [end-point] (= {:status 200 :headers {"Content-Type" "application/json"} :body "[]"} (web/myapp (mock/request :get end-point))) "/records/email" "/records/birthdate" "/records/name")) (deftest post-comma-delim (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str '("PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI, orange, 7/7/1867"))} (web/myapp (mock/body (mock/request :post "/records") "PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI, orange, 7/7/1867"))))) (deftest post-pipe-delim (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str '("PI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | PI:EMAIL:<EMAIL>END_PI | orange | 7/7/1867"))} (web/myapp (mock/body (mock/request :post "/records") "PI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | PI:EMAIL:<EMAIL>END_PI | orange | 7/7/1867"))))) (deftest post-ws-delim (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str '("PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI orange 7/7/1867"))} (web/myapp (mock/body (mock/request :post "/records") "PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI orange 7/7/1867"))))) (defn load-data [] (web/myapp (mock/body (mock/request :post "/records") "PI:NAME:<NAME>END_PI|PI:NAME:<NAME>END_PI|PI:EMAIL:<EMAIL>END_PI|white|3/27/1845")) (web/myapp (mock/body (mock/request :post "/records") "PI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | PI:EMAIL:<EMAIL>END_PI | red | 7/18/1853")) (web/myapp (mock/body (mock/request :post "/records") "PI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | PI:EMAIL:<EMAIL>END_PI | blue | 5/25/1865")) (web/myapp (mock/body (mock/request :post "/records") "PI:NAME:<NAME>END_PI|PI:NAME:<NAME>END_PI|PI:EMAIL:<EMAIL>END_PI|orange|7/7/1867"))) (deftest get-email-sorted (load-data) (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str [{:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "red" :dob "7/18/1853"} {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "orange" :dob "7/7/1867"} {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "white" :dob "3/27/1845"} {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "blue" :dob "5/25/1865"}])} (web/myapp (mock/request :get "/records/email"))))) (deftest get-birthdate-sorted (load-data) (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str [{:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "white" :dob "3/27/1845"} {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "red" :dob "7/18/1853"} {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "blue" :dob "5/25/1865"} {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "orange" :dob "7/7/1867"}])} (web/myapp (mock/request :get "/records/birthdate"))))) (deftest get-name-sorted (load-data) (is (= {:status 200 :headers {"Content-Type" "application/json"} :body (json/write-str [{:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "orange" :dob "7/7/1867"} {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "red" :dob "7/18/1853"} {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "white" :dob "3/27/1845"} {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :favorite-color "blue" :dob "5/25/1865"}])} (web/myapp (mock/request :get "/records/name")))))
[ { "context": ";; Copyright © 2015-2021 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998833537101746, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
src/territory_bro/gis/gis_sync.clj
3breadt/territory-bro
2
;; Copyright © 2015-2021 Esko Luontola ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.gis.gis-sync (:require [clojure.java.jdbc :as jdbc] [clojure.tools.logging :as log] [mount.core :as mount] [territory-bro.dispatcher :as dispatcher] [territory-bro.gis.gis-change :as gis-change] [territory-bro.gis.gis-db :as gis-db] [territory-bro.infra.db :as db] [territory-bro.infra.executors :as executors] [territory-bro.infra.poller :as poller] [territory-bro.projections :as projections]) (:import (com.google.common.util.concurrent ThreadFactoryBuilder) (java.time Duration) (java.util.concurrent Executors ExecutorService TimeUnit) (org.postgresql PGConnection) (org.postgresql.util PSQLException))) (defn- process-changes! [conn state had-changes?] (if-some [change (gis-db/next-unprocessed-change conn)] (let [changes (gis-change/normalize-change change) state (reduce (fn [state change] (let [command (gis-change/change->command change state) events (dispatcher/command! conn state command)] ;; the state needs to be updated for e.g. command validation's foreign key checks (reduce projections/projection state events))) state changes)] (gis-db/mark-changes-processed! conn [(:gis-change/id change)]) (recur conn state true)) had-changes?)) (defn refresh! [] (log/info "Refreshing GIS changes") (when (db/with-db [conn {}] (process-changes! conn (projections/cached-state) false)) (projections/refresh-async!))) (mount/defstate refresher :start (poller/create refresh!) :stop (poller/shutdown! refresher)) (defn refresh-async! [] (poller/trigger! refresher)) (defn await-refreshed [^Duration duration] (poller/await refresher duration)) (defonce ^:private scheduled-refresh-thread-factory (-> (ThreadFactoryBuilder.) (.setNameFormat "territory-bro.gis.gis-sync/scheduled-refresh-%d") (.setDaemon true) (.setUncaughtExceptionHandler executors/uncaught-exception-handler) (.build))) (mount/defstate scheduled-refresh :start (doto (Executors/newScheduledThreadPool 1 scheduled-refresh-thread-factory) (.scheduleWithFixedDelay (executors/safe-task refresh-async!) 0 1 TimeUnit/MINUTES)) :stop (.shutdown ^ExecutorService scheduled-refresh)) (defn listen-for-gis-changes [notify] (jdbc/with-db-connection [conn db/database {}] (db/use-master-schema conn) (jdbc/execute! conn ["LISTEN gis_change"]) (let [timeout (Duration/ofSeconds 30) ^PGConnection pg-conn (-> (jdbc/db-connection conn) (.unwrap PGConnection))] (log/info "Started listening for GIS changes") (notify) (loop [] ;; getNotifications is not interruptible, so it will take up to `timeout` for this loop to exit (let [notifications (try (.getNotifications pg-conn (.toMillis timeout)) (catch PSQLException e ;; hide failures during shutdown; the database connection was closed while waiting for notifications (if (.isInterrupted (Thread/currentThread)) (log/info "Ignoring errors during shutdown:" (str e)) (throw e))))] (when-not (.isInterrupted (Thread/currentThread)) (doseq [_ notifications] (notify)) (recur)))) (log/info "Stopped listening for GIS changes")))) (defn- until-interrupted [task] (fn [] (while (not (.isInterrupted (Thread/currentThread))) (task)))) (defonce ^:private notified-refresh-thread-factory (-> (ThreadFactoryBuilder.) (.setNameFormat "territory-bro.gis.gis-sync/notified-refresh-%d") (.setDaemon true) (.setUncaughtExceptionHandler executors/uncaught-exception-handler) (.build))) (mount/defstate notified-refresh :start (doto (Executors/newFixedThreadPool 1 notified-refresh-thread-factory) (.submit ^Callable (until-interrupted (executors/safe-task #(listen-for-gis-changes refresh-async!))))) ;; XXX: not awaiting termination, because PGConnection.getNotifications() is not interruptible :stop (.shutdownNow ^ExecutorService notified-refresh))
55397
;; Copyright © 2015-2021 <NAME> ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.gis.gis-sync (:require [clojure.java.jdbc :as jdbc] [clojure.tools.logging :as log] [mount.core :as mount] [territory-bro.dispatcher :as dispatcher] [territory-bro.gis.gis-change :as gis-change] [territory-bro.gis.gis-db :as gis-db] [territory-bro.infra.db :as db] [territory-bro.infra.executors :as executors] [territory-bro.infra.poller :as poller] [territory-bro.projections :as projections]) (:import (com.google.common.util.concurrent ThreadFactoryBuilder) (java.time Duration) (java.util.concurrent Executors ExecutorService TimeUnit) (org.postgresql PGConnection) (org.postgresql.util PSQLException))) (defn- process-changes! [conn state had-changes?] (if-some [change (gis-db/next-unprocessed-change conn)] (let [changes (gis-change/normalize-change change) state (reduce (fn [state change] (let [command (gis-change/change->command change state) events (dispatcher/command! conn state command)] ;; the state needs to be updated for e.g. command validation's foreign key checks (reduce projections/projection state events))) state changes)] (gis-db/mark-changes-processed! conn [(:gis-change/id change)]) (recur conn state true)) had-changes?)) (defn refresh! [] (log/info "Refreshing GIS changes") (when (db/with-db [conn {}] (process-changes! conn (projections/cached-state) false)) (projections/refresh-async!))) (mount/defstate refresher :start (poller/create refresh!) :stop (poller/shutdown! refresher)) (defn refresh-async! [] (poller/trigger! refresher)) (defn await-refreshed [^Duration duration] (poller/await refresher duration)) (defonce ^:private scheduled-refresh-thread-factory (-> (ThreadFactoryBuilder.) (.setNameFormat "territory-bro.gis.gis-sync/scheduled-refresh-%d") (.setDaemon true) (.setUncaughtExceptionHandler executors/uncaught-exception-handler) (.build))) (mount/defstate scheduled-refresh :start (doto (Executors/newScheduledThreadPool 1 scheduled-refresh-thread-factory) (.scheduleWithFixedDelay (executors/safe-task refresh-async!) 0 1 TimeUnit/MINUTES)) :stop (.shutdown ^ExecutorService scheduled-refresh)) (defn listen-for-gis-changes [notify] (jdbc/with-db-connection [conn db/database {}] (db/use-master-schema conn) (jdbc/execute! conn ["LISTEN gis_change"]) (let [timeout (Duration/ofSeconds 30) ^PGConnection pg-conn (-> (jdbc/db-connection conn) (.unwrap PGConnection))] (log/info "Started listening for GIS changes") (notify) (loop [] ;; getNotifications is not interruptible, so it will take up to `timeout` for this loop to exit (let [notifications (try (.getNotifications pg-conn (.toMillis timeout)) (catch PSQLException e ;; hide failures during shutdown; the database connection was closed while waiting for notifications (if (.isInterrupted (Thread/currentThread)) (log/info "Ignoring errors during shutdown:" (str e)) (throw e))))] (when-not (.isInterrupted (Thread/currentThread)) (doseq [_ notifications] (notify)) (recur)))) (log/info "Stopped listening for GIS changes")))) (defn- until-interrupted [task] (fn [] (while (not (.isInterrupted (Thread/currentThread))) (task)))) (defonce ^:private notified-refresh-thread-factory (-> (ThreadFactoryBuilder.) (.setNameFormat "territory-bro.gis.gis-sync/notified-refresh-%d") (.setDaemon true) (.setUncaughtExceptionHandler executors/uncaught-exception-handler) (.build))) (mount/defstate notified-refresh :start (doto (Executors/newFixedThreadPool 1 notified-refresh-thread-factory) (.submit ^Callable (until-interrupted (executors/safe-task #(listen-for-gis-changes refresh-async!))))) ;; XXX: not awaiting termination, because PGConnection.getNotifications() is not interruptible :stop (.shutdownNow ^ExecutorService notified-refresh))
true
;; Copyright © 2015-2021 PI:NAME:<NAME>END_PI ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.gis.gis-sync (:require [clojure.java.jdbc :as jdbc] [clojure.tools.logging :as log] [mount.core :as mount] [territory-bro.dispatcher :as dispatcher] [territory-bro.gis.gis-change :as gis-change] [territory-bro.gis.gis-db :as gis-db] [territory-bro.infra.db :as db] [territory-bro.infra.executors :as executors] [territory-bro.infra.poller :as poller] [territory-bro.projections :as projections]) (:import (com.google.common.util.concurrent ThreadFactoryBuilder) (java.time Duration) (java.util.concurrent Executors ExecutorService TimeUnit) (org.postgresql PGConnection) (org.postgresql.util PSQLException))) (defn- process-changes! [conn state had-changes?] (if-some [change (gis-db/next-unprocessed-change conn)] (let [changes (gis-change/normalize-change change) state (reduce (fn [state change] (let [command (gis-change/change->command change state) events (dispatcher/command! conn state command)] ;; the state needs to be updated for e.g. command validation's foreign key checks (reduce projections/projection state events))) state changes)] (gis-db/mark-changes-processed! conn [(:gis-change/id change)]) (recur conn state true)) had-changes?)) (defn refresh! [] (log/info "Refreshing GIS changes") (when (db/with-db [conn {}] (process-changes! conn (projections/cached-state) false)) (projections/refresh-async!))) (mount/defstate refresher :start (poller/create refresh!) :stop (poller/shutdown! refresher)) (defn refresh-async! [] (poller/trigger! refresher)) (defn await-refreshed [^Duration duration] (poller/await refresher duration)) (defonce ^:private scheduled-refresh-thread-factory (-> (ThreadFactoryBuilder.) (.setNameFormat "territory-bro.gis.gis-sync/scheduled-refresh-%d") (.setDaemon true) (.setUncaughtExceptionHandler executors/uncaught-exception-handler) (.build))) (mount/defstate scheduled-refresh :start (doto (Executors/newScheduledThreadPool 1 scheduled-refresh-thread-factory) (.scheduleWithFixedDelay (executors/safe-task refresh-async!) 0 1 TimeUnit/MINUTES)) :stop (.shutdown ^ExecutorService scheduled-refresh)) (defn listen-for-gis-changes [notify] (jdbc/with-db-connection [conn db/database {}] (db/use-master-schema conn) (jdbc/execute! conn ["LISTEN gis_change"]) (let [timeout (Duration/ofSeconds 30) ^PGConnection pg-conn (-> (jdbc/db-connection conn) (.unwrap PGConnection))] (log/info "Started listening for GIS changes") (notify) (loop [] ;; getNotifications is not interruptible, so it will take up to `timeout` for this loop to exit (let [notifications (try (.getNotifications pg-conn (.toMillis timeout)) (catch PSQLException e ;; hide failures during shutdown; the database connection was closed while waiting for notifications (if (.isInterrupted (Thread/currentThread)) (log/info "Ignoring errors during shutdown:" (str e)) (throw e))))] (when-not (.isInterrupted (Thread/currentThread)) (doseq [_ notifications] (notify)) (recur)))) (log/info "Stopped listening for GIS changes")))) (defn- until-interrupted [task] (fn [] (while (not (.isInterrupted (Thread/currentThread))) (task)))) (defonce ^:private notified-refresh-thread-factory (-> (ThreadFactoryBuilder.) (.setNameFormat "territory-bro.gis.gis-sync/notified-refresh-%d") (.setDaemon true) (.setUncaughtExceptionHandler executors/uncaught-exception-handler) (.build))) (mount/defstate notified-refresh :start (doto (Executors/newFixedThreadPool 1 notified-refresh-thread-factory) (.submit ^Callable (until-interrupted (executors/safe-task #(listen-for-gis-changes refresh-async!))))) ;; XXX: not awaiting termination, because PGConnection.getNotifications() is not interruptible :stop (.shutdownNow ^ExecutorService notified-refresh))
[ { "context": " common-names\n {:female #{\"anjali\" \"divya\" \"ishita\" \"priya\" \"priyanka\"\n \"riya\" \"", "end": 425, "score": 0.5465091466903687, "start": 422, "tag": "NAME", "value": "ish" }, { "context": "reya\" \"tanvi\" \"tanya\" \"vani\"},\n :male #{\"abhishek\" \"adityaamit\" \"ankit\" \"deepak\" \"mahesh\"\n ", "end": 535, "score": 0.9737070202827454, "start": 527, "tag": "NAME", "value": "abhishek" }, { "context": "i\" \"tanya\" \"vani\"},\n :male #{\"abhishek\" \"adityaamit\" \"ankit\" \"deepak\" \"mahesh\"\n \"rah", "end": 548, "score": 0.9890211224555969, "start": 538, "tag": "NAME", "value": "adityaamit" }, { "context": "ani\"},\n :male #{\"abhishek\" \"adityaamit\" \"ankit\" \"deepak\" \"mahesh\"\n \"rahul\" \"roh", "end": 556, "score": 0.9795240163803101, "start": 551, "tag": "NAME", "value": "ankit" }, { "context": " :male #{\"abhishek\" \"adityaamit\" \"ankit\" \"deepak\" \"mahesh\"\n \"rahul\" \"rohit\" \"shya", "end": 565, "score": 0.9568194150924683, "start": 559, "tag": "NAME", "value": "deepak" }, { "context": " #{\"abhishek\" \"adityaamit\" \"ankit\" \"deepak\" \"mahesh\"\n \"rahul\" \"rohit\" \"shyam\" \"yash\"", "end": 574, "score": 0.8048678040504456, "start": 568, "tag": "NAME", "value": "mahesh" }, { "context": "mit\" \"ankit\" \"deepak\" \"mahesh\"\n \"rahul\" \"rohit\" \"shyam\" \"yash\"},\n :transgender #{\"bhar", "end": 600, "score": 0.9053230285644531, "start": 595, "tag": "NAME", "value": "rahul" }, { "context": "kit\" \"deepak\" \"mahesh\"\n \"rahul\" \"rohit\" \"shyam\" \"yash\"},\n :transgender #{\"bharathi\" \"m", "end": 608, "score": 0.787898063659668, "start": 603, "tag": "NAME", "value": "rohit" }, { "context": "ak\" \"mahesh\"\n \"rahul\" \"rohit\" \"shyam\" \"yash\"},\n :transgender #{\"bharathi\" \"madhu\" \"m", "end": 616, "score": 0.8888200521469116, "start": 613, "tag": "NAME", "value": "yam" }, { "context": "hesh\"\n \"rahul\" \"rohit\" \"shyam\" \"yash\"},\n :transgender #{\"bharathi\" \"madhu\" \"manabi\" ", "end": 623, "score": 0.8292376399040222, "start": 620, "tag": "NAME", "value": "ash" }, { "context": "riya\" \"shreya\" \"kiran\" \"amit\"}\n :last-name #{\"Lamba\" \"Bahl\" \"Sodhi\" \"Sardana\" \"Puri\" \"Chhabra\"\n ", "end": 762, "score": 0.9996693134307861, "start": 757, "tag": "NAME", "value": "Lamba" }, { "context": "hreya\" \"kiran\" \"amit\"}\n :last-name #{\"Lamba\" \"Bahl\" \"Sodhi\" \"Sardana\" \"Puri\" \"Chhabra\"\n ", "end": 769, "score": 0.9991800785064697, "start": 765, "tag": "NAME", "value": "Bahl" }, { "context": "\"kiran\" \"amit\"}\n :last-name #{\"Lamba\" \"Bahl\" \"Sodhi\" \"Sardana\" \"Puri\" \"Chhabra\"\n \"Ma", "end": 777, "score": 0.9993473887443542, "start": 772, "tag": "NAME", "value": "Sodhi" }, { "context": "\"amit\"}\n :last-name #{\"Lamba\" \"Bahl\" \"Sodhi\" \"Sardana\" \"Puri\" \"Chhabra\"\n \"Malhotra\" \"G", "end": 787, "score": 0.9987151026725769, "start": 780, "tag": "NAME", "value": "Sardana" }, { "context": " :last-name #{\"Lamba\" \"Bahl\" \"Sodhi\" \"Sardana\" \"Puri\" \"Chhabra\"\n \"Malhotra\" \"Garewal\"", "end": 794, "score": 0.9992960691452026, "start": 790, "tag": "NAME", "value": "Puri" }, { "context": "name #{\"Lamba\" \"Bahl\" \"Sodhi\" \"Sardana\" \"Puri\" \"Chhabra\"\n \"Malhotra\" \"Garewal\" \"Dhillon\"", "end": 804, "score": 0.9981226921081543, "start": 797, "tag": "NAME", "value": "Chhabra" }, { "context": "hi\" \"Sardana\" \"Puri\" \"Chhabra\"\n \"Malhotra\" \"Garewal\" \"Dhillon\"}})\n\n(def common-addresses\n ", "end": 833, "score": 0.9989960193634033, "start": 825, "tag": "NAME", "value": "Malhotra" }, { "context": "a\" \"Puri\" \"Chhabra\"\n \"Malhotra\" \"Garewal\" \"Dhillon\"}})\n\n(def common-addresses\n {:street-n", "end": 843, "score": 0.9985032081604004, "start": 836, "tag": "NAME", "value": "Garewal" }, { "context": "\"Chhabra\"\n \"Malhotra\" \"Garewal\" \"Dhillon\"}})\n\n(def common-addresses\n {:street-name\n [\"B", "end": 853, "score": 0.9953636527061462, "start": 846, "tag": "NAME", "value": "Dhillon" }, { "context": " (and string? not-empty)\n #(gen/elements #{\"randomzole\" \"lisinopril\" \"losartan\"\n \"fu", "end": 4101, "score": 0.9551591873168945, "start": 4091, "tag": "NAME", "value": "randomzole" }, { "context": "ng? not-empty)\n #(gen/elements #{\"randomzole\" \"lisinopril\" \"losartan\"\n \"furosemide\" \"cu", "end": 4114, "score": 0.9922171831130981, "start": 4104, "tag": "NAME", "value": "lisinopril" }, { "context": ")\n #(gen/elements #{\"randomzole\" \"lisinopril\" \"losartan\"\n \"furosemide\" \"customoril\" \"", "end": 4125, "score": 0.9945063591003418, "start": 4117, "tag": "NAME", "value": "losartan" }, { "context": "le\" \"lisinopril\" \"losartan\"\n \"furosemide\" \"customoril\" \"cherries\"})))\n\n(s/def ::drug-dosag", "end": 4159, "score": 0.8411134481430054, "start": 4149, "tag": "NAME", "value": "furosemide" }, { "context": "\"\n \"furosemide\" \"customoril\" \"cherries\"})))\n\n(s/def ::drug-dosage\n (s/with-gen\n (and", "end": 4183, "score": 0.9777947664260864, "start": 4175, "tag": "NAME", "value": "cherries" } ]
src/simple_experiments/db/patient.cljs
simpledotorg/simple-experiments
7
(ns simple-experiments.db.patient (:require [clojure.spec.alpha :as s] [clojure.string :as string] [clojure.test.check] [cljs-time.core :as time] [cljs-time.coerce :as timec] [cljs-time.format :as timef] [clojure.test.check.generators :as tcgen] [clojure.spec.gen.alpha :as gen])) (def common-names {:female #{"anjali" "divya" "ishita" "priya" "priyanka" "riya" "shreya" "tanvi" "tanya" "vani"}, :male #{"abhishek" "adityaamit" "ankit" "deepak" "mahesh" "rahul" "rohit" "shyam" "yash"}, :transgender #{"bharathi" "madhu" "manabi" "anjum" "vani" "riya" "shreya" "kiran" "amit"} :last-name #{"Lamba" "Bahl" "Sodhi" "Sardana" "Puri" "Chhabra" "Malhotra" "Garewal" "Dhillon"}}) (def common-addresses {:street-name ["Bhagat singh colony" "Gandhi Basti" "NFL Colony" "Farid Nagari" "Bathinda Road" "Bus Stand Rd" "Hirke Road" "Makhewala Jhanduke Road"] :village-or-colony ["Bathinda" "Bhagwangarh" "Dannewala" "Nandgarh" "Nathana" "Bhikhi" "Budhlada" "Hirke" "Jhanduke" "Mansa" "Bareta" "Bhaini" "Bagha" "Sadulgarh" "Sardulewala"]}) (def protocol-drugs [[:amlodipine [{:id :am-5 :drug-dosage "5mg"} {:id :am-10 :drug-dosage "10mg"}]] [:telmisartan [{:id :tel-40 :drug-dosage "40mg"} {:id :tel-80 :drug-dosage "80mg"}]] [:chlorthalidone [{:id :chlo-12-5 :drug-dosage "12.5mg"} {:id :chlo-25 :drug-dosage "25mg"}]]]) (def protocol-drugs-by-id (->> (for [[drug-name drugs] protocol-drugs {:keys [id drug-dosage]} drugs] {id {:drug-name drug-name :drug-dosage drug-dosage}}) (into {}))) (def protocol-drug-ids (set (keys protocol-drugs-by-id))) (s/def ::non-empty-string (s/and string? not-empty)) (s/def ::id (s/with-gen (s/and string? #(= 36 (count %))) #(gen/fmap (fn [x] (str x)) (gen/uuid)))) (s/def ::gender #{"male" "female" "transgender"}) (s/def ::full-name (s/with-gen (s/and string? not-empty) #(gen/fmap (fn [x] (string/join " " (take 2 x))) (tcgen/shuffle (apply concat (vals common-names)))))) (s/def ::status #{"active" "dead" "migrated" "unresponsive" "inactive"}) (s/def ::timestamp (s/with-gen int? #(gen/choose (timec/to-long (time/date-time 1920 0 0)) (timec/to-long (time/now))))) (s/def ::recent-timestamp (s/with-gen int? #(gen/choose (timec/to-long (time/minus (time/now) (time/days 50))) (timec/to-long (time/now))))) (s/def ::age (s/with-gen (s/and int? #(< 0 % 100)) #(gen/choose 18 90))) (s/def ::age-string (s/and string? #(<= 0 (js/parseInt %) 100))) (s/def ::date-of-birth-string (s/and string? #(= (count %) 10) #(try (let [t (timef/parse (timef/formatter "dd/MM/YYYY") %)] (and (time/before? t (time/now)) (time/after? t (time/date-time 1900)))) (catch :default e false)))) (s/def ::optional-dob-string (s/nilable ::date-of-birth-string)) (s/def ::date-of-birth ::timestamp) (s/def ::age-updated-at ::recent-timestamp) (s/def ::created-at ::recent-timestamp) (s/def ::updated-at ::recent-timestamp) (s/def ::deleted-at ::recent-timestamp) (s/def ::phone-number (s/with-gen (s/and string? not-empty #(re-find #"^\d*$" %)) #(gen/fmap str (gen/choose 6000000000 9999999999)))) (s/def ::village-or-colony (s/with-gen (s/and string? not-empty) #(gen/elements (:village-or-colony common-addresses)))) (s/def ::systolic (s/with-gen int? #(gen/choose 50 300))) (s/def ::diastolic (s/with-gen int? #(gen/choose 50 100))) (s/def ::blood-pressure (s/keys :req-un [::systolic ::diastolic ::created-at ::updated-at])) (s/def ::blood-pressures (s/with-gen (s/coll-of ::blood-pressure) #(gen/vector (s/gen ::blood-pressure) 0 5))) (s/def ::drug-name (s/with-gen (and string? not-empty) #(gen/elements #{"randomzole" "lisinopril" "losartan" "furosemide" "customoril" "cherries"}))) (s/def ::drug-dosage (s/with-gen (and string? not-empty) #(gen/elements #{"10mg" "5mg" "1 packet" "10 times" "12.5g" "20mg"}))) (s/def ::custom-drug (s/keys :req-un [::id ::drug-name ::drug-dosage ::created-at ::updated-at])) (s/def ::custom-drugs (s/with-gen (s/map-of ::id ::custom-drug) #(gen/fmap (fn [ds] (zipmap (map :id ds) ds)) (gen/vector (s/gen ::custom-drug) 0 2)))) (s/def ::drug-ids (s/with-gen set? #(gen/set (gen/elements protocol-drug-ids) {:min-elements 0 :max-elements 3}))) (s/def ::protocol-drugs (s/keys :req-un [::updated-at ::drug-ids])) (s/def ::prescription-drugs (s/keys :req-un [::protocol-drugs ::custom-drugs])) (def patient-fields #{:id :full-name :age :phone-number :gender :date-of-birth :village-or-colony :district :state}) (s/def ::patient (s/keys :req-un [::id ::gender ::full-name ::status ::date-of-birth ::age ::age-updated-at ::created-at ::updated-at ::phone-number ::village-or-colony ::blood-pressures ::prescription-drugs])) (defn generate-patients [num-patients] (let [patients (gen/sample (s/gen ::patient) num-patients)] (zipmap (map :id patients) patients))) (comment ;;gen patients (dotimes [_ 10] (re-frame.core/dispatch [:add-patient (gen/generate (s/gen ::patient))])) )
5283
(ns simple-experiments.db.patient (:require [clojure.spec.alpha :as s] [clojure.string :as string] [clojure.test.check] [cljs-time.core :as time] [cljs-time.coerce :as timec] [cljs-time.format :as timef] [clojure.test.check.generators :as tcgen] [clojure.spec.gen.alpha :as gen])) (def common-names {:female #{"anjali" "divya" "<NAME>ita" "priya" "priyanka" "riya" "shreya" "tanvi" "tanya" "vani"}, :male #{"<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "sh<NAME>" "y<NAME>"}, :transgender #{"bharathi" "madhu" "manabi" "anjum" "vani" "riya" "shreya" "kiran" "amit"} :last-name #{"<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"}}) (def common-addresses {:street-name ["Bhagat singh colony" "Gandhi Basti" "NFL Colony" "Farid Nagari" "Bathinda Road" "Bus Stand Rd" "Hirke Road" "Makhewala Jhanduke Road"] :village-or-colony ["Bathinda" "Bhagwangarh" "Dannewala" "Nandgarh" "Nathana" "Bhikhi" "Budhlada" "Hirke" "Jhanduke" "Mansa" "Bareta" "Bhaini" "Bagha" "Sadulgarh" "Sardulewala"]}) (def protocol-drugs [[:amlodipine [{:id :am-5 :drug-dosage "5mg"} {:id :am-10 :drug-dosage "10mg"}]] [:telmisartan [{:id :tel-40 :drug-dosage "40mg"} {:id :tel-80 :drug-dosage "80mg"}]] [:chlorthalidone [{:id :chlo-12-5 :drug-dosage "12.5mg"} {:id :chlo-25 :drug-dosage "25mg"}]]]) (def protocol-drugs-by-id (->> (for [[drug-name drugs] protocol-drugs {:keys [id drug-dosage]} drugs] {id {:drug-name drug-name :drug-dosage drug-dosage}}) (into {}))) (def protocol-drug-ids (set (keys protocol-drugs-by-id))) (s/def ::non-empty-string (s/and string? not-empty)) (s/def ::id (s/with-gen (s/and string? #(= 36 (count %))) #(gen/fmap (fn [x] (str x)) (gen/uuid)))) (s/def ::gender #{"male" "female" "transgender"}) (s/def ::full-name (s/with-gen (s/and string? not-empty) #(gen/fmap (fn [x] (string/join " " (take 2 x))) (tcgen/shuffle (apply concat (vals common-names)))))) (s/def ::status #{"active" "dead" "migrated" "unresponsive" "inactive"}) (s/def ::timestamp (s/with-gen int? #(gen/choose (timec/to-long (time/date-time 1920 0 0)) (timec/to-long (time/now))))) (s/def ::recent-timestamp (s/with-gen int? #(gen/choose (timec/to-long (time/minus (time/now) (time/days 50))) (timec/to-long (time/now))))) (s/def ::age (s/with-gen (s/and int? #(< 0 % 100)) #(gen/choose 18 90))) (s/def ::age-string (s/and string? #(<= 0 (js/parseInt %) 100))) (s/def ::date-of-birth-string (s/and string? #(= (count %) 10) #(try (let [t (timef/parse (timef/formatter "dd/MM/YYYY") %)] (and (time/before? t (time/now)) (time/after? t (time/date-time 1900)))) (catch :default e false)))) (s/def ::optional-dob-string (s/nilable ::date-of-birth-string)) (s/def ::date-of-birth ::timestamp) (s/def ::age-updated-at ::recent-timestamp) (s/def ::created-at ::recent-timestamp) (s/def ::updated-at ::recent-timestamp) (s/def ::deleted-at ::recent-timestamp) (s/def ::phone-number (s/with-gen (s/and string? not-empty #(re-find #"^\d*$" %)) #(gen/fmap str (gen/choose 6000000000 9999999999)))) (s/def ::village-or-colony (s/with-gen (s/and string? not-empty) #(gen/elements (:village-or-colony common-addresses)))) (s/def ::systolic (s/with-gen int? #(gen/choose 50 300))) (s/def ::diastolic (s/with-gen int? #(gen/choose 50 100))) (s/def ::blood-pressure (s/keys :req-un [::systolic ::diastolic ::created-at ::updated-at])) (s/def ::blood-pressures (s/with-gen (s/coll-of ::blood-pressure) #(gen/vector (s/gen ::blood-pressure) 0 5))) (s/def ::drug-name (s/with-gen (and string? not-empty) #(gen/elements #{"<NAME>" "<NAME>" "<NAME>" "<NAME>" "customoril" "<NAME>"}))) (s/def ::drug-dosage (s/with-gen (and string? not-empty) #(gen/elements #{"10mg" "5mg" "1 packet" "10 times" "12.5g" "20mg"}))) (s/def ::custom-drug (s/keys :req-un [::id ::drug-name ::drug-dosage ::created-at ::updated-at])) (s/def ::custom-drugs (s/with-gen (s/map-of ::id ::custom-drug) #(gen/fmap (fn [ds] (zipmap (map :id ds) ds)) (gen/vector (s/gen ::custom-drug) 0 2)))) (s/def ::drug-ids (s/with-gen set? #(gen/set (gen/elements protocol-drug-ids) {:min-elements 0 :max-elements 3}))) (s/def ::protocol-drugs (s/keys :req-un [::updated-at ::drug-ids])) (s/def ::prescription-drugs (s/keys :req-un [::protocol-drugs ::custom-drugs])) (def patient-fields #{:id :full-name :age :phone-number :gender :date-of-birth :village-or-colony :district :state}) (s/def ::patient (s/keys :req-un [::id ::gender ::full-name ::status ::date-of-birth ::age ::age-updated-at ::created-at ::updated-at ::phone-number ::village-or-colony ::blood-pressures ::prescription-drugs])) (defn generate-patients [num-patients] (let [patients (gen/sample (s/gen ::patient) num-patients)] (zipmap (map :id patients) patients))) (comment ;;gen patients (dotimes [_ 10] (re-frame.core/dispatch [:add-patient (gen/generate (s/gen ::patient))])) )
true
(ns simple-experiments.db.patient (:require [clojure.spec.alpha :as s] [clojure.string :as string] [clojure.test.check] [cljs-time.core :as time] [cljs-time.coerce :as timec] [cljs-time.format :as timef] [clojure.test.check.generators :as tcgen] [clojure.spec.gen.alpha :as gen])) (def common-names {:female #{"anjali" "divya" "PI:NAME:<NAME>END_PIita" "priya" "priyanka" "riya" "shreya" "tanvi" "tanya" "vani"}, :male #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "shPI:NAME:<NAME>END_PI" "yPI:NAME:<NAME>END_PI"}, :transgender #{"bharathi" "madhu" "manabi" "anjum" "vani" "riya" "shreya" "kiran" "amit"} :last-name #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"}}) (def common-addresses {:street-name ["Bhagat singh colony" "Gandhi Basti" "NFL Colony" "Farid Nagari" "Bathinda Road" "Bus Stand Rd" "Hirke Road" "Makhewala Jhanduke Road"] :village-or-colony ["Bathinda" "Bhagwangarh" "Dannewala" "Nandgarh" "Nathana" "Bhikhi" "Budhlada" "Hirke" "Jhanduke" "Mansa" "Bareta" "Bhaini" "Bagha" "Sadulgarh" "Sardulewala"]}) (def protocol-drugs [[:amlodipine [{:id :am-5 :drug-dosage "5mg"} {:id :am-10 :drug-dosage "10mg"}]] [:telmisartan [{:id :tel-40 :drug-dosage "40mg"} {:id :tel-80 :drug-dosage "80mg"}]] [:chlorthalidone [{:id :chlo-12-5 :drug-dosage "12.5mg"} {:id :chlo-25 :drug-dosage "25mg"}]]]) (def protocol-drugs-by-id (->> (for [[drug-name drugs] protocol-drugs {:keys [id drug-dosage]} drugs] {id {:drug-name drug-name :drug-dosage drug-dosage}}) (into {}))) (def protocol-drug-ids (set (keys protocol-drugs-by-id))) (s/def ::non-empty-string (s/and string? not-empty)) (s/def ::id (s/with-gen (s/and string? #(= 36 (count %))) #(gen/fmap (fn [x] (str x)) (gen/uuid)))) (s/def ::gender #{"male" "female" "transgender"}) (s/def ::full-name (s/with-gen (s/and string? not-empty) #(gen/fmap (fn [x] (string/join " " (take 2 x))) (tcgen/shuffle (apply concat (vals common-names)))))) (s/def ::status #{"active" "dead" "migrated" "unresponsive" "inactive"}) (s/def ::timestamp (s/with-gen int? #(gen/choose (timec/to-long (time/date-time 1920 0 0)) (timec/to-long (time/now))))) (s/def ::recent-timestamp (s/with-gen int? #(gen/choose (timec/to-long (time/minus (time/now) (time/days 50))) (timec/to-long (time/now))))) (s/def ::age (s/with-gen (s/and int? #(< 0 % 100)) #(gen/choose 18 90))) (s/def ::age-string (s/and string? #(<= 0 (js/parseInt %) 100))) (s/def ::date-of-birth-string (s/and string? #(= (count %) 10) #(try (let [t (timef/parse (timef/formatter "dd/MM/YYYY") %)] (and (time/before? t (time/now)) (time/after? t (time/date-time 1900)))) (catch :default e false)))) (s/def ::optional-dob-string (s/nilable ::date-of-birth-string)) (s/def ::date-of-birth ::timestamp) (s/def ::age-updated-at ::recent-timestamp) (s/def ::created-at ::recent-timestamp) (s/def ::updated-at ::recent-timestamp) (s/def ::deleted-at ::recent-timestamp) (s/def ::phone-number (s/with-gen (s/and string? not-empty #(re-find #"^\d*$" %)) #(gen/fmap str (gen/choose 6000000000 9999999999)))) (s/def ::village-or-colony (s/with-gen (s/and string? not-empty) #(gen/elements (:village-or-colony common-addresses)))) (s/def ::systolic (s/with-gen int? #(gen/choose 50 300))) (s/def ::diastolic (s/with-gen int? #(gen/choose 50 100))) (s/def ::blood-pressure (s/keys :req-un [::systolic ::diastolic ::created-at ::updated-at])) (s/def ::blood-pressures (s/with-gen (s/coll-of ::blood-pressure) #(gen/vector (s/gen ::blood-pressure) 0 5))) (s/def ::drug-name (s/with-gen (and string? not-empty) #(gen/elements #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "customoril" "PI:NAME:<NAME>END_PI"}))) (s/def ::drug-dosage (s/with-gen (and string? not-empty) #(gen/elements #{"10mg" "5mg" "1 packet" "10 times" "12.5g" "20mg"}))) (s/def ::custom-drug (s/keys :req-un [::id ::drug-name ::drug-dosage ::created-at ::updated-at])) (s/def ::custom-drugs (s/with-gen (s/map-of ::id ::custom-drug) #(gen/fmap (fn [ds] (zipmap (map :id ds) ds)) (gen/vector (s/gen ::custom-drug) 0 2)))) (s/def ::drug-ids (s/with-gen set? #(gen/set (gen/elements protocol-drug-ids) {:min-elements 0 :max-elements 3}))) (s/def ::protocol-drugs (s/keys :req-un [::updated-at ::drug-ids])) (s/def ::prescription-drugs (s/keys :req-un [::protocol-drugs ::custom-drugs])) (def patient-fields #{:id :full-name :age :phone-number :gender :date-of-birth :village-or-colony :district :state}) (s/def ::patient (s/keys :req-un [::id ::gender ::full-name ::status ::date-of-birth ::age ::age-updated-at ::created-at ::updated-at ::phone-number ::village-or-colony ::blood-pressures ::prescription-drugs])) (defn generate-patients [num-patients] (let [patients (gen/sample (s/gen ::patient) num-patients)] (zipmap (map :id patients) patients))) (comment ;;gen patients (dotimes [_ 10] (re-frame.core/dispatch [:add-patient (gen/generate (s/gen ::patient))])) )
[ { "context": "ct\n (fn use-query-effect []\n (let [key (rand)]\n (d/listen! conn key listener)\n ", "end": 9102, "score": 0.3521166741847992, "start": 9098, "tag": "KEY", "value": "rand" } ]
src/homebase/react.cljs
mchaudhry05/homebase-react
0
(ns homebase.react (:require ["react" :as react] [clojure.string] [cljs.reader] [goog.object] [clojure.set] [homebase.js :as hbjs] [datascript.core :as d] [datascript.impl.entity :as de])) (defn try-hook [hook-name f] (if hbjs/*debug* (f) (try (f) (catch js/Error e (throw (js/Error. (condp re-find (goog.object/get e "message") #"No protocol method IDeref.-deref defined for type undefined" "HomebaseProvider context unavailable. <HomebaseProvider> must be declared by a parent component before homebase-react hooks can be used." (str (goog.object/get e "message") "\n" (some->> (goog.object/get e "stack") (re-find (re-pattern (str hook-name ".*\\n(.*)\\n?"))) (second) (clojure.string/trim)))))))))) (defn debug-msg [return-value & msgs] (when (and (number? hbjs/*debug*) (>= hbjs/*debug* 2)) (apply js/console.log "%c homebase-react " "background: yellow" msgs)) return-value) (defn changed? [entities cached-entities track-count?] (cond (and track-count? (not= (count entities) (count cached-entities))) (debug-msg true "cache:miss" "count of entities != cache" #js {:entities (clj->js entities) :cache (clj->js cached-entities)}) (and track-count? (not (clojure.set/superset? (set (keys cached-entities)) (set (map #(get % "id") entities))))) (debug-msg true "cache:miss" "cache not superset of entities" #js {:entities (clj->js entities) :cache (clj->js cached-entities)}) :else (reduce (fn [_ e] (when (let [id (get e "id") cached-e (get cached-entities id)] (if (nil? cached-e) (if-not id (reduced false) ; This entity has probably been removed, do not force a rerender (reduced (debug-msg true "cache:miss" "not in cache" #js {:entity-id id :entities (clj->js entities) :cache (clj->js cached-entities)}))) (reduce (fn [_ [ks old-v]] (let [e-without-cache (hbjs/Entity. ^de/Entity (.-_entity e) nil nil nil nil) new-v (.apply (.-get e-without-cache) e-without-cache (into-array ks))] (when (and (not= 0 (compare old-v new-v)) ;; Ignore Entities and arrays of Entities (not (or (instance? hbjs/Entity new-v) (and (array? new-v) (= (count new-v) (count old-v)) (instance? hbjs/Entity (nth new-v 0)))))) (reduced (debug-msg true "cache:miss" "value changed" #js {:entity-id id :attr-path (clj->js ks) :e e :old-v old-v :new-v new-v :entities (clj->js entities) :cache (clj->js cached-entities)}))))) nil cached-e))) (reduced true))) nil entities))) (defn cache->js [entity cached-entities] (reduce (fn [acc [ks v]] (goog.object/set acc (str (to-array ks)) v) acc) #js {} (get @cached-entities (get entity "id")))) (defn touch-entity-cache [entity cached-entities] (let [get-cb (fn [[e ks v]] (if (get e "id") (do (swap! cached-entities assoc-in [(get e "id") ks] v) (when hbjs/*debug* (set! ^js/Object (.-_recentlyTouchedAttributes entity) (cache->js e cached-entities)))) (do (reset! cached-entities {}) (when hbjs/*debug* (set! ^js/Object (.-_recentlyTouchedAttributes entity) #js {}))))) _ (when hbjs/*debug* (set! ^js/Object (.-_recentlyTouchedAttributes entity) #js {})) ; Use (set! ...) instead of (vary-meta) to preserve the reference to the original entity ;; entity (vary-meta entity merge {:Entity/get-cb get-cb}) _ (set! ^hbjs/Entity (.-_meta entity) {:Entity/get-cb get-cb})] entity)) (defn datom-select-keys [d] #js [(:e d) (str (:a d)) (:v d) (:tx d) (:added d)]) (defn datoms->js [datoms] (-> datoms into-array (.map datom-select-keys))) ;; (defn datoms->json [datoms] ;; (reduce ;; (fn [acc {:keys [e a v]}] ;; (assoc-in acc [e (namespace a) (name a)] v)) ;; {} datoms)) (defonce ^:export homebase-context (react/createContext)) (def base-schema {:db/ident {:db/unique :db.unique/identity} :homebase.array/ref {:db/type :db.type/ref :db/cardinality :db.cardinality/one}}) (defn ^:export HomebaseProvider [props] (let [schema (goog.object/getValueByKeys props #js ["config" "schema"]) initial-tx (goog.object/getValueByKeys props #js ["config" "initialData"]) debug (goog.object/getValueByKeys props #js ["config" "debug"]) _ (when debug (set! hbjs/*debug* debug)) conn (d/create-conn (if schema (merge (hbjs/js->schema schema) base-schema) base-schema))] (when initial-tx (hbjs/transact! conn initial-tx)) (react/createElement (goog.object/get homebase-context "Provider") #js {:value conn} (goog.object/get props "children")))) (defn ^:export useClient [] (let [conn (react/useContext homebase-context) key (react/useMemo rand #js []) client (react/useMemo (fn [] #js {"dbToString" #(pr-str @conn) "dbFromString" #(do (reset! conn (cljs.reader/read-string %)) (d/transact! conn [] ::silent)) "dbToDatoms" #(datoms->js (d/datoms @conn :eavt)) ;; "dbToJSON" #(clj->js (datoms->json (d/datoms @conn :eavt))) "transactSilently" (fn [tx] (try-hook "useClient" #(hbjs/transact! conn tx ::silent))) "addTransactListener" (fn [listener-fn] (d/listen! conn key #(when (not= ::silent (:tx-meta %)) (listener-fn (datoms->js (:tx-data %)))))) "removeTransactListener" #(d/unlisten! conn key)}) #js [])] [client])) (defn ^:export useEntity [lookup] (let [conn (react/useContext homebase-context) cached-entities (react/useMemo #(atom {}) #js []) run-lookup (react/useCallback (fn run-lookup [] (touch-entity-cache (try-hook "useEntity" #(hbjs/entity conn lookup)) cached-entities)) #js [lookup]) [result setResult] (react/useState (run-lookup)) listener (react/useCallback (fn entity-listener [] (let [result (run-lookup)] (when (changed? #js [result] @cached-entities false) (setResult result)))) #js [run-lookup])] (react/useEffect (fn use-entity-effect [] (let [key (rand)] (d/listen! conn key listener) #(d/unlisten! conn key))) #js [lookup]) [result])) (defn ^:export useQuery [query & args] (let [conn (react/useContext homebase-context) cached-entities (react/useMemo #(atom {}) #js []) run-query (react/useCallback (fn run-query [] (let [result (try-hook "useQuery" #(apply hbjs/q query conn args))] (when (and (not= (count result) (count @cached-entities)) (not= 0 (count result))) (reset! cached-entities {})) (.map result (fn [e] (touch-entity-cache e cached-entities))))) #js [query args]) [result setResult] (react/useState (run-query)) listener (react/useCallback (fn query-listener [] (let [result (run-query)] (when (changed? result @cached-entities true) (setResult result)))) #js [run-query])] (react/useEffect (fn use-query-effect [] (let [key (rand)] (d/listen! conn key listener) #(d/unlisten! conn key))) #js [query args]) [result])) (defn ^:export useTransact [] (let [conn (react/useContext homebase-context) transact (react/useCallback (fn transact [tx] (try-hook "useTransact" #(hbjs/transact! conn tx))) #js [])] [transact]))
44054
(ns homebase.react (:require ["react" :as react] [clojure.string] [cljs.reader] [goog.object] [clojure.set] [homebase.js :as hbjs] [datascript.core :as d] [datascript.impl.entity :as de])) (defn try-hook [hook-name f] (if hbjs/*debug* (f) (try (f) (catch js/Error e (throw (js/Error. (condp re-find (goog.object/get e "message") #"No protocol method IDeref.-deref defined for type undefined" "HomebaseProvider context unavailable. <HomebaseProvider> must be declared by a parent component before homebase-react hooks can be used." (str (goog.object/get e "message") "\n" (some->> (goog.object/get e "stack") (re-find (re-pattern (str hook-name ".*\\n(.*)\\n?"))) (second) (clojure.string/trim)))))))))) (defn debug-msg [return-value & msgs] (when (and (number? hbjs/*debug*) (>= hbjs/*debug* 2)) (apply js/console.log "%c homebase-react " "background: yellow" msgs)) return-value) (defn changed? [entities cached-entities track-count?] (cond (and track-count? (not= (count entities) (count cached-entities))) (debug-msg true "cache:miss" "count of entities != cache" #js {:entities (clj->js entities) :cache (clj->js cached-entities)}) (and track-count? (not (clojure.set/superset? (set (keys cached-entities)) (set (map #(get % "id") entities))))) (debug-msg true "cache:miss" "cache not superset of entities" #js {:entities (clj->js entities) :cache (clj->js cached-entities)}) :else (reduce (fn [_ e] (when (let [id (get e "id") cached-e (get cached-entities id)] (if (nil? cached-e) (if-not id (reduced false) ; This entity has probably been removed, do not force a rerender (reduced (debug-msg true "cache:miss" "not in cache" #js {:entity-id id :entities (clj->js entities) :cache (clj->js cached-entities)}))) (reduce (fn [_ [ks old-v]] (let [e-without-cache (hbjs/Entity. ^de/Entity (.-_entity e) nil nil nil nil) new-v (.apply (.-get e-without-cache) e-without-cache (into-array ks))] (when (and (not= 0 (compare old-v new-v)) ;; Ignore Entities and arrays of Entities (not (or (instance? hbjs/Entity new-v) (and (array? new-v) (= (count new-v) (count old-v)) (instance? hbjs/Entity (nth new-v 0)))))) (reduced (debug-msg true "cache:miss" "value changed" #js {:entity-id id :attr-path (clj->js ks) :e e :old-v old-v :new-v new-v :entities (clj->js entities) :cache (clj->js cached-entities)}))))) nil cached-e))) (reduced true))) nil entities))) (defn cache->js [entity cached-entities] (reduce (fn [acc [ks v]] (goog.object/set acc (str (to-array ks)) v) acc) #js {} (get @cached-entities (get entity "id")))) (defn touch-entity-cache [entity cached-entities] (let [get-cb (fn [[e ks v]] (if (get e "id") (do (swap! cached-entities assoc-in [(get e "id") ks] v) (when hbjs/*debug* (set! ^js/Object (.-_recentlyTouchedAttributes entity) (cache->js e cached-entities)))) (do (reset! cached-entities {}) (when hbjs/*debug* (set! ^js/Object (.-_recentlyTouchedAttributes entity) #js {}))))) _ (when hbjs/*debug* (set! ^js/Object (.-_recentlyTouchedAttributes entity) #js {})) ; Use (set! ...) instead of (vary-meta) to preserve the reference to the original entity ;; entity (vary-meta entity merge {:Entity/get-cb get-cb}) _ (set! ^hbjs/Entity (.-_meta entity) {:Entity/get-cb get-cb})] entity)) (defn datom-select-keys [d] #js [(:e d) (str (:a d)) (:v d) (:tx d) (:added d)]) (defn datoms->js [datoms] (-> datoms into-array (.map datom-select-keys))) ;; (defn datoms->json [datoms] ;; (reduce ;; (fn [acc {:keys [e a v]}] ;; (assoc-in acc [e (namespace a) (name a)] v)) ;; {} datoms)) (defonce ^:export homebase-context (react/createContext)) (def base-schema {:db/ident {:db/unique :db.unique/identity} :homebase.array/ref {:db/type :db.type/ref :db/cardinality :db.cardinality/one}}) (defn ^:export HomebaseProvider [props] (let [schema (goog.object/getValueByKeys props #js ["config" "schema"]) initial-tx (goog.object/getValueByKeys props #js ["config" "initialData"]) debug (goog.object/getValueByKeys props #js ["config" "debug"]) _ (when debug (set! hbjs/*debug* debug)) conn (d/create-conn (if schema (merge (hbjs/js->schema schema) base-schema) base-schema))] (when initial-tx (hbjs/transact! conn initial-tx)) (react/createElement (goog.object/get homebase-context "Provider") #js {:value conn} (goog.object/get props "children")))) (defn ^:export useClient [] (let [conn (react/useContext homebase-context) key (react/useMemo rand #js []) client (react/useMemo (fn [] #js {"dbToString" #(pr-str @conn) "dbFromString" #(do (reset! conn (cljs.reader/read-string %)) (d/transact! conn [] ::silent)) "dbToDatoms" #(datoms->js (d/datoms @conn :eavt)) ;; "dbToJSON" #(clj->js (datoms->json (d/datoms @conn :eavt))) "transactSilently" (fn [tx] (try-hook "useClient" #(hbjs/transact! conn tx ::silent))) "addTransactListener" (fn [listener-fn] (d/listen! conn key #(when (not= ::silent (:tx-meta %)) (listener-fn (datoms->js (:tx-data %)))))) "removeTransactListener" #(d/unlisten! conn key)}) #js [])] [client])) (defn ^:export useEntity [lookup] (let [conn (react/useContext homebase-context) cached-entities (react/useMemo #(atom {}) #js []) run-lookup (react/useCallback (fn run-lookup [] (touch-entity-cache (try-hook "useEntity" #(hbjs/entity conn lookup)) cached-entities)) #js [lookup]) [result setResult] (react/useState (run-lookup)) listener (react/useCallback (fn entity-listener [] (let [result (run-lookup)] (when (changed? #js [result] @cached-entities false) (setResult result)))) #js [run-lookup])] (react/useEffect (fn use-entity-effect [] (let [key (rand)] (d/listen! conn key listener) #(d/unlisten! conn key))) #js [lookup]) [result])) (defn ^:export useQuery [query & args] (let [conn (react/useContext homebase-context) cached-entities (react/useMemo #(atom {}) #js []) run-query (react/useCallback (fn run-query [] (let [result (try-hook "useQuery" #(apply hbjs/q query conn args))] (when (and (not= (count result) (count @cached-entities)) (not= 0 (count result))) (reset! cached-entities {})) (.map result (fn [e] (touch-entity-cache e cached-entities))))) #js [query args]) [result setResult] (react/useState (run-query)) listener (react/useCallback (fn query-listener [] (let [result (run-query)] (when (changed? result @cached-entities true) (setResult result)))) #js [run-query])] (react/useEffect (fn use-query-effect [] (let [key (<KEY>)] (d/listen! conn key listener) #(d/unlisten! conn key))) #js [query args]) [result])) (defn ^:export useTransact [] (let [conn (react/useContext homebase-context) transact (react/useCallback (fn transact [tx] (try-hook "useTransact" #(hbjs/transact! conn tx))) #js [])] [transact]))
true
(ns homebase.react (:require ["react" :as react] [clojure.string] [cljs.reader] [goog.object] [clojure.set] [homebase.js :as hbjs] [datascript.core :as d] [datascript.impl.entity :as de])) (defn try-hook [hook-name f] (if hbjs/*debug* (f) (try (f) (catch js/Error e (throw (js/Error. (condp re-find (goog.object/get e "message") #"No protocol method IDeref.-deref defined for type undefined" "HomebaseProvider context unavailable. <HomebaseProvider> must be declared by a parent component before homebase-react hooks can be used." (str (goog.object/get e "message") "\n" (some->> (goog.object/get e "stack") (re-find (re-pattern (str hook-name ".*\\n(.*)\\n?"))) (second) (clojure.string/trim)))))))))) (defn debug-msg [return-value & msgs] (when (and (number? hbjs/*debug*) (>= hbjs/*debug* 2)) (apply js/console.log "%c homebase-react " "background: yellow" msgs)) return-value) (defn changed? [entities cached-entities track-count?] (cond (and track-count? (not= (count entities) (count cached-entities))) (debug-msg true "cache:miss" "count of entities != cache" #js {:entities (clj->js entities) :cache (clj->js cached-entities)}) (and track-count? (not (clojure.set/superset? (set (keys cached-entities)) (set (map #(get % "id") entities))))) (debug-msg true "cache:miss" "cache not superset of entities" #js {:entities (clj->js entities) :cache (clj->js cached-entities)}) :else (reduce (fn [_ e] (when (let [id (get e "id") cached-e (get cached-entities id)] (if (nil? cached-e) (if-not id (reduced false) ; This entity has probably been removed, do not force a rerender (reduced (debug-msg true "cache:miss" "not in cache" #js {:entity-id id :entities (clj->js entities) :cache (clj->js cached-entities)}))) (reduce (fn [_ [ks old-v]] (let [e-without-cache (hbjs/Entity. ^de/Entity (.-_entity e) nil nil nil nil) new-v (.apply (.-get e-without-cache) e-without-cache (into-array ks))] (when (and (not= 0 (compare old-v new-v)) ;; Ignore Entities and arrays of Entities (not (or (instance? hbjs/Entity new-v) (and (array? new-v) (= (count new-v) (count old-v)) (instance? hbjs/Entity (nth new-v 0)))))) (reduced (debug-msg true "cache:miss" "value changed" #js {:entity-id id :attr-path (clj->js ks) :e e :old-v old-v :new-v new-v :entities (clj->js entities) :cache (clj->js cached-entities)}))))) nil cached-e))) (reduced true))) nil entities))) (defn cache->js [entity cached-entities] (reduce (fn [acc [ks v]] (goog.object/set acc (str (to-array ks)) v) acc) #js {} (get @cached-entities (get entity "id")))) (defn touch-entity-cache [entity cached-entities] (let [get-cb (fn [[e ks v]] (if (get e "id") (do (swap! cached-entities assoc-in [(get e "id") ks] v) (when hbjs/*debug* (set! ^js/Object (.-_recentlyTouchedAttributes entity) (cache->js e cached-entities)))) (do (reset! cached-entities {}) (when hbjs/*debug* (set! ^js/Object (.-_recentlyTouchedAttributes entity) #js {}))))) _ (when hbjs/*debug* (set! ^js/Object (.-_recentlyTouchedAttributes entity) #js {})) ; Use (set! ...) instead of (vary-meta) to preserve the reference to the original entity ;; entity (vary-meta entity merge {:Entity/get-cb get-cb}) _ (set! ^hbjs/Entity (.-_meta entity) {:Entity/get-cb get-cb})] entity)) (defn datom-select-keys [d] #js [(:e d) (str (:a d)) (:v d) (:tx d) (:added d)]) (defn datoms->js [datoms] (-> datoms into-array (.map datom-select-keys))) ;; (defn datoms->json [datoms] ;; (reduce ;; (fn [acc {:keys [e a v]}] ;; (assoc-in acc [e (namespace a) (name a)] v)) ;; {} datoms)) (defonce ^:export homebase-context (react/createContext)) (def base-schema {:db/ident {:db/unique :db.unique/identity} :homebase.array/ref {:db/type :db.type/ref :db/cardinality :db.cardinality/one}}) (defn ^:export HomebaseProvider [props] (let [schema (goog.object/getValueByKeys props #js ["config" "schema"]) initial-tx (goog.object/getValueByKeys props #js ["config" "initialData"]) debug (goog.object/getValueByKeys props #js ["config" "debug"]) _ (when debug (set! hbjs/*debug* debug)) conn (d/create-conn (if schema (merge (hbjs/js->schema schema) base-schema) base-schema))] (when initial-tx (hbjs/transact! conn initial-tx)) (react/createElement (goog.object/get homebase-context "Provider") #js {:value conn} (goog.object/get props "children")))) (defn ^:export useClient [] (let [conn (react/useContext homebase-context) key (react/useMemo rand #js []) client (react/useMemo (fn [] #js {"dbToString" #(pr-str @conn) "dbFromString" #(do (reset! conn (cljs.reader/read-string %)) (d/transact! conn [] ::silent)) "dbToDatoms" #(datoms->js (d/datoms @conn :eavt)) ;; "dbToJSON" #(clj->js (datoms->json (d/datoms @conn :eavt))) "transactSilently" (fn [tx] (try-hook "useClient" #(hbjs/transact! conn tx ::silent))) "addTransactListener" (fn [listener-fn] (d/listen! conn key #(when (not= ::silent (:tx-meta %)) (listener-fn (datoms->js (:tx-data %)))))) "removeTransactListener" #(d/unlisten! conn key)}) #js [])] [client])) (defn ^:export useEntity [lookup] (let [conn (react/useContext homebase-context) cached-entities (react/useMemo #(atom {}) #js []) run-lookup (react/useCallback (fn run-lookup [] (touch-entity-cache (try-hook "useEntity" #(hbjs/entity conn lookup)) cached-entities)) #js [lookup]) [result setResult] (react/useState (run-lookup)) listener (react/useCallback (fn entity-listener [] (let [result (run-lookup)] (when (changed? #js [result] @cached-entities false) (setResult result)))) #js [run-lookup])] (react/useEffect (fn use-entity-effect [] (let [key (rand)] (d/listen! conn key listener) #(d/unlisten! conn key))) #js [lookup]) [result])) (defn ^:export useQuery [query & args] (let [conn (react/useContext homebase-context) cached-entities (react/useMemo #(atom {}) #js []) run-query (react/useCallback (fn run-query [] (let [result (try-hook "useQuery" #(apply hbjs/q query conn args))] (when (and (not= (count result) (count @cached-entities)) (not= 0 (count result))) (reset! cached-entities {})) (.map result (fn [e] (touch-entity-cache e cached-entities))))) #js [query args]) [result setResult] (react/useState (run-query)) listener (react/useCallback (fn query-listener [] (let [result (run-query)] (when (changed? result @cached-entities true) (setResult result)))) #js [run-query])] (react/useEffect (fn use-query-effect [] (let [key (PI:KEY:<KEY>END_PI)] (d/listen! conn key listener) #(d/unlisten! conn key))) #js [query args]) [result])) (defn ^:export useTransact [] (let [conn (react/useContext homebase-context) transact (react/useCallback (fn transact [tx] (try-hook "useTransact" #(hbjs/transact! conn tx))) #js [])] [transact]))
[ { "context": "star_wars))\n (def mega_blaster_wars {:ep1 {:old \"Yoyoda\" :crazy \"Maul\" :master \"Qigon Jin\"} :ep3 {:vader ", "end": 212, "score": 0.9611355662345886, "start": 206, "tag": "NAME", "value": "Yoyoda" }, { "context": "ef mega_blaster_wars {:ep1 {:old \"Yoyoda\" :crazy \"Maul\" :master \"Qigon Jin\"} :ep3 {:vader \"Darth Vader\"}", "end": 226, "score": 0.9898852109909058, "start": 222, "tag": "NAME", "value": "Maul" }, { "context": "_wars {:ep1 {:old \"Yoyoda\" :crazy \"Maul\" :master \"Qigon Jin\"} :ep3 {:vader \"Darth Vader\"}})\n (println (:craz", "end": 246, "score": 0.9993854761123657, "start": 237, "tag": "NAME", "value": "Qigon Jin" }, { "context": ":crazy \"Maul\" :master \"Qigon Jin\"} :ep3 {:vader \"Darth Vader\"}})\n (println (:crazy (:ep1 mega_blaster_w", "end": 268, "score": 0.5524269938468933, "start": 264, "tag": "NAME", "value": "arth" } ]
let-the-noob-be-with-you/src/let_the_noob_be_with_you/core.clj
naomijub/Noobing
0
(ns let-the-noob-be-with-you.core (:gen-class)) (defn -main [& args] (def star_wars {:best "Chewwie" :last "Luke" :power "Leia"}) (println (:power star_wars)) (def mega_blaster_wars {:ep1 {:old "Yoyoda" :crazy "Maul" :master "Qigon Jin"} :ep3 {:vader "Darth Vader"}}) (println (:crazy (:ep1 mega_blaster_wars))) (def crazy_games ["Lol" "Heroes" "Dota"]) (println (get crazy_games 0)) (def crazyness (conj crazy_games "Age of Empires")) (println (get crazyness 3)) (def my_sw_lis '(:best :last :power)) (println ((nth my_sw_lis 0) star_wars)) )
37157
(ns let-the-noob-be-with-you.core (:gen-class)) (defn -main [& args] (def star_wars {:best "Chewwie" :last "Luke" :power "Leia"}) (println (:power star_wars)) (def mega_blaster_wars {:ep1 {:old "<NAME>" :crazy "<NAME>" :master "<NAME>"} :ep3 {:vader "D<NAME> Vader"}}) (println (:crazy (:ep1 mega_blaster_wars))) (def crazy_games ["Lol" "Heroes" "Dota"]) (println (get crazy_games 0)) (def crazyness (conj crazy_games "Age of Empires")) (println (get crazyness 3)) (def my_sw_lis '(:best :last :power)) (println ((nth my_sw_lis 0) star_wars)) )
true
(ns let-the-noob-be-with-you.core (:gen-class)) (defn -main [& args] (def star_wars {:best "Chewwie" :last "Luke" :power "Leia"}) (println (:power star_wars)) (def mega_blaster_wars {:ep1 {:old "PI:NAME:<NAME>END_PI" :crazy "PI:NAME:<NAME>END_PI" :master "PI:NAME:<NAME>END_PI"} :ep3 {:vader "DPI:NAME:<NAME>END_PI Vader"}}) (println (:crazy (:ep1 mega_blaster_wars))) (def crazy_games ["Lol" "Heroes" "Dota"]) (println (get crazy_games 0)) (def crazyness (conj crazy_games "Age of Empires")) (println (get crazyness 3)) (def my_sw_lis '(:best :last :power)) (println ((nth my_sw_lis 0) star_wars)) )
[ { "context": ";; Copyright (c) Andrew A. Raines\n;;\n;; Permission is hereby granted, free of charg", "end": 33, "score": 0.9998785853385925, "start": 17, "tag": "NAME", "value": "Andrew A. Raines" } ]
src/postal/support.clj
guv/postal
0
;; Copyright (c) Andrew A. Raines ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following ;; conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;; OTHER DEALINGS IN THE SOFTWARE. (ns postal.support (:require [clojure.java.io :as io]) (:import (java.util Properties Random) (org.apache.commons.codec.binary Base64))) (def boolean-props #{:allow8bitmime :auth :auth.login.disable :auth.plain.disable :auth.digest-md5.disable :auth.ntlm.disable :ehlo :noop.strict :quitwait :reportsuccess :sasl.enable :sasl.usecanonicalhostname :sendpartial :socketFactory.fallback :ssl.enable :ssl.checkserveridentity :starttls.enable :starttls.required :userset}) (defmacro do-when [arg condition & body] `(when ~condition (doto ~arg ~@body))) (defn prop-names [sender {:keys [user ssl] :as params}] (let [prop-map {:tls :starttls.enable} defaults {:host "not.provided" :port (if ssl 465 25) :auth (boolean user)}] (into {} (apply concat (for [[k v] (merge defaults (if sender {:from sender} {}) (dissoc params :pass :ssl :proto)) :when (not (nil? v)) :let [k (if (prop-map k) (prop-map k) k) v (if (or (instance? Boolean v) (boolean-props k)) (if v "true" "false") v)]] (if (keyword? k) [[(str "mail.smtp." (name k)) v] [(str "mail.smtps." (name k)) v]] [[k v]])))))) (defn make-props [sender params] (let [p (Properties.)] (doseq [[k v] (prop-names sender params)] (.put p k v)) p)) (defn hostname [] (.getHostName (java.net.InetAddress/getLocalHost))) (defn message-id ([] (message-id (format "postal.%s" (hostname)))) ([host] (let [bs (byte-array 16) r (Random.) _ (.nextBytes r bs) rs (String. (Base64/encodeBase64 bs)) onlychars (apply str (re-seq #"[0-9A-Za-z]" rs)) epoch (.getTime (java.util.Date.))] (format "<%s.%s@%s>" onlychars epoch host)))) (defn pom-version [] (let [pom "META-INF/maven/org.clojars.guv/postal/pom.properties" props (doto (Properties.) (.load (-> pom io/resource io/input-stream)))] (.getProperty props "version"))) (defn user-agent [] (let [prop (Properties.) ver (or (System/getProperty "postal.version") (pom-version))] (format "postal/%s" ver)))
71919
;; Copyright (c) <NAME> ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following ;; conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;; OTHER DEALINGS IN THE SOFTWARE. (ns postal.support (:require [clojure.java.io :as io]) (:import (java.util Properties Random) (org.apache.commons.codec.binary Base64))) (def boolean-props #{:allow8bitmime :auth :auth.login.disable :auth.plain.disable :auth.digest-md5.disable :auth.ntlm.disable :ehlo :noop.strict :quitwait :reportsuccess :sasl.enable :sasl.usecanonicalhostname :sendpartial :socketFactory.fallback :ssl.enable :ssl.checkserveridentity :starttls.enable :starttls.required :userset}) (defmacro do-when [arg condition & body] `(when ~condition (doto ~arg ~@body))) (defn prop-names [sender {:keys [user ssl] :as params}] (let [prop-map {:tls :starttls.enable} defaults {:host "not.provided" :port (if ssl 465 25) :auth (boolean user)}] (into {} (apply concat (for [[k v] (merge defaults (if sender {:from sender} {}) (dissoc params :pass :ssl :proto)) :when (not (nil? v)) :let [k (if (prop-map k) (prop-map k) k) v (if (or (instance? Boolean v) (boolean-props k)) (if v "true" "false") v)]] (if (keyword? k) [[(str "mail.smtp." (name k)) v] [(str "mail.smtps." (name k)) v]] [[k v]])))))) (defn make-props [sender params] (let [p (Properties.)] (doseq [[k v] (prop-names sender params)] (.put p k v)) p)) (defn hostname [] (.getHostName (java.net.InetAddress/getLocalHost))) (defn message-id ([] (message-id (format "postal.%s" (hostname)))) ([host] (let [bs (byte-array 16) r (Random.) _ (.nextBytes r bs) rs (String. (Base64/encodeBase64 bs)) onlychars (apply str (re-seq #"[0-9A-Za-z]" rs)) epoch (.getTime (java.util.Date.))] (format "<%s.%s@%s>" onlychars epoch host)))) (defn pom-version [] (let [pom "META-INF/maven/org.clojars.guv/postal/pom.properties" props (doto (Properties.) (.load (-> pom io/resource io/input-stream)))] (.getProperty props "version"))) (defn user-agent [] (let [prop (Properties.) ver (or (System/getProperty "postal.version") (pom-version))] (format "postal/%s" ver)))
true
;; Copyright (c) PI:NAME:<NAME>END_PI ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following ;; conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;; OTHER DEALINGS IN THE SOFTWARE. (ns postal.support (:require [clojure.java.io :as io]) (:import (java.util Properties Random) (org.apache.commons.codec.binary Base64))) (def boolean-props #{:allow8bitmime :auth :auth.login.disable :auth.plain.disable :auth.digest-md5.disable :auth.ntlm.disable :ehlo :noop.strict :quitwait :reportsuccess :sasl.enable :sasl.usecanonicalhostname :sendpartial :socketFactory.fallback :ssl.enable :ssl.checkserveridentity :starttls.enable :starttls.required :userset}) (defmacro do-when [arg condition & body] `(when ~condition (doto ~arg ~@body))) (defn prop-names [sender {:keys [user ssl] :as params}] (let [prop-map {:tls :starttls.enable} defaults {:host "not.provided" :port (if ssl 465 25) :auth (boolean user)}] (into {} (apply concat (for [[k v] (merge defaults (if sender {:from sender} {}) (dissoc params :pass :ssl :proto)) :when (not (nil? v)) :let [k (if (prop-map k) (prop-map k) k) v (if (or (instance? Boolean v) (boolean-props k)) (if v "true" "false") v)]] (if (keyword? k) [[(str "mail.smtp." (name k)) v] [(str "mail.smtps." (name k)) v]] [[k v]])))))) (defn make-props [sender params] (let [p (Properties.)] (doseq [[k v] (prop-names sender params)] (.put p k v)) p)) (defn hostname [] (.getHostName (java.net.InetAddress/getLocalHost))) (defn message-id ([] (message-id (format "postal.%s" (hostname)))) ([host] (let [bs (byte-array 16) r (Random.) _ (.nextBytes r bs) rs (String. (Base64/encodeBase64 bs)) onlychars (apply str (re-seq #"[0-9A-Za-z]" rs)) epoch (.getTime (java.util.Date.))] (format "<%s.%s@%s>" onlychars epoch host)))) (defn pom-version [] (let [pom "META-INF/maven/org.clojars.guv/postal/pom.properties" props (doto (Properties.) (.load (-> pom io/resource io/input-stream)))] (.getProperty props "version"))) (defn user-agent [] (let [prop (Properties.) ver (or (System/getProperty "postal.version") (pom-version))] (format "postal/%s" ver)))
[ { "context": "92b3523a6c\",\n :author-ident {:email-address \"z@caudate.me\",\n :name \"Chris Zheng\",\n ", "end": 903, "score": 0.9999222159385681, "start": 891, "tag": "EMAIL", "value": "z@caudate.me" }, { "context": "dress \"z@caudate.me\",\n :name \"Chris Zheng\",\n :time-zone-offset 330,\n ", "end": 945, "score": 0.9998898506164551, "start": 934, "tag": "NAME", "value": "Chris Zheng" }, { "context": "92b3523a6c\",\n :author-ident {:email-address \"z@caudate.me\",\n :name \"Chris Zheng\",\n ", "end": 1249, "score": 0.9999222755432129, "start": 1237, "tag": "EMAIL", "value": "z@caudate.me" }, { "context": "dress \"z@caudate.me\",\n :name \"Chris Zheng\",\n :time-zone-offset 330,\n ", "end": 1291, "score": 0.9998895525932312, "start": 1280, "tag": "NAME", "value": "Chris Zheng" }, { "context": "be3c380159\",\n :author-ident {:email-address \"z@caudate.me\",\n :name \"Chris Zheng\",\n ", "end": 1669, "score": 0.9999157786369324, "start": 1657, "tag": "EMAIL", "value": "z@caudate.me" }, { "context": "dress \"z@caudate.me\",\n :name \"Chris Zheng\",\n :time-zone-offset 330,\n ", "end": 1711, "score": 0.9998885989189148, "start": 1700, "tag": "NAME", "value": "Chris Zheng" }, { "context": "33d70bbd21\",\n :author-ident {:email-address \"z@caudate.me\",\n :name \"Chris Zheng\",\n ", "end": 2187, "score": 0.9999164938926697, "start": 2175, "tag": "EMAIL", "value": "z@caudate.me" }, { "context": "dress \"z@caudate.me\",\n :name \"Chris Zheng\",\n :time-zone-offset 330,\n ", "end": 2229, "score": 0.9998810887336731, "start": 2218, "tag": "NAME", "value": "Chris Zheng" }, { "context": "\"9fb08f2b6d10ae1ec8cf15eb81ac56edd504160f\"\n \"2aad32d04470f118c1c891e163290433d70bbd21\"\n \"f21fe52cdc3511918b7d52e43f909dbe3c380159\"", "end": 2793, "score": 0.849139392375946, "start": 2753, "tag": "KEY", "value": "2aad32d04470f118c1c891e163290433d70bbd21" }, { "context": " (git :add :?)\n (git :cd)\n (git :push :remote \"git@github.com:zcaudate/gita.git\")\n (def res (git :pull :&))\n\n ", "end": 4806, "score": 0.8028005361557007, "start": 4792, "tag": "EMAIL", "value": "git@github.com" }, { "context": "\n (git :cd)\n (git :push :remote \"git@github.com:zcaudate/gita.git\")\n (def res (git :pull :&))\n\n (interop", "end": 4815, "score": 0.9995630383491516, "start": 4807, "tag": "USERNAME", "value": "zcaudate" } ]
test/lucid/git_test.clj
willcohen/lucidity
3
(ns lucid.git-test (:require [clojure.test :refer :all] [lucid.git :refer :all])) (comment (first (git :log )) (git :status) (git :checkout :name "gh-pages") (git) [:add :apply :archive :blame :branch :checkout :cherry :clean :clone :commit :describe :diff :fetch :gc :init :log :ls :merge :name :notes :pull :push :rebase :reflog :reset :revert :rm :stash :status :submodule :tag] (git :init :directory "/tmp/gita-example") (git :cd "/tmp/gita-example") (do (spit "/tmp/gita-example/hello.txt" "hello") (spit "/tmp/gita-example/world.txt" "world") (spit "/tmp/gita-example/again.txt" "again")) (git :add :filepattern ["hello.txt"]) => {"hello.txt" #{:merged}} (git :commit :message "Added Hello.txt") => {:commit-time 1425683330, :name "9f1177ad928d7dea2afedd58b1fb7192b3523a6c", :author-ident {:email-address "z@caudate.me", :name "Chris Zheng", :time-zone-offset 330, :when #inst "2015-03-06T23:08:50.000-00:00"}, :full-message "Added Hello.txt"} (git :log) => [{:commit-time 1425683330, :name "9f1177ad928d7dea2afedd58b1fb7192b3523a6c", :author-ident {:email-address "z@caudate.me", :name "Chris Zheng", :time-zone-offset 330, :when #inst "2015-03-06T23:08:50.000-00:00"}, :full-message "Added Hello.txt"}] ;; Oops.. I made an error: (git :commit :message "Added `hello.txt`" :amend true) => {:commit-time 1425683376, :name "f21fe52cdc3511918b7d52e43f909dbe3c380159", :author-ident {:email-address "z@caudate.me", :name "Chris Zheng", :time-zone-offset 330, :when #inst "2015-03-06T23:08:50.000-00:00"}, :full-message "Added `hello.txt`"} (git :add :filepattern ["."]) => {"again.txt" #{:merged}, "hello.txt" #{:merged}, "world.txt" #{:merged}} (git :commit :message "Added `world.txt` and `again.txt`") => {:commit-time 1425683590, :name "2aad32d04470f118c1c891e163290433d70bbd21", :author-ident {:email-address "z@caudate.me", :name "Chris Zheng", :time-zone-offset 330, :when #inst "2015-03-06T23:13:10.000-00:00"}, :full-message "Added `world.txt` and `again.txt`"} (mapv :name (git :log)) => ["2aad32d04470f118c1c891e163290433d70bbd21" "f21fe52cdc3511918b7d52e43f909dbe3c380159"] (git :rm :filepattern ["hello.txt" "world.txt"]) => {"again.txt" #{:merged}} (git :commit :message "Leave `again.txt` as the only file") (mapv :name (git :log)) => ["9fb08f2b6d10ae1ec8cf15eb81ac56edd504160f" "2aad32d04470f118c1c891e163290433d70bbd21" "f21fe52cdc3511918b7d52e43f909dbe3c380159"] (git :status) => {:clean? true, :uncommitted-changes! false} (def status-obj (git :status :&)) (type status-obj) => org.eclipse.jgit.api.Status (require '[hara.reflect :as reflect]) (reflect/query-class status-obj [:name]) => ("clean" "diff" "getAdded" "getChanged" "getConflicting" "getConflictingStageState" "getIgnoredNotInIndex" "getMissing" "getModified" "getRemoved" "getUncommittedChanges" "getUntracked" "getUntrackedFolders" "hasUncommittedChanges" "isClean" "new") (git :diff) (type (git :init :directory "/tmp/git-example" :&)) org.eclipse.jgit.api.Git ) (comment (git) (git :cd) (git :pwd) (git :init :?) ;; => {:git-dir java.lang.String, :directory java.lang.String, :bare boolean} (git :add :?) (git :rm :?) (def res (git :stash :create)) (def author (.getAuthorIdent res)) (type res) () (util/object-methods res) (git :pwd) "/tmp/gita-example" "/Users/chris/Development/chit/gita" => "/tmp/gita-example/.git" (do (git :init :directory "/tmp/gita-example") (git :cd "/tmp/gita-example") (spit "/tmp/gita-example/hello.txt" "hello there") (git :add :filepattern ["."]) (git :commit :message (str (rand-int 1000) " - basic commit")) (spit "/tmp/gita-example/hello.txt" "hello world") (git :stash :create) (spit "/tmp/gita-example/hello.txt" "hello foo") (git :stash :create)) (git :stash :list) (count (git :log)) (git :cd "/tmp/gita-example1") (spit "/tmp/gita-example/hello.note" "hello there") (spit "/tmp/gita-example/hello.txt" "hello there") (git :status) (git :add :filepattern ["."]) (iterator-seq (.iterator (git :log))) (type (.getAuthor (.next (git :log))) (type (.getEncoding (.next (git :log)))) sun.nio.cs.UTF_8 (-> (git :log) (.iterator) (iterator-seq)) (.getAuthorIdent (.next (git :log)))) (git :add :?) (git :cd) (git :push :remote "git@github.com:zcaudate/gita.git") (def res (git :pull :&)) (interop/to-data res) (git :init :?) (git :status) (spit "/tmp/gita-example/hello.txt" "hello there") (git :add :filepattern ["."]) (git :commit :message "basic commit" :&) (git :rm :help) (git :status) (def res ) (util/object-methods res) (git "/tmp/gita/init" :status) (git "." :status) (git :branch :create))
42040
(ns lucid.git-test (:require [clojure.test :refer :all] [lucid.git :refer :all])) (comment (first (git :log )) (git :status) (git :checkout :name "gh-pages") (git) [:add :apply :archive :blame :branch :checkout :cherry :clean :clone :commit :describe :diff :fetch :gc :init :log :ls :merge :name :notes :pull :push :rebase :reflog :reset :revert :rm :stash :status :submodule :tag] (git :init :directory "/tmp/gita-example") (git :cd "/tmp/gita-example") (do (spit "/tmp/gita-example/hello.txt" "hello") (spit "/tmp/gita-example/world.txt" "world") (spit "/tmp/gita-example/again.txt" "again")) (git :add :filepattern ["hello.txt"]) => {"hello.txt" #{:merged}} (git :commit :message "Added Hello.txt") => {:commit-time 1425683330, :name "9f1177ad928d7dea2afedd58b1fb7192b3523a6c", :author-ident {:email-address "<EMAIL>", :name "<NAME>", :time-zone-offset 330, :when #inst "2015-03-06T23:08:50.000-00:00"}, :full-message "Added Hello.txt"} (git :log) => [{:commit-time 1425683330, :name "9f1177ad928d7dea2afedd58b1fb7192b3523a6c", :author-ident {:email-address "<EMAIL>", :name "<NAME>", :time-zone-offset 330, :when #inst "2015-03-06T23:08:50.000-00:00"}, :full-message "Added Hello.txt"}] ;; Oops.. I made an error: (git :commit :message "Added `hello.txt`" :amend true) => {:commit-time 1425683376, :name "f21fe52cdc3511918b7d52e43f909dbe3c380159", :author-ident {:email-address "<EMAIL>", :name "<NAME>", :time-zone-offset 330, :when #inst "2015-03-06T23:08:50.000-00:00"}, :full-message "Added `hello.txt`"} (git :add :filepattern ["."]) => {"again.txt" #{:merged}, "hello.txt" #{:merged}, "world.txt" #{:merged}} (git :commit :message "Added `world.txt` and `again.txt`") => {:commit-time 1425683590, :name "2aad32d04470f118c1c891e163290433d70bbd21", :author-ident {:email-address "<EMAIL>", :name "<NAME>", :time-zone-offset 330, :when #inst "2015-03-06T23:13:10.000-00:00"}, :full-message "Added `world.txt` and `again.txt`"} (mapv :name (git :log)) => ["2aad32d04470f118c1c891e163290433d70bbd21" "f21fe52cdc3511918b7d52e43f909dbe3c380159"] (git :rm :filepattern ["hello.txt" "world.txt"]) => {"again.txt" #{:merged}} (git :commit :message "Leave `again.txt` as the only file") (mapv :name (git :log)) => ["9fb08f2b6d10ae1ec8cf15eb81ac56edd504160f" "<KEY>" "f21fe52cdc3511918b7d52e43f909dbe3c380159"] (git :status) => {:clean? true, :uncommitted-changes! false} (def status-obj (git :status :&)) (type status-obj) => org.eclipse.jgit.api.Status (require '[hara.reflect :as reflect]) (reflect/query-class status-obj [:name]) => ("clean" "diff" "getAdded" "getChanged" "getConflicting" "getConflictingStageState" "getIgnoredNotInIndex" "getMissing" "getModified" "getRemoved" "getUncommittedChanges" "getUntracked" "getUntrackedFolders" "hasUncommittedChanges" "isClean" "new") (git :diff) (type (git :init :directory "/tmp/git-example" :&)) org.eclipse.jgit.api.Git ) (comment (git) (git :cd) (git :pwd) (git :init :?) ;; => {:git-dir java.lang.String, :directory java.lang.String, :bare boolean} (git :add :?) (git :rm :?) (def res (git :stash :create)) (def author (.getAuthorIdent res)) (type res) () (util/object-methods res) (git :pwd) "/tmp/gita-example" "/Users/chris/Development/chit/gita" => "/tmp/gita-example/.git" (do (git :init :directory "/tmp/gita-example") (git :cd "/tmp/gita-example") (spit "/tmp/gita-example/hello.txt" "hello there") (git :add :filepattern ["."]) (git :commit :message (str (rand-int 1000) " - basic commit")) (spit "/tmp/gita-example/hello.txt" "hello world") (git :stash :create) (spit "/tmp/gita-example/hello.txt" "hello foo") (git :stash :create)) (git :stash :list) (count (git :log)) (git :cd "/tmp/gita-example1") (spit "/tmp/gita-example/hello.note" "hello there") (spit "/tmp/gita-example/hello.txt" "hello there") (git :status) (git :add :filepattern ["."]) (iterator-seq (.iterator (git :log))) (type (.getAuthor (.next (git :log))) (type (.getEncoding (.next (git :log)))) sun.nio.cs.UTF_8 (-> (git :log) (.iterator) (iterator-seq)) (.getAuthorIdent (.next (git :log)))) (git :add :?) (git :cd) (git :push :remote "<EMAIL>:zcaudate/gita.git") (def res (git :pull :&)) (interop/to-data res) (git :init :?) (git :status) (spit "/tmp/gita-example/hello.txt" "hello there") (git :add :filepattern ["."]) (git :commit :message "basic commit" :&) (git :rm :help) (git :status) (def res ) (util/object-methods res) (git "/tmp/gita/init" :status) (git "." :status) (git :branch :create))
true
(ns lucid.git-test (:require [clojure.test :refer :all] [lucid.git :refer :all])) (comment (first (git :log )) (git :status) (git :checkout :name "gh-pages") (git) [:add :apply :archive :blame :branch :checkout :cherry :clean :clone :commit :describe :diff :fetch :gc :init :log :ls :merge :name :notes :pull :push :rebase :reflog :reset :revert :rm :stash :status :submodule :tag] (git :init :directory "/tmp/gita-example") (git :cd "/tmp/gita-example") (do (spit "/tmp/gita-example/hello.txt" "hello") (spit "/tmp/gita-example/world.txt" "world") (spit "/tmp/gita-example/again.txt" "again")) (git :add :filepattern ["hello.txt"]) => {"hello.txt" #{:merged}} (git :commit :message "Added Hello.txt") => {:commit-time 1425683330, :name "9f1177ad928d7dea2afedd58b1fb7192b3523a6c", :author-ident {:email-address "PI:EMAIL:<EMAIL>END_PI", :name "PI:NAME:<NAME>END_PI", :time-zone-offset 330, :when #inst "2015-03-06T23:08:50.000-00:00"}, :full-message "Added Hello.txt"} (git :log) => [{:commit-time 1425683330, :name "9f1177ad928d7dea2afedd58b1fb7192b3523a6c", :author-ident {:email-address "PI:EMAIL:<EMAIL>END_PI", :name "PI:NAME:<NAME>END_PI", :time-zone-offset 330, :when #inst "2015-03-06T23:08:50.000-00:00"}, :full-message "Added Hello.txt"}] ;; Oops.. I made an error: (git :commit :message "Added `hello.txt`" :amend true) => {:commit-time 1425683376, :name "f21fe52cdc3511918b7d52e43f909dbe3c380159", :author-ident {:email-address "PI:EMAIL:<EMAIL>END_PI", :name "PI:NAME:<NAME>END_PI", :time-zone-offset 330, :when #inst "2015-03-06T23:08:50.000-00:00"}, :full-message "Added `hello.txt`"} (git :add :filepattern ["."]) => {"again.txt" #{:merged}, "hello.txt" #{:merged}, "world.txt" #{:merged}} (git :commit :message "Added `world.txt` and `again.txt`") => {:commit-time 1425683590, :name "2aad32d04470f118c1c891e163290433d70bbd21", :author-ident {:email-address "PI:EMAIL:<EMAIL>END_PI", :name "PI:NAME:<NAME>END_PI", :time-zone-offset 330, :when #inst "2015-03-06T23:13:10.000-00:00"}, :full-message "Added `world.txt` and `again.txt`"} (mapv :name (git :log)) => ["2aad32d04470f118c1c891e163290433d70bbd21" "f21fe52cdc3511918b7d52e43f909dbe3c380159"] (git :rm :filepattern ["hello.txt" "world.txt"]) => {"again.txt" #{:merged}} (git :commit :message "Leave `again.txt` as the only file") (mapv :name (git :log)) => ["9fb08f2b6d10ae1ec8cf15eb81ac56edd504160f" "PI:KEY:<KEY>END_PI" "f21fe52cdc3511918b7d52e43f909dbe3c380159"] (git :status) => {:clean? true, :uncommitted-changes! false} (def status-obj (git :status :&)) (type status-obj) => org.eclipse.jgit.api.Status (require '[hara.reflect :as reflect]) (reflect/query-class status-obj [:name]) => ("clean" "diff" "getAdded" "getChanged" "getConflicting" "getConflictingStageState" "getIgnoredNotInIndex" "getMissing" "getModified" "getRemoved" "getUncommittedChanges" "getUntracked" "getUntrackedFolders" "hasUncommittedChanges" "isClean" "new") (git :diff) (type (git :init :directory "/tmp/git-example" :&)) org.eclipse.jgit.api.Git ) (comment (git) (git :cd) (git :pwd) (git :init :?) ;; => {:git-dir java.lang.String, :directory java.lang.String, :bare boolean} (git :add :?) (git :rm :?) (def res (git :stash :create)) (def author (.getAuthorIdent res)) (type res) () (util/object-methods res) (git :pwd) "/tmp/gita-example" "/Users/chris/Development/chit/gita" => "/tmp/gita-example/.git" (do (git :init :directory "/tmp/gita-example") (git :cd "/tmp/gita-example") (spit "/tmp/gita-example/hello.txt" "hello there") (git :add :filepattern ["."]) (git :commit :message (str (rand-int 1000) " - basic commit")) (spit "/tmp/gita-example/hello.txt" "hello world") (git :stash :create) (spit "/tmp/gita-example/hello.txt" "hello foo") (git :stash :create)) (git :stash :list) (count (git :log)) (git :cd "/tmp/gita-example1") (spit "/tmp/gita-example/hello.note" "hello there") (spit "/tmp/gita-example/hello.txt" "hello there") (git :status) (git :add :filepattern ["."]) (iterator-seq (.iterator (git :log))) (type (.getAuthor (.next (git :log))) (type (.getEncoding (.next (git :log)))) sun.nio.cs.UTF_8 (-> (git :log) (.iterator) (iterator-seq)) (.getAuthorIdent (.next (git :log)))) (git :add :?) (git :cd) (git :push :remote "PI:EMAIL:<EMAIL>END_PI:zcaudate/gita.git") (def res (git :pull :&)) (interop/to-data res) (git :init :?) (git :status) (spit "/tmp/gita-example/hello.txt" "hello there") (git :add :filepattern ["."]) (git :commit :message "basic commit" :&) (git :rm :help) (git :status) (def res ) (util/object-methods res) (git "/tmp/gita/init" :status) (git "." :status) (git :branch :create))
[ { "context": "; :db/id idkeyword\n;; :user/name \"Sam\"\n;; :user/authorization-role roleIDs\n;; ", "end": 1115, "score": 0.430899053812027, "start": 1112, "tag": "NAME", "value": "Sam" }, { "context": "uthorization-role roleIDs\n;; :user/email \"sam@example.net\" }))\n;;\n;; (defn gen-account [idkeyword userI", "end": 1200, "score": 0.9999288320541382, "start": 1185, "tag": "EMAIL", "value": "sam@example.net" }, { "context": "d[:db.part/user -1]\n;; :person/name \"Bob\"}]\n;; )\n;; \n;;\n;; (def seed-data ", "end": 1690, "score": 0.9989287257194519, "start": 1687, "tag": "NAME", "value": "Bob" }, { "context": "d #db/id[:db.part/user -1] ;; add a spouse attr to Bob from base users\n;; :person/spouse #d", "end": 1879, "score": 0.8503116965293884, "start": 1876, "tag": "NAME", "value": "Bob" }, { "context": " {:db/id #db/id[:db.part/user -2] ;; Add Alice with cross-ref to Bob\n;; :person/nam", "end": 2013, "score": 0.8857359886169434, "start": 2008, "tag": "NAME", "value": "Alice" }, { "context": "d[:db.part/user -2] ;; Add Alice with cross-ref to Bob\n;; :person/name \"Alice\"\n;; ", "end": 2035, "score": 0.9366775751113892, "start": 2032, "tag": "NAME", "value": "Bob" }, { "context": "th cross-ref to Bob\n;; :person/name \"Alice\"\n;; :person/spouse #db/id[:db.part/u", "end": 2071, "score": 0.9994304776191711, "start": 2066, "tag": "NAME", "value": "Alice" } ]
specs/seeddata/sample.clj
fulcro-legacy/fulcro-datomic
6
;; Sample file for generating seed data. You can use full-blown clojure in here. ;; In general, test will depend on this data, so once a seed file is committed, it generally should ;; not be modified; however, you can base a new seed file on an existing one simply by pulling it ;; into your new one. ;; Set your namespace to match your file. (ns seeddata.sample ;; optionally bring in other things, including other seed data: ;; (:require seeddata.base-user) ) ;; The seed-data must be a single transaction ;; (which is a list of maps or a list of lists, as described in the ;; datomic docs). This makes it easier to compose seed data and refer to prior ;; temporary IDs. ;; ;; Desired API: ;; ;; (gen-user :id/USER1) ;; ;; (defn auth-role [idkeyword entitlementIDs] ;; (entity/gen { ;; :db/id idkeyword ;; :authorization-role/name "NWMgr" ;; :authorization-role/entitlement (vec entitlementIDs) ;; })) ;; ;; (defn gen-user [idkeyword roleIDs] ;; (assert (vec? roleIDs)) ;; (entity/gen { ;; :db/id idkeyword ;; :user/name "Sam" ;; :user/authorization-role roleIDs ;; :user/email "sam@example.net" })) ;; ;; (defn gen-account [idkeyword userIDs] ;; (assert (vec? userIDs)) ;; (entity/gen { ;; :db/id idkeyword ;; :account/account-id "Account 1" ;; :account/account-name "Account 1" ;; :account/user (vec userIDs) ;; })) ;; ;; TODO: Continue defining API here... ;; ;; ;; ;; ;; ;; ;; ;;........... ;; (ns seeddata.base-user) ;; (def seed-data ;; [{:db/id #db/id[:db.part/user -1] ;; :person/name "Bob"}] ;; ) ;; ;; ;; (def seed-data ;; (concat ;; seeddata.base-user/seed-data ;; [{:db/id #db/id[:db.part/user -1] ;; add a spouse attr to Bob from base users ;; :person/spouse #db/id[:db.part/user -2]} ;; {:db/id #db/id[:db.part/user -2] ;; Add Alice with cross-ref to Bob ;; :person/name "Alice" ;; :person/spouse #db/id[:db.part/user -1]}] ;; ) ;; ) ;; ;; Now seeddata.sample/seed-data includes the base user data as well as some additional bits.
88179
;; Sample file for generating seed data. You can use full-blown clojure in here. ;; In general, test will depend on this data, so once a seed file is committed, it generally should ;; not be modified; however, you can base a new seed file on an existing one simply by pulling it ;; into your new one. ;; Set your namespace to match your file. (ns seeddata.sample ;; optionally bring in other things, including other seed data: ;; (:require seeddata.base-user) ) ;; The seed-data must be a single transaction ;; (which is a list of maps or a list of lists, as described in the ;; datomic docs). This makes it easier to compose seed data and refer to prior ;; temporary IDs. ;; ;; Desired API: ;; ;; (gen-user :id/USER1) ;; ;; (defn auth-role [idkeyword entitlementIDs] ;; (entity/gen { ;; :db/id idkeyword ;; :authorization-role/name "NWMgr" ;; :authorization-role/entitlement (vec entitlementIDs) ;; })) ;; ;; (defn gen-user [idkeyword roleIDs] ;; (assert (vec? roleIDs)) ;; (entity/gen { ;; :db/id idkeyword ;; :user/name "<NAME>" ;; :user/authorization-role roleIDs ;; :user/email "<EMAIL>" })) ;; ;; (defn gen-account [idkeyword userIDs] ;; (assert (vec? userIDs)) ;; (entity/gen { ;; :db/id idkeyword ;; :account/account-id "Account 1" ;; :account/account-name "Account 1" ;; :account/user (vec userIDs) ;; })) ;; ;; TODO: Continue defining API here... ;; ;; ;; ;; ;; ;; ;; ;;........... ;; (ns seeddata.base-user) ;; (def seed-data ;; [{:db/id #db/id[:db.part/user -1] ;; :person/name "<NAME>"}] ;; ) ;; ;; ;; (def seed-data ;; (concat ;; seeddata.base-user/seed-data ;; [{:db/id #db/id[:db.part/user -1] ;; add a spouse attr to <NAME> from base users ;; :person/spouse #db/id[:db.part/user -2]} ;; {:db/id #db/id[:db.part/user -2] ;; Add <NAME> with cross-ref to <NAME> ;; :person/name "<NAME>" ;; :person/spouse #db/id[:db.part/user -1]}] ;; ) ;; ) ;; ;; Now seeddata.sample/seed-data includes the base user data as well as some additional bits.
true
;; Sample file for generating seed data. You can use full-blown clojure in here. ;; In general, test will depend on this data, so once a seed file is committed, it generally should ;; not be modified; however, you can base a new seed file on an existing one simply by pulling it ;; into your new one. ;; Set your namespace to match your file. (ns seeddata.sample ;; optionally bring in other things, including other seed data: ;; (:require seeddata.base-user) ) ;; The seed-data must be a single transaction ;; (which is a list of maps or a list of lists, as described in the ;; datomic docs). This makes it easier to compose seed data and refer to prior ;; temporary IDs. ;; ;; Desired API: ;; ;; (gen-user :id/USER1) ;; ;; (defn auth-role [idkeyword entitlementIDs] ;; (entity/gen { ;; :db/id idkeyword ;; :authorization-role/name "NWMgr" ;; :authorization-role/entitlement (vec entitlementIDs) ;; })) ;; ;; (defn gen-user [idkeyword roleIDs] ;; (assert (vec? roleIDs)) ;; (entity/gen { ;; :db/id idkeyword ;; :user/name "PI:NAME:<NAME>END_PI" ;; :user/authorization-role roleIDs ;; :user/email "PI:EMAIL:<EMAIL>END_PI" })) ;; ;; (defn gen-account [idkeyword userIDs] ;; (assert (vec? userIDs)) ;; (entity/gen { ;; :db/id idkeyword ;; :account/account-id "Account 1" ;; :account/account-name "Account 1" ;; :account/user (vec userIDs) ;; })) ;; ;; TODO: Continue defining API here... ;; ;; ;; ;; ;; ;; ;; ;;........... ;; (ns seeddata.base-user) ;; (def seed-data ;; [{:db/id #db/id[:db.part/user -1] ;; :person/name "PI:NAME:<NAME>END_PI"}] ;; ) ;; ;; ;; (def seed-data ;; (concat ;; seeddata.base-user/seed-data ;; [{:db/id #db/id[:db.part/user -1] ;; add a spouse attr to PI:NAME:<NAME>END_PI from base users ;; :person/spouse #db/id[:db.part/user -2]} ;; {:db/id #db/id[:db.part/user -2] ;; Add PI:NAME:<NAME>END_PI with cross-ref to PI:NAME:<NAME>END_PI ;; :person/name "PI:NAME:<NAME>END_PI" ;; :person/spouse #db/id[:db.part/user -1]}] ;; ) ;; ) ;; ;; Now seeddata.sample/seed-data includes the base user data as well as some additional bits.
[ { "context": "ctus-cactus-garden-cactus-plant-291544/\n; Photo by Abhinav Goswami from Pexels\n; Cactus\n\n; https://www.pexels.com/ph", "end": 109, "score": 0.9998930096626282, "start": 94, "tag": "NAME", "value": "Abhinav Goswami" }, { "context": "; Photo by Kaboompics .com from Pexels\n\n; Photo by Maureen Bekker from Pexels\n; Echeveria 'Fleur Blanc'\n; This plan", "end": 251, "score": 0.999907910823822, "start": 237, "tag": "NAME", "value": "Maureen Bekker" }, { "context": " Photo by Maureen Bekker from Pexels\n; Echeveria 'Fleur Blanc'\n; This plant grows as a rosette of succulent lob", "end": 288, "score": 0.9998482465744019, "start": 277, "tag": "NAME", "value": "Fleur Blanc" }, { "context": "w.pexels.com/photo/pink-flower-66181/\n; Photo by Wolfgang from Pexels\n\n; https://www.pexels.com/photo/green", "end": 495, "score": 0.7716038823127747, "start": 488, "tag": "NAME", "value": "olfgang" }, { "context": "n-leaf-plant-on-wooden-surface-3205147/\n; Photo by Nika Akin from Pexels\n\n; https://www.pexels.com/photo/shall", "end": 604, "score": 0.9998875856399536, "start": 595, "tag": "NAME", "value": "Nika Akin" }, { "context": "ocus-photo-of-aloe-vera-plants-3234638/\n; Photo by Himesh Mehta from Pexels\n; Spotted Aloe Vera\n\n; https://www.pe", "end": 721, "score": 0.999896228313446, "start": 709, "tag": "NAME", "value": "Himesh Mehta" }, { "context": "us-white-and-green-moth-orchids-926572/\n; Photo by Artem Beliaikin from Pexels\n\n(ns garden-sprites.atoms.plants\n (:", "end": 865, "score": 0.9998988509178162, "start": 850, "tag": "NAME", "value": "Artem Beliaikin" }, { "context": " :price 3.90\n :description \"\"}\n {:name \"Echeveria 'Fleur Blanc'\"\n :plant-type \"succulent\"", "end": 1339, "score": 0.7207586765289307, "start": 1335, "tag": "NAME", "value": "Eche" }, { "context": ".90\n :description \"\"}\n {:name \"Echeveria 'Fleur Blanc'\"\n :plant-type \"succulent\"\n :image-path", "end": 1357, "score": 0.9102213978767395, "start": 1346, "tag": "NAME", "value": "Fleur Blanc" }, { "context": " are easy to care for and maintain.\"}\n {:name \"Pink Orchid\"\n :plant-type \"epiphyte\"\n :image-paths ", "end": 1647, "score": 0.9065000414848328, "start": 1636, "tag": "NAME", "value": "Pink Orchid" }, { "context": " :price 25.75\n :description \"\"}\n {:name \"Rosemary\"\n :plant-type \"herb\"\n :image-paths [\n ", "end": 1796, "score": 0.9681380391120911, "start": 1788, "tag": "NAME", "value": "Rosemary" }, { "context": " :price 3.50\n :description \"\"}\n {:name \"Spotted Aloe Vera\"\n :plant-type \"succulent\"\n ", "end": 1933, "score": 0.7166337966918945, "start": 1929, "tag": "NAME", "value": "Spot" }, { "context": " 3.50\n :description \"\"}\n {:name \"Spotted Aloe Vera\"\n :plant-type \"succulent\"\n :image", "end": 1940, "score": 0.6142246127128601, "start": 1938, "tag": "NAME", "value": "lo" }, { "context": " Vera Plant.\"}\n {:name \"White and Green Moth Orchid\"\n :plant-type \"epiphyte\"\n :image-paths ", "end": 2172, "score": 0.6324690580368042, "start": 2168, "tag": "NAME", "value": "chid" } ]
src/garden_sprites/atoms/plants.cljs
mes32/garden-sprites
1
; https://www.pexels.com/photo/botanical-cactus-cactus-garden-cactus-plant-291544/ ; Photo by Abhinav Goswami from Pexels ; Cactus ; https://www.pexels.com/photo/basil-in-the-cup-5818/ ; Photo by Kaboompics .com from Pexels ; Photo by Maureen Bekker from Pexels ; Echeveria 'Fleur Blanc' ; This plant grows as a rosette of succulent lobes. As native plants growing in semi-arid areas, they are robust and easy to maintain. ; https://www.pexels.com/photo/pink-flower-66181/ ; Photo by Wolfgang from Pexels ; https://www.pexels.com/photo/green-leaf-plant-on-wooden-surface-3205147/ ; Photo by Nika Akin from Pexels ; https://www.pexels.com/photo/shallow-focus-photo-of-aloe-vera-plants-3234638/ ; Photo by Himesh Mehta from Pexels ; Spotted Aloe Vera ; https://www.pexels.com/photo/selective-focus-white-and-green-moth-orchids-926572/ ; Photo by Artem Beliaikin from Pexels (ns garden-sprites.atoms.plants (:require [reagent.core :as r])) (defonce all-plants [ {:name "Cactus" :plant-type "succulent" :image-paths [ "./images/cactus.jpg"] :price 10.20 :description "This classic succulent requires minimal water. Watch out for the spines."} {:name "Basil" :plant-type "herb" :image-paths [ "./images/basil.jpg"] :price 3.90 :description ""} {:name "Echeveria 'Fleur Blanc'" :plant-type "succulent" :image-paths [ "./images/green-echeveria.jpg"] :price 20.00 :description "This plant grows as a rosette of succulent lobes. These plants are native semi-arid biomes. They are easy to care for and maintain."} {:name "Pink Orchid" :plant-type "epiphyte" :image-paths [ "./images/pink-orchid.jpg"] :price 25.75 :description ""} {:name "Rosemary" :plant-type "herb" :image-paths [ "./images/rosemary.jpg"] :price 3.50 :description ""} {:name "Spotted Aloe Vera" :plant-type "succulent" :image-paths [ "./images/spotted-aloe-vera.jpg"] :price 15.50 :description "This is the spotted variety of the Aloe Vera Plant."} {:name "White and Green Moth Orchid" :plant-type "epiphyte" :image-paths [ "./images/white-and-green-moth-orchid.jpg"] :price 20.50 :description ""}]) (defonce plants (r/atom all-plants)) (defn get-plants-type! [plant-type] (if (nil? plant-type) (reset! plants all-plants) (reset! plants (filter #(= (:plant-type %) plant-type) all-plants))))
41344
; https://www.pexels.com/photo/botanical-cactus-cactus-garden-cactus-plant-291544/ ; Photo by <NAME> from Pexels ; Cactus ; https://www.pexels.com/photo/basil-in-the-cup-5818/ ; Photo by Kaboompics .com from Pexels ; Photo by <NAME> from Pexels ; Echeveria '<NAME>' ; This plant grows as a rosette of succulent lobes. As native plants growing in semi-arid areas, they are robust and easy to maintain. ; https://www.pexels.com/photo/pink-flower-66181/ ; Photo by W<NAME> from Pexels ; https://www.pexels.com/photo/green-leaf-plant-on-wooden-surface-3205147/ ; Photo by <NAME> from Pexels ; https://www.pexels.com/photo/shallow-focus-photo-of-aloe-vera-plants-3234638/ ; Photo by <NAME> from Pexels ; Spotted Aloe Vera ; https://www.pexels.com/photo/selective-focus-white-and-green-moth-orchids-926572/ ; Photo by <NAME> from Pexels (ns garden-sprites.atoms.plants (:require [reagent.core :as r])) (defonce all-plants [ {:name "Cactus" :plant-type "succulent" :image-paths [ "./images/cactus.jpg"] :price 10.20 :description "This classic succulent requires minimal water. Watch out for the spines."} {:name "Basil" :plant-type "herb" :image-paths [ "./images/basil.jpg"] :price 3.90 :description ""} {:name "<NAME>veria '<NAME>'" :plant-type "succulent" :image-paths [ "./images/green-echeveria.jpg"] :price 20.00 :description "This plant grows as a rosette of succulent lobes. These plants are native semi-arid biomes. They are easy to care for and maintain."} {:name "<NAME>" :plant-type "epiphyte" :image-paths [ "./images/pink-orchid.jpg"] :price 25.75 :description ""} {:name "<NAME>" :plant-type "herb" :image-paths [ "./images/rosemary.jpg"] :price 3.50 :description ""} {:name "<NAME>ted A<NAME>e Vera" :plant-type "succulent" :image-paths [ "./images/spotted-aloe-vera.jpg"] :price 15.50 :description "This is the spotted variety of the Aloe Vera Plant."} {:name "White and Green Moth Or<NAME>" :plant-type "epiphyte" :image-paths [ "./images/white-and-green-moth-orchid.jpg"] :price 20.50 :description ""}]) (defonce plants (r/atom all-plants)) (defn get-plants-type! [plant-type] (if (nil? plant-type) (reset! plants all-plants) (reset! plants (filter #(= (:plant-type %) plant-type) all-plants))))
true
; https://www.pexels.com/photo/botanical-cactus-cactus-garden-cactus-plant-291544/ ; Photo by PI:NAME:<NAME>END_PI from Pexels ; Cactus ; https://www.pexels.com/photo/basil-in-the-cup-5818/ ; Photo by Kaboompics .com from Pexels ; Photo by PI:NAME:<NAME>END_PI from Pexels ; Echeveria 'PI:NAME:<NAME>END_PI' ; This plant grows as a rosette of succulent lobes. As native plants growing in semi-arid areas, they are robust and easy to maintain. ; https://www.pexels.com/photo/pink-flower-66181/ ; Photo by WPI:NAME:<NAME>END_PI from Pexels ; https://www.pexels.com/photo/green-leaf-plant-on-wooden-surface-3205147/ ; Photo by PI:NAME:<NAME>END_PI from Pexels ; https://www.pexels.com/photo/shallow-focus-photo-of-aloe-vera-plants-3234638/ ; Photo by PI:NAME:<NAME>END_PI from Pexels ; Spotted Aloe Vera ; https://www.pexels.com/photo/selective-focus-white-and-green-moth-orchids-926572/ ; Photo by PI:NAME:<NAME>END_PI from Pexels (ns garden-sprites.atoms.plants (:require [reagent.core :as r])) (defonce all-plants [ {:name "Cactus" :plant-type "succulent" :image-paths [ "./images/cactus.jpg"] :price 10.20 :description "This classic succulent requires minimal water. Watch out for the spines."} {:name "Basil" :plant-type "herb" :image-paths [ "./images/basil.jpg"] :price 3.90 :description ""} {:name "PI:NAME:<NAME>END_PIveria 'PI:NAME:<NAME>END_PI'" :plant-type "succulent" :image-paths [ "./images/green-echeveria.jpg"] :price 20.00 :description "This plant grows as a rosette of succulent lobes. These plants are native semi-arid biomes. They are easy to care for and maintain."} {:name "PI:NAME:<NAME>END_PI" :plant-type "epiphyte" :image-paths [ "./images/pink-orchid.jpg"] :price 25.75 :description ""} {:name "PI:NAME:<NAME>END_PI" :plant-type "herb" :image-paths [ "./images/rosemary.jpg"] :price 3.50 :description ""} {:name "PI:NAME:<NAME>END_PIted API:NAME:<NAME>END_PIe Vera" :plant-type "succulent" :image-paths [ "./images/spotted-aloe-vera.jpg"] :price 15.50 :description "This is the spotted variety of the Aloe Vera Plant."} {:name "White and Green Moth OrPI:NAME:<NAME>END_PI" :plant-type "epiphyte" :image-paths [ "./images/white-and-green-moth-orchid.jpg"] :price 20.50 :description ""}]) (defonce plants (r/atom all-plants)) (defn get-plants-type! [plant-type] (if (nil? plant-type) (reset! plants all-plants) (reset! plants (filter #(= (:plant-type %) plant-type) all-plants))))
[ { "context": "o-blocks and threads.\n;;;\n;;; Inspired by: http://martintrojer.github.io/clojure/2013/07/07/coreasync-and-blocki", "end": 96, "score": 0.7726662755012512, "start": 84, "tag": "USERNAME", "value": "martintrojer" }, { "context": "ojure/2013/07/07/coreasync-and-blocking-io\n;;;\n;;; Eli Bendersky [http://eli.thegreenplace.net]\n;;; This code is i", "end": 173, "score": 0.9995573163032532, "start": 160, "tag": "NAME", "value": "Eli Bendersky" }, { "context": ".client]))\n\n(def url-template \"https://github.com/eliben/pycparser/pull/%d\")\n\n(defn blocking-get-page [i]\n", "end": 404, "score": 0.9806122779846191, "start": 398, "tag": "USERNAME", "value": "eliben" } ]
2017/clojure-blocking-async/src/clojure_blocking_async/http_client.clj
mikiec84/code-for-blog
1,199
;;; Concurrent HTTP client using go-blocks and threads. ;;; ;;; Inspired by: http://martintrojer.github.io/clojure/2013/07/07/coreasync-and-blocking-io ;;; ;;; Eli Bendersky [http://eli.thegreenplace.net] ;;; This code is in the public domain. (ns clojure-blocking-async.http-client (:require [clojure.core.async :as async]) (:require [clj-http.client])) (def url-template "https://github.com/eliben/pycparser/pull/%d") (defn blocking-get-page [i] (clj-http.client/get (format url-template i))) (defn verify [] (let [r (blocking-get-page 22)] (time (clojure.string/includes? (:body r) "integer typedefs")))) (defn get-multiple [generator-fn start n] (let [c (async/chan)] (generator-fn c start n) (loop [i 0 res []] (if (= i n) res (recur (inc i) (conj res (async/<!! c))))))) (defn go-blocking-generator [c start n] (doseq [i (range start (+ start n))] (async/go (async/>! c (blocking-get-page i))))) (defn thread-blocking-generator [c start n] (doseq [i (range start (+ start n))] (async/thread (async/>!! c (blocking-get-page i))))) (def start 10) (def num-results 20) ;(time (count (get-multiple go-blocking-generator 10 num-results))) (time (count (get-multiple thread-blocking-generator start num-results))) (prn (verify))
57410
;;; Concurrent HTTP client using go-blocks and threads. ;;; ;;; Inspired by: http://martintrojer.github.io/clojure/2013/07/07/coreasync-and-blocking-io ;;; ;;; <NAME> [http://eli.thegreenplace.net] ;;; This code is in the public domain. (ns clojure-blocking-async.http-client (:require [clojure.core.async :as async]) (:require [clj-http.client])) (def url-template "https://github.com/eliben/pycparser/pull/%d") (defn blocking-get-page [i] (clj-http.client/get (format url-template i))) (defn verify [] (let [r (blocking-get-page 22)] (time (clojure.string/includes? (:body r) "integer typedefs")))) (defn get-multiple [generator-fn start n] (let [c (async/chan)] (generator-fn c start n) (loop [i 0 res []] (if (= i n) res (recur (inc i) (conj res (async/<!! c))))))) (defn go-blocking-generator [c start n] (doseq [i (range start (+ start n))] (async/go (async/>! c (blocking-get-page i))))) (defn thread-blocking-generator [c start n] (doseq [i (range start (+ start n))] (async/thread (async/>!! c (blocking-get-page i))))) (def start 10) (def num-results 20) ;(time (count (get-multiple go-blocking-generator 10 num-results))) (time (count (get-multiple thread-blocking-generator start num-results))) (prn (verify))
true
;;; Concurrent HTTP client using go-blocks and threads. ;;; ;;; Inspired by: http://martintrojer.github.io/clojure/2013/07/07/coreasync-and-blocking-io ;;; ;;; PI:NAME:<NAME>END_PI [http://eli.thegreenplace.net] ;;; This code is in the public domain. (ns clojure-blocking-async.http-client (:require [clojure.core.async :as async]) (:require [clj-http.client])) (def url-template "https://github.com/eliben/pycparser/pull/%d") (defn blocking-get-page [i] (clj-http.client/get (format url-template i))) (defn verify [] (let [r (blocking-get-page 22)] (time (clojure.string/includes? (:body r) "integer typedefs")))) (defn get-multiple [generator-fn start n] (let [c (async/chan)] (generator-fn c start n) (loop [i 0 res []] (if (= i n) res (recur (inc i) (conj res (async/<!! c))))))) (defn go-blocking-generator [c start n] (doseq [i (range start (+ start n))] (async/go (async/>! c (blocking-get-page i))))) (defn thread-blocking-generator [c start n] (doseq [i (range start (+ start n))] (async/thread (async/>!! c (blocking-get-page i))))) (def start 10) (def num-results 20) ;(time (count (get-multiple go-blocking-generator 10 num-results))) (time (count (get-multiple thread-blocking-generator start num-results))) (prn (verify))
[ { "context": " nil\n\n(def customer-ref\n (ref\n {:makoto {:name \"Makoto Hashimoto\" :country \"Japan\"}\n :nico {:name \"Nicolas Modrz", "end": 1958, "score": 0.9998666644096375, "start": 1942, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "oto Hashimoto\" :country \"Japan\"}\n :nico {:name \"Nicolas Modrzyk\" :country \"France\"}}))\n;;=> #'liberator-example.e", "end": 2010, "score": 0.9998645782470703, "start": 1995, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "v20150310)\"},\n;;=> :body \"{\\\"makoto\\\":{\\\"name\\\":\\\"Makoto Hashimoto\\\",\\\"country\\\":\\\"Japan\\\"},\n;;=> \\\"nico\\\":{\\\"name\\\"", "end": 4175, "score": 0.9998720288276672, "start": 4159, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "\\\"country\\\":\\\"Japan\\\"},\n;;=> \\\"nico\\\":{\\\"name\\\":\\\"Nicolas Modrzyk\\\",\\\"country\\\":\\\"France\\\"}}\",\n;;=> :request-time 6", "end": 4243, "score": 0.9998573660850525, "start": 4228, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "tomer\"\n {:body (generate-string {:id \"rh\" :name \"Rich Hickey\" :country \"United States\"})})", "end": 4473, "score": 0.6021008491516113, "start": 4471, "tag": "USERNAME", "value": "rh" }, { "context": " {:body (generate-string {:id \"rh\" :name \"Rich Hickey\" :country \"United States\"})})\n;;=> {:status 201, ", "end": 4493, "score": 0.9998877048492432, "start": 4482, "tag": "NAME", "value": "Rich Hickey" }, { "context": "er/rh\" ) :body (parse-string true))\n;;=> {:name \"Rich Hickey\", :country \"United States\"}\n\n(client/put \"http://", "end": 4935, "score": 0.9998695254325867, "start": 4924, "tag": "NAME", "value": "Rich Hickey" }, { "context": "/rh\"\n {:body (generate-string {:name \"Rich Hickey\" :country \"USA\"})})\n;;=> {:status 204, :headers {", "end": 5069, "score": 0.99985671043396, "start": 5058, "tag": "NAME", "value": "Rich Hickey" }, { "context": "\", \"Connection\" \"close\",\n;;=> \"Server\" \"Jetty(9.2.10.v20150310)\"}, :body nil, :request-time 9,\n;;=> :", "end": 5264, "score": 0.6290498375892639, "start": 5263, "tag": "IP_ADDRESS", "value": "1" }, { "context": "mer/rh\") :body (parse-string true))\n;;=> {:name \"Rich Hickey\", :country \"USA\"}\n\n(client/delete \"http://localho", "end": 5504, "score": 0.999853789806366, "start": 5493, "tag": "NAME", "value": "Rich Hickey" }, { "context": "cept\", \"Connection\" \"close\",\n;;=> \"Server\" \"Jetty(9.2.10.v20150310)\"}, :body nil, :request-time 8,\n;;=> :t", "end": 5752, "score": 0.7811182141304016, "start": 5746, "tag": "IP_ADDRESS", "value": "9.2.10" } ]
Chapter 08 Code/liberator-example/src/liberator_example/example.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(ns liberator-example.example (:require [liberator.core :refer [resource defresource]] [ring.adapter.jetty :refer [run-jetty]] [ring.middleware.params :refer [wrap-params]] [compojure.core :refer [defroutes ANY GET PUT POST DELETE OPTIONS]] [clj-http.client :as client] [cheshire.core :refer [parse-string generate-string]])) (defroutes app (ANY "/hello" [] (resource :available-media-types ["text/html"] :handle-ok "<html><h1>Hello Clojure !</h1></html>")) (route/not-found "Not Found !")) ;;=> #'liberator-example.example/app (def handler (-> app wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (.stop server) ;;=> nil (defresource hello :available-media-types ["text/html"] :handle-ok "<html><h1>Hello Clojure from defresource !</h1></html>") ;;=> #'liberator-example.example/hello (defroutes app (ANY "/hello" [] hello) (route/not-found "Not Found !")) ;;=> #'liberator-example.example/app (def handler (-> app wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (.stop server) ;;=> nil (defresource parameterized-hello [x] :available-media-types ["text/html"] :handle-ok (format "<html><h1>Hello Clojure from %s !</h1></html>" x) ) ;;=> #'liberator-example.example/parameterized-hello (defroutes parameterized-hello-app (ANY "/hello/:x" [x] (parameterized-hello x)) (route/not-found "Not Found !")) ;;=> #'liberator-example.example/parameterized-hello-app (def handler (-> parameterized-hello-app wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (.stop server) ;;=> nil (def customer-ref (ref {:makoto {:name "Makoto Hashimoto" :country "Japan"} :nico {:name "Nicolas Modrzyk" :country "France"}})) ;;=> #'liberator-example.example/customer-ref (defresource customer-list :allowed-methods [:get :post] :available-media-types ["application/json"] :exists? (fn [_] (let [result @customer-ref] (if-not (nil? result) {::entry result}))) :post! (fn [ctx] (let [body (parse-string (slurp (get-in ctx [:request :body])) true)] (dosync (alter customer-ref assoc (keyword (:id body)) (dissoc body :id))))) :handle-ok ::entry :handle-not-found {:error "id is not found"}) ;;=> #'liberator-example.example/customer-list (defresource customer-entity [id] :allowed-methods [:get :put :delete] :available-media-types ["application/json"] :exists? (fn [_] (let [result ( get @customer-ref (keyword id))] (info "get ======>" (keyword id)) (if-not (nil? result) {::entry result}))) :put! (fn [ctx] (let [body (parse-string (slurp (get-in ctx [:request :body])) true)] (dosync (alter customer-ref assoc (keyword id) (dissoc body :id))))) :delete! (fn [_] (dosync (alter customer-ref dissoc (keyword id)))) :existed? (fn [_] (nil? (get @customer-ref id ::sentinel))) :new? (fn [_] (nil? (get @customer-ref id ::sentinel))) :handle-ok ::entry :handle-not-found {:error "id is not found"})) ;;=> #'liberator-example.example/customer-entity (defroutes customer (ANY "/customer" [] customer-list) (ANY "/customer/:id" [id] (customer-entity id))) ;;=> #'liberator-example.example/app (def handler (-> customer wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (client/get "http://localhost:3000/customer") ;;=> {:status 200, :headers {"Date" "Sun, 26 Jun 2016 20:14:34 GMT", ;;=> "Content-Type" "application/json;charset=UTF-8", "Vary" "Accept", ;;=> "Connection" "close", "Server" "Jetty(9.2.10.v20150310)"}, ;;=> :body "{\"makoto\":{\"name\":\"Makoto Hashimoto\",\"country\":\"Japan\"}, ;;=> \"nico\":{\"name\":\"Nicolas Modrzyk\",\"country\":\"France\"}}", ;;=> :request-time 6, :trace-redirects ["http://localhost:3000/customer"], ;;=> :orig-content-encoding nil} (client/post "http://localhost:3000/customer" {:body (generate-string {:id "rh" :name "Rich Hickey" :country "United States"})}) ;;=> {:status 201, :headers {"Date" "Sun, 26 Jun 2016 14:33:28 GMT", ;;=> "Content-Type" "application/json", "Vary" "Accept", "Connection" "close", ;;=> "Server" "Jetty(9.2.10.v20150310)"}, :body "", :request-time 8, ;;=> :trace-redirects ["http://localhost:3000/customer"], :orig-content-encoding nil} (-> (client/get "http://localhost:3000/customer/rh" ) :body (parse-string true)) ;;=> {:name "Rich Hickey", :country "United States"} (client/put "http://localhost:3000/customer/rh" {:body (generate-string {:name "Rich Hickey" :country "USA"})}) ;;=> {:status 204, :headers {"Date" "Sun, 26 Jun 2016 22:04:35 GMT", ;;=> "Content-Type" "application/json", "Vary" "Accept", "Connection" "close", ;;=> "Server" "Jetty(9.2.10.v20150310)"}, :body nil, :request-time 9, ;;=> :trace-redirects ["http://localhost:3000/customer/rh"], :orig-content-encoding nil} (-> (client/get "http://localhost:3000/customer/rh") :body (parse-string true)) ;;=> {:name "Rich Hickey", :country "USA"} (client/delete "http://localhost:3000/customer/rh") ;;=> {:status 204, :headers {"Date" "Sun, 26 Jun 2016 14:38:58 GMT", ;;=> "Content-Type" "application/json", "Vary" "Accept", "Connection" "close", ;;=> "Server" "Jetty(9.2.10.v20150310)"}, :body nil, :request-time 8, ;;=> :trace-redirects ["http://localhost:3000/customer/rh"], :orig-content-encoding nil} (.stop server) ;;=> nil (def handler (-> customer wrap-params (wrap-trace :header :ui))) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (client/get "http://localhost:3000/customer")
20274
(ns liberator-example.example (:require [liberator.core :refer [resource defresource]] [ring.adapter.jetty :refer [run-jetty]] [ring.middleware.params :refer [wrap-params]] [compojure.core :refer [defroutes ANY GET PUT POST DELETE OPTIONS]] [clj-http.client :as client] [cheshire.core :refer [parse-string generate-string]])) (defroutes app (ANY "/hello" [] (resource :available-media-types ["text/html"] :handle-ok "<html><h1>Hello Clojure !</h1></html>")) (route/not-found "Not Found !")) ;;=> #'liberator-example.example/app (def handler (-> app wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (.stop server) ;;=> nil (defresource hello :available-media-types ["text/html"] :handle-ok "<html><h1>Hello Clojure from defresource !</h1></html>") ;;=> #'liberator-example.example/hello (defroutes app (ANY "/hello" [] hello) (route/not-found "Not Found !")) ;;=> #'liberator-example.example/app (def handler (-> app wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (.stop server) ;;=> nil (defresource parameterized-hello [x] :available-media-types ["text/html"] :handle-ok (format "<html><h1>Hello Clojure from %s !</h1></html>" x) ) ;;=> #'liberator-example.example/parameterized-hello (defroutes parameterized-hello-app (ANY "/hello/:x" [x] (parameterized-hello x)) (route/not-found "Not Found !")) ;;=> #'liberator-example.example/parameterized-hello-app (def handler (-> parameterized-hello-app wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (.stop server) ;;=> nil (def customer-ref (ref {:makoto {:name "<NAME>" :country "Japan"} :nico {:name "<NAME>" :country "France"}})) ;;=> #'liberator-example.example/customer-ref (defresource customer-list :allowed-methods [:get :post] :available-media-types ["application/json"] :exists? (fn [_] (let [result @customer-ref] (if-not (nil? result) {::entry result}))) :post! (fn [ctx] (let [body (parse-string (slurp (get-in ctx [:request :body])) true)] (dosync (alter customer-ref assoc (keyword (:id body)) (dissoc body :id))))) :handle-ok ::entry :handle-not-found {:error "id is not found"}) ;;=> #'liberator-example.example/customer-list (defresource customer-entity [id] :allowed-methods [:get :put :delete] :available-media-types ["application/json"] :exists? (fn [_] (let [result ( get @customer-ref (keyword id))] (info "get ======>" (keyword id)) (if-not (nil? result) {::entry result}))) :put! (fn [ctx] (let [body (parse-string (slurp (get-in ctx [:request :body])) true)] (dosync (alter customer-ref assoc (keyword id) (dissoc body :id))))) :delete! (fn [_] (dosync (alter customer-ref dissoc (keyword id)))) :existed? (fn [_] (nil? (get @customer-ref id ::sentinel))) :new? (fn [_] (nil? (get @customer-ref id ::sentinel))) :handle-ok ::entry :handle-not-found {:error "id is not found"})) ;;=> #'liberator-example.example/customer-entity (defroutes customer (ANY "/customer" [] customer-list) (ANY "/customer/:id" [id] (customer-entity id))) ;;=> #'liberator-example.example/app (def handler (-> customer wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (client/get "http://localhost:3000/customer") ;;=> {:status 200, :headers {"Date" "Sun, 26 Jun 2016 20:14:34 GMT", ;;=> "Content-Type" "application/json;charset=UTF-8", "Vary" "Accept", ;;=> "Connection" "close", "Server" "Jetty(9.2.10.v20150310)"}, ;;=> :body "{\"makoto\":{\"name\":\"<NAME>\",\"country\":\"Japan\"}, ;;=> \"nico\":{\"name\":\"<NAME>\",\"country\":\"France\"}}", ;;=> :request-time 6, :trace-redirects ["http://localhost:3000/customer"], ;;=> :orig-content-encoding nil} (client/post "http://localhost:3000/customer" {:body (generate-string {:id "rh" :name "<NAME>" :country "United States"})}) ;;=> {:status 201, :headers {"Date" "Sun, 26 Jun 2016 14:33:28 GMT", ;;=> "Content-Type" "application/json", "Vary" "Accept", "Connection" "close", ;;=> "Server" "Jetty(9.2.10.v20150310)"}, :body "", :request-time 8, ;;=> :trace-redirects ["http://localhost:3000/customer"], :orig-content-encoding nil} (-> (client/get "http://localhost:3000/customer/rh" ) :body (parse-string true)) ;;=> {:name "<NAME>", :country "United States"} (client/put "http://localhost:3000/customer/rh" {:body (generate-string {:name "<NAME>" :country "USA"})}) ;;=> {:status 204, :headers {"Date" "Sun, 26 Jun 2016 22:04:35 GMT", ;;=> "Content-Type" "application/json", "Vary" "Accept", "Connection" "close", ;;=> "Server" "Jetty(9.2.10.v20150310)"}, :body nil, :request-time 9, ;;=> :trace-redirects ["http://localhost:3000/customer/rh"], :orig-content-encoding nil} (-> (client/get "http://localhost:3000/customer/rh") :body (parse-string true)) ;;=> {:name "<NAME>", :country "USA"} (client/delete "http://localhost:3000/customer/rh") ;;=> {:status 204, :headers {"Date" "Sun, 26 Jun 2016 14:38:58 GMT", ;;=> "Content-Type" "application/json", "Vary" "Accept", "Connection" "close", ;;=> "Server" "Jetty(9.2.10.v20150310)"}, :body nil, :request-time 8, ;;=> :trace-redirects ["http://localhost:3000/customer/rh"], :orig-content-encoding nil} (.stop server) ;;=> nil (def handler (-> customer wrap-params (wrap-trace :header :ui))) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (client/get "http://localhost:3000/customer")
true
(ns liberator-example.example (:require [liberator.core :refer [resource defresource]] [ring.adapter.jetty :refer [run-jetty]] [ring.middleware.params :refer [wrap-params]] [compojure.core :refer [defroutes ANY GET PUT POST DELETE OPTIONS]] [clj-http.client :as client] [cheshire.core :refer [parse-string generate-string]])) (defroutes app (ANY "/hello" [] (resource :available-media-types ["text/html"] :handle-ok "<html><h1>Hello Clojure !</h1></html>")) (route/not-found "Not Found !")) ;;=> #'liberator-example.example/app (def handler (-> app wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (.stop server) ;;=> nil (defresource hello :available-media-types ["text/html"] :handle-ok "<html><h1>Hello Clojure from defresource !</h1></html>") ;;=> #'liberator-example.example/hello (defroutes app (ANY "/hello" [] hello) (route/not-found "Not Found !")) ;;=> #'liberator-example.example/app (def handler (-> app wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (.stop server) ;;=> nil (defresource parameterized-hello [x] :available-media-types ["text/html"] :handle-ok (format "<html><h1>Hello Clojure from %s !</h1></html>" x) ) ;;=> #'liberator-example.example/parameterized-hello (defroutes parameterized-hello-app (ANY "/hello/:x" [x] (parameterized-hello x)) (route/not-found "Not Found !")) ;;=> #'liberator-example.example/parameterized-hello-app (def handler (-> parameterized-hello-app wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (.stop server) ;;=> nil (def customer-ref (ref {:makoto {:name "PI:NAME:<NAME>END_PI" :country "Japan"} :nico {:name "PI:NAME:<NAME>END_PI" :country "France"}})) ;;=> #'liberator-example.example/customer-ref (defresource customer-list :allowed-methods [:get :post] :available-media-types ["application/json"] :exists? (fn [_] (let [result @customer-ref] (if-not (nil? result) {::entry result}))) :post! (fn [ctx] (let [body (parse-string (slurp (get-in ctx [:request :body])) true)] (dosync (alter customer-ref assoc (keyword (:id body)) (dissoc body :id))))) :handle-ok ::entry :handle-not-found {:error "id is not found"}) ;;=> #'liberator-example.example/customer-list (defresource customer-entity [id] :allowed-methods [:get :put :delete] :available-media-types ["application/json"] :exists? (fn [_] (let [result ( get @customer-ref (keyword id))] (info "get ======>" (keyword id)) (if-not (nil? result) {::entry result}))) :put! (fn [ctx] (let [body (parse-string (slurp (get-in ctx [:request :body])) true)] (dosync (alter customer-ref assoc (keyword id) (dissoc body :id))))) :delete! (fn [_] (dosync (alter customer-ref dissoc (keyword id)))) :existed? (fn [_] (nil? (get @customer-ref id ::sentinel))) :new? (fn [_] (nil? (get @customer-ref id ::sentinel))) :handle-ok ::entry :handle-not-found {:error "id is not found"})) ;;=> #'liberator-example.example/customer-entity (defroutes customer (ANY "/customer" [] customer-list) (ANY "/customer/:id" [id] (customer-entity id))) ;;=> #'liberator-example.example/app (def handler (-> customer wrap-params)) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (client/get "http://localhost:3000/customer") ;;=> {:status 200, :headers {"Date" "Sun, 26 Jun 2016 20:14:34 GMT", ;;=> "Content-Type" "application/json;charset=UTF-8", "Vary" "Accept", ;;=> "Connection" "close", "Server" "Jetty(9.2.10.v20150310)"}, ;;=> :body "{\"makoto\":{\"name\":\"PI:NAME:<NAME>END_PI\",\"country\":\"Japan\"}, ;;=> \"nico\":{\"name\":\"PI:NAME:<NAME>END_PI\",\"country\":\"France\"}}", ;;=> :request-time 6, :trace-redirects ["http://localhost:3000/customer"], ;;=> :orig-content-encoding nil} (client/post "http://localhost:3000/customer" {:body (generate-string {:id "rh" :name "PI:NAME:<NAME>END_PI" :country "United States"})}) ;;=> {:status 201, :headers {"Date" "Sun, 26 Jun 2016 14:33:28 GMT", ;;=> "Content-Type" "application/json", "Vary" "Accept", "Connection" "close", ;;=> "Server" "Jetty(9.2.10.v20150310)"}, :body "", :request-time 8, ;;=> :trace-redirects ["http://localhost:3000/customer"], :orig-content-encoding nil} (-> (client/get "http://localhost:3000/customer/rh" ) :body (parse-string true)) ;;=> {:name "PI:NAME:<NAME>END_PI", :country "United States"} (client/put "http://localhost:3000/customer/rh" {:body (generate-string {:name "PI:NAME:<NAME>END_PI" :country "USA"})}) ;;=> {:status 204, :headers {"Date" "Sun, 26 Jun 2016 22:04:35 GMT", ;;=> "Content-Type" "application/json", "Vary" "Accept", "Connection" "close", ;;=> "Server" "Jetty(9.2.10.v20150310)"}, :body nil, :request-time 9, ;;=> :trace-redirects ["http://localhost:3000/customer/rh"], :orig-content-encoding nil} (-> (client/get "http://localhost:3000/customer/rh") :body (parse-string true)) ;;=> {:name "PI:NAME:<NAME>END_PI", :country "USA"} (client/delete "http://localhost:3000/customer/rh") ;;=> {:status 204, :headers {"Date" "Sun, 26 Jun 2016 14:38:58 GMT", ;;=> "Content-Type" "application/json", "Vary" "Accept", "Connection" "close", ;;=> "Server" "Jetty(9.2.10.v20150310)"}, :body nil, :request-time 8, ;;=> :trace-redirects ["http://localhost:3000/customer/rh"], :orig-content-encoding nil} (.stop server) ;;=> nil (def handler (-> customer wrap-params (wrap-trace :header :ui))) ;;=> #'liberator-example.example/handler (def server (run-jetty handler {:port 3000 :join? false})) ;;=> #'liberator-example.example/server (client/get "http://localhost:3000/customer")
[ { "context": "))))\n\n(def wall? (partial = \\#))\n\n(def key? (set \"abcdefghijklmnopqrstuvwxyz\"))\n\n(def door? (set \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")", "end": 1342, "score": 0.9911338686943054, "start": 1316, "tag": "KEY", "value": "abcdefghijklmnopqrstuvwxyz" } ]
src/adventofcode2019/day18.clj
agriffis/adventofcode2019
0
(ns adventofcode2019.day18 (:require [adventofcode2019.contrib :refer [cond-let]] [adventofcode2019.graph :refer [trim-non-path-nodes join-hallways]] [clojure.string :as str] [ubergraph.core :as uber] [ubergraph.alg :as alg])) ;!zprint {:format :skip} (def example1 " ######################## #f.D.E.e.C.b.A.@.a.B.c.# ######################.# #d.....................# ######################## ") ;!zprint {:format :skip} (def example2 " ######################## #...............b.C.D.f# #.###################### #.....@.a.B.c.d.A.e.F.g# ######################## ") ;!zprint {:format :skip} (def example3 " ################# #i.G..c...e..H.p# ########.######## #j.A..b...f..D.o# ########@######## #k.E..a...g..B.n# ########.######## #l.F..d...h..C.m# ################# ") ;!zprint {:format :skip} (def example4 " ############# #DcBa.#.GhKl# #.###@#@#I### #e#d#####j#k# ###C#@#@###J# #fEbA.#.FgHi# ############# ") (def input1 (slurp "resources/day18.txt")) (def input2 (slurp "resources/day18b.txt")) (defn ->grid [s] (let [lines (str/split-lines (str/trim s))] (->> (for [[line y] (map vector lines (range)) [cell x] (map vector line (range))] [[x y] cell]) (into {})))) (def wall? (partial = \#)) (def key? (set "abcdefghijklmnopqrstuvwxyz")) (def door? (set "ABCDEFGHIJKLMNOPQRSTUVWXYZ")) (def origin? (partial = \@)) (defn ->graph [grid] (let [nodes (->> grid (remove (comp wall? second)) (map (fn [[xy c]] (vector xy (cond-> {} (key? c) (assoc :key c) (door? c) (assoc :door (Character/toLowerCase c)) (origin? c) (assoc :origin c)))))) edges (->> grid (remove (comp wall? second)) (mapcat (fn [[[x y]]] (vector [[x y] [(inc x) y] 1] [[x y] [x (inc y)] 1]))) (remove (comp wall? grid second)))] (-> (uber/graph) (uber/add-nodes-with-attrs* nodes) (uber/add-edges* edges)))) (defn paths-to-keys "What keys can we reach given a start node and keyring?" [g keyring start] (let [can-pass? (fn [n] (let [door (uber/attr g n :door)] (or (not door) (keyring door)))) interesting-key? (fn [n] (let [key (uber/attr g n :key)] (and key (not (keyring key))))) from-start (alg/shortest-path g {:start-node start :node-filter can-pass? :cost-attr :weight}) reachable-keys (->> (alg/all-destinations from-start) (filter interesting-key?))] (map (partial alg/path-to from-start) reachable-keys))) (defn explore- [best {:keys [g need keyring starts] steps-here :steps :as state}] ;(when (<= (count keyring) 5) (println keyring need)) (cond-let (zero? need) steps-here :let [best-here (@best [starts keyring])] (and (not (nil? best-here)) (>= steps-here best-here)) Long/MAX_VALUE :else (do (swap! best assoc [starts keyring] steps-here) (apply min (for [[i start] (map-indexed vector starts) p (sort-by alg/cost-of-path (paths-to-keys g keyring start)) :let [n (alg/end-of-path p)]] (explore- best (assoc state :steps (+ steps-here (alg/cost-of-path p)) :keyring (conj keyring (uber/attr g n :key)) :need (dec need) :starts (assoc starts i n)))))))) (defn explore [& args] (apply explore- (atom {}) args)) (defn shortest [input] (let [grid (->grid input) g (-> (->graph grid) trim-non-path-nodes join-hallways) origins (->> (uber/nodes g) (filterv #(uber/attr g % :origin))) need (->> grid vals (filter key?) count) state {:g g :keyring #{} :starts origins :steps 0 :need need}] (explore state))) (defn part1 [] (shortest input1)) (defn part2 [] (shortest input2))
27534
(ns adventofcode2019.day18 (:require [adventofcode2019.contrib :refer [cond-let]] [adventofcode2019.graph :refer [trim-non-path-nodes join-hallways]] [clojure.string :as str] [ubergraph.core :as uber] [ubergraph.alg :as alg])) ;!zprint {:format :skip} (def example1 " ######################## #f.D.E.e.C.b.A.@.a.B.c.# ######################.# #d.....................# ######################## ") ;!zprint {:format :skip} (def example2 " ######################## #...............b.C.D.f# #.###################### #.....@.a.B.c.d.A.e.F.g# ######################## ") ;!zprint {:format :skip} (def example3 " ################# #i.G..c...e..H.p# ########.######## #j.A..b...f..D.o# ########@######## #k.E..a...g..B.n# ########.######## #l.F..d...h..C.m# ################# ") ;!zprint {:format :skip} (def example4 " ############# #DcBa.#.GhKl# #.###@#@#I### #e#d#####j#k# ###C#@#@###J# #fEbA.#.FgHi# ############# ") (def input1 (slurp "resources/day18.txt")) (def input2 (slurp "resources/day18b.txt")) (defn ->grid [s] (let [lines (str/split-lines (str/trim s))] (->> (for [[line y] (map vector lines (range)) [cell x] (map vector line (range))] [[x y] cell]) (into {})))) (def wall? (partial = \#)) (def key? (set "<KEY>")) (def door? (set "ABCDEFGHIJKLMNOPQRSTUVWXYZ")) (def origin? (partial = \@)) (defn ->graph [grid] (let [nodes (->> grid (remove (comp wall? second)) (map (fn [[xy c]] (vector xy (cond-> {} (key? c) (assoc :key c) (door? c) (assoc :door (Character/toLowerCase c)) (origin? c) (assoc :origin c)))))) edges (->> grid (remove (comp wall? second)) (mapcat (fn [[[x y]]] (vector [[x y] [(inc x) y] 1] [[x y] [x (inc y)] 1]))) (remove (comp wall? grid second)))] (-> (uber/graph) (uber/add-nodes-with-attrs* nodes) (uber/add-edges* edges)))) (defn paths-to-keys "What keys can we reach given a start node and keyring?" [g keyring start] (let [can-pass? (fn [n] (let [door (uber/attr g n :door)] (or (not door) (keyring door)))) interesting-key? (fn [n] (let [key (uber/attr g n :key)] (and key (not (keyring key))))) from-start (alg/shortest-path g {:start-node start :node-filter can-pass? :cost-attr :weight}) reachable-keys (->> (alg/all-destinations from-start) (filter interesting-key?))] (map (partial alg/path-to from-start) reachable-keys))) (defn explore- [best {:keys [g need keyring starts] steps-here :steps :as state}] ;(when (<= (count keyring) 5) (println keyring need)) (cond-let (zero? need) steps-here :let [best-here (@best [starts keyring])] (and (not (nil? best-here)) (>= steps-here best-here)) Long/MAX_VALUE :else (do (swap! best assoc [starts keyring] steps-here) (apply min (for [[i start] (map-indexed vector starts) p (sort-by alg/cost-of-path (paths-to-keys g keyring start)) :let [n (alg/end-of-path p)]] (explore- best (assoc state :steps (+ steps-here (alg/cost-of-path p)) :keyring (conj keyring (uber/attr g n :key)) :need (dec need) :starts (assoc starts i n)))))))) (defn explore [& args] (apply explore- (atom {}) args)) (defn shortest [input] (let [grid (->grid input) g (-> (->graph grid) trim-non-path-nodes join-hallways) origins (->> (uber/nodes g) (filterv #(uber/attr g % :origin))) need (->> grid vals (filter key?) count) state {:g g :keyring #{} :starts origins :steps 0 :need need}] (explore state))) (defn part1 [] (shortest input1)) (defn part2 [] (shortest input2))
true
(ns adventofcode2019.day18 (:require [adventofcode2019.contrib :refer [cond-let]] [adventofcode2019.graph :refer [trim-non-path-nodes join-hallways]] [clojure.string :as str] [ubergraph.core :as uber] [ubergraph.alg :as alg])) ;!zprint {:format :skip} (def example1 " ######################## #f.D.E.e.C.b.A.@.a.B.c.# ######################.# #d.....................# ######################## ") ;!zprint {:format :skip} (def example2 " ######################## #...............b.C.D.f# #.###################### #.....@.a.B.c.d.A.e.F.g# ######################## ") ;!zprint {:format :skip} (def example3 " ################# #i.G..c...e..H.p# ########.######## #j.A..b...f..D.o# ########@######## #k.E..a...g..B.n# ########.######## #l.F..d...h..C.m# ################# ") ;!zprint {:format :skip} (def example4 " ############# #DcBa.#.GhKl# #.###@#@#I### #e#d#####j#k# ###C#@#@###J# #fEbA.#.FgHi# ############# ") (def input1 (slurp "resources/day18.txt")) (def input2 (slurp "resources/day18b.txt")) (defn ->grid [s] (let [lines (str/split-lines (str/trim s))] (->> (for [[line y] (map vector lines (range)) [cell x] (map vector line (range))] [[x y] cell]) (into {})))) (def wall? (partial = \#)) (def key? (set "PI:KEY:<KEY>END_PI")) (def door? (set "ABCDEFGHIJKLMNOPQRSTUVWXYZ")) (def origin? (partial = \@)) (defn ->graph [grid] (let [nodes (->> grid (remove (comp wall? second)) (map (fn [[xy c]] (vector xy (cond-> {} (key? c) (assoc :key c) (door? c) (assoc :door (Character/toLowerCase c)) (origin? c) (assoc :origin c)))))) edges (->> grid (remove (comp wall? second)) (mapcat (fn [[[x y]]] (vector [[x y] [(inc x) y] 1] [[x y] [x (inc y)] 1]))) (remove (comp wall? grid second)))] (-> (uber/graph) (uber/add-nodes-with-attrs* nodes) (uber/add-edges* edges)))) (defn paths-to-keys "What keys can we reach given a start node and keyring?" [g keyring start] (let [can-pass? (fn [n] (let [door (uber/attr g n :door)] (or (not door) (keyring door)))) interesting-key? (fn [n] (let [key (uber/attr g n :key)] (and key (not (keyring key))))) from-start (alg/shortest-path g {:start-node start :node-filter can-pass? :cost-attr :weight}) reachable-keys (->> (alg/all-destinations from-start) (filter interesting-key?))] (map (partial alg/path-to from-start) reachable-keys))) (defn explore- [best {:keys [g need keyring starts] steps-here :steps :as state}] ;(when (<= (count keyring) 5) (println keyring need)) (cond-let (zero? need) steps-here :let [best-here (@best [starts keyring])] (and (not (nil? best-here)) (>= steps-here best-here)) Long/MAX_VALUE :else (do (swap! best assoc [starts keyring] steps-here) (apply min (for [[i start] (map-indexed vector starts) p (sort-by alg/cost-of-path (paths-to-keys g keyring start)) :let [n (alg/end-of-path p)]] (explore- best (assoc state :steps (+ steps-here (alg/cost-of-path p)) :keyring (conj keyring (uber/attr g n :key)) :need (dec need) :starts (assoc starts i n)))))))) (defn explore [& args] (apply explore- (atom {}) args)) (defn shortest [input] (let [grid (->grid input) g (-> (->graph grid) trim-non-path-nodes join-hallways) origins (->> (uber/nodes g) (filterv #(uber/attr g % :origin))) need (->> grid vals (filter key?) count) state {:g g :keyring #{} :starts origins :steps 0 :need need}] (explore state))) (defn part1 [] (shortest input1)) (defn part2 [] (shortest input2))
[ { "context": "ntent \"\"}]\n [:meta {:name \"author\" :content \"Adrian Smith\"}]\n\n ;; <link rel=\"icon\" href=\"../../favicon", "end": 12232, "score": 0.9984460473060608, "start": 12220, "tag": "NAME", "value": "Adrian Smith" }, { "context": " [:a.nav-link {:href \"https://github.com/phronmophobic/treemap-clj\"}\n \"Code on Github\"]]", "end": 14046, "score": 0.9993013739585876, "start": 14033, "tag": "USERNAME", "value": "phronmophobic" }, { "context": " [:a.nav-link {:href \"https://github.com/phronmophobic/treemap-clj\"}\n \"Code on Github\"]]]\n :", "end": 16300, "score": 0.9979576468467712, "start": 16287, "tag": "USERNAME", "value": "phronmophobic" } ]
src/blog/mdown.clj
rgkirch/blog
2
(ns blog.mdown (:require [clojure.zip :as z] [membrane.ui :as ui :refer [horizontal-layout vertical-layout spacer on]] [membrane.skia :as skia] [membrane.component :refer [defui defeffect] :as component] [membrane.basic-components :as basic :refer [textarea checkbox]] [glow.core :as glow] glow.parse glow.html [glow.colorschemes] [hiccup.core :refer [html] :as hiccup]) (:import com.vladsch.flexmark.util.ast.Node com.vladsch.flexmark.html.HtmlRenderer com.vladsch.flexmark.parser.Parser com.vladsch.flexmark.ext.attributes.AttributesExtension com.vladsch.flexmark.ext.xwiki.macros.MacroExtension com.vladsch.flexmark.util.data.MutableDataSet com.phronemophobic.blog.HiccupNode)) ;; //options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create())); (def POSTS (atom {})) (defmacro defpost [name val] `(let [v# (def ~name ~val)] (swap! POSTS assoc (:id ~name) ~name) v#)) (defn doc->tree-seq [doc] (tree-seq #(.hasChildren %) #(seq (.getChildren %)) doc)) (defn doc->zip [doc] (z/zipper #(.hasChildren %) #(seq (.getChildren %)) (fn [node children] (.removeChildren node) (doseq [child children] (.appendChild node child)) node) doc)) (defn children [doc] (seq (.getChildren doc))) (def ^:dynamic *parse-state*) (defn zip-walk "Depth first walk of zip. edit each loc with f" [zip f] (loop [zip zip] (if (z/end? zip) (z/root zip) (recur (-> (z/edit zip f) z/next))))) (declare hiccup-node) (defmulti macroexpand1-doc (fn [m] (if (instance? com.vladsch.flexmark.ext.xwiki.macros.Macro m) (.getName m) (if (instance? com.vladsch.flexmark.ext.xwiki.macros.MacroBlock m) (.getName (.getMacroNode m)) (type m))))) (defmethod macroexpand1-doc :default [node] node) (defn inc-footnote-count [] (let [k [::footnote-macro ::footnote-index]] (set! *parse-state* (update-in *parse-state* k (fnil inc 0))) (get-in *parse-state* k))) (defn add-footnote [hiccup] (set! *parse-state* (update-in *parse-state* [::footnote-macro ::footnotes] (fnil conj []) hiccup))) (declare blog-html) (defmethod macroexpand1-doc "footnote" [macro] (let [idx (inc-footnote-count) childs (->> (children macro) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.MacroClose %)) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.Macro %)))] (add-footnote (map blog-html childs)) (hiccup-node [:sup [:a {:href (str "#footnote-" idx) :name (str "footnote-ref-" idx) :title (clojure.string/join (map #(.getChars %) childs))} idx]]))) (defn get-footnotes [] (get-in *parse-state* [::footnote-macro ::footnotes])) (defmethod macroexpand1-doc "footnotes" [macro] (hiccup-node [:div.footnotes (for [[i footnote] (map-indexed vector (get-footnotes)) :let [idx (inc i)]] [:div [:a {:name (str "footnote-" idx) :href (str "#footnote-ref-" idx)} idx] ". " footnote])])) (defn preprocess-footnotes [doc] (binding [*parse-state* nil] (zip-walk (doc->zip doc) macroexpand1-doc))) (defn header->tag-name [header] (let [tag-chars (clojure.string/join (map #(.getChars %) (children header))) tag-name (-> tag-chars (clojure.string/replace #"[ ]" "-") (clojure.string/replace #"[^A-Z\-a-z0-9]" ""))] tag-name)) (defn make-toc [] (z/zipper (constantly true) #(get % :children []) (fn [node children] (assoc node :children children)) {})) (defn add-section [toc header] (loop [toc toc] (let [p (z/up toc) level (.getLevel header)] (if (and p (>= (get (z/node toc) :level) level)) (recur p) (let [res (-> toc (z/append-child {:title (clojure.string/join (map #(.getChars %) (children header))) :name (header->tag-name header) :level level}) z/down z/rightmost)] res))))) (defn gen-table-of-contents [doc] (loop [zip (doc->zip doc) toc (make-toc)] (if (z/end? zip) (z/root toc) (let [node (z/node zip)] (if (instance? com.vladsch.flexmark.ast.Heading node) (recur (z/next zip) (add-section toc node)) (recur (z/next zip) toc)))))) (defn gen-toc-html [toc] (let [html () html (if-let [childs (:children toc)] (cons [:ul (map gen-toc-html childs)] html) html) html (if-let [title (:title toc)] (cons [:li [:a {:href (str "#" (:name toc))} title]] html) html)] html)) (defn preprocess-table-of-contents [doc] (let [toc (gen-table-of-contents doc) toc-html (gen-toc-html toc)] (zip-walk (doc->zip doc) (fn [node] (if (instance? com.vladsch.flexmark.ext.xwiki.macros.MacroBlock node) (if (= (.getName (.getMacroNode node)) "table-of-contents") (hiccup-node toc-html) node) node))))) (defn parse [s] (let [options (doto (MutableDataSet.) (.set Parser/EXTENSIONS [(AttributesExtension/create) (MacroExtension/create)])) parser (-> (Parser/builder options) (.build)) doc (.parse parser s) doc (-> doc (preprocess-footnotes) (preprocess-table-of-contents))] doc)) (defprotocol IBlogHtml (blog-html [this])) (extend-type Object IBlogHtml (blog-html [this] (println "No implementation of method :blog-html found for class: " (type this)) (println "line: " (.getLineNumber this)) (let [s (str (.getChars this))] (println (subs s 0 (min 30 (count s))))) (throw (Exception. "")))) (defn hiccup-node [content] (HiccupNode. content)) #_(defn doall* [s] (dorun (tree-seq #(do (prn %) (seqable? %)) seq s)) s) (extend-type HiccupNode IBlogHtml (blog-html [this] (.hiccup this))) (extend-type com.vladsch.flexmark.util.ast.Document IBlogHtml (blog-html [this] [:div {} (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.Paragraph IBlogHtml (blog-html [this] [:p {} (map blog-html (children this)) ])) (extend-type com.vladsch.flexmark.ast.Heading IBlogHtml (blog-html [this] (let [tag (keyword (str "h" (.getLevel this)))] [tag {:id (header->tag-name this)} (map blog-html (children this))]))) (extend-type com.vladsch.flexmark.ast.StrongEmphasis IBlogHtml (blog-html [this] [:strong (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.Emphasis IBlogHtml (blog-html [this] [:em (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.BlockQuote IBlogHtml (blog-html [this] [:blockquote.blockquote (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.FencedCodeBlock IBlogHtml (blog-html [this] (case (.getInfo this) "clojure" (let [source (clojure.string/join (map #(.getChars %) (children this)))] (glow/highlight-html source)) ;; else [:pre [:code (map blog-html (children this))]] ) )) (extend-type com.vladsch.flexmark.ast.Code IBlogHtml (blog-html [this] [:code (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.Text IBlogHtml (blog-html [this] (hiccup/h (str (.getChars this))))) (extend-type com.vladsch.flexmark.ast.Link IBlogHtml (blog-html [this] [:a {:href (-> this .getUrl str)} (-> this (.getText) str)])) (extend-type com.vladsch.flexmark.ast.AutoLink IBlogHtml (blog-html [this] [:a {:href (-> this .getUrl str)} (-> this (.getText) str)])) (extend-type com.vladsch.flexmark.ast.Image IBlogHtml (blog-html [this] [:img {:src (-> this .getUrl str) :alt (-> this (.getText) str) :style "max-width: 90vw;height:auto"}])) (extend-type com.vladsch.flexmark.ast.SoftLineBreak IBlogHtml (blog-html [this] [:br])) (extend-type com.vladsch.flexmark.ast.OrderedList IBlogHtml (blog-html [this] [:ol (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.OrderedListItem IBlogHtml (blog-html [this] [:li (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.BulletList IBlogHtml (blog-html [this] [:ul (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.BulletListItem IBlogHtml (blog-html [this] [:li (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.HtmlCommentBlock IBlogHtml (blog-html [this] nil)) (extend-type com.vladsch.flexmark.ast.HtmlInlineComment IBlogHtml (blog-html [this] nil)) ;; (extend-type com.vladsch.flexmark.ast.OrderedList ;; IBlogHtml ;; (blog-html [this] ;; [:ol.list-group (map blog-html (children this))])) ;; com.vladsch.flexmark.ast.BulletList (defmulti markdown-macro (fn [macro] (.getName macro))) (defmethod markdown-macro "tableflip" [macro] [:p {:title "table flip"} "(╯°□°)╯︵ ┻━┻"]) (defmethod markdown-macro "blockquote-footer" [macro] [:footer.blockquote-footer (map blog-html (drop-last (children macro)))]) (defmethod markdown-macro "contemplation-break" [macro] [:div {:style "width: 90%;height: 500px;border-top: #c4c4c4 1px solid;border-bottom: #c4c4c4 1px solid;margin-bottom:30px;" :title "This space intentionally left blank for contemplation."}]) (defmethod markdown-macro "shoot-in-the-foots" [macro] [:span {:title "everybody is each shooting just one foot in this metaphor"} "foots"]) (defmethod markdown-macro "square-bracket-left" [macro] "[") (defmethod markdown-macro "square-bracket-right" [macro] "]") (defmethod markdown-macro "quote" [macro] (let [childs (->> (children macro) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.MacroClose %)) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.Macro %)))] (hiccup/h (clojure.string/join (map #(.getChars %) childs))))) ;; (defmethod markdown-macro "footnote" [macro] ;; (let [idx ] ;; [:a {:href "#"} ;; (hiccup/h (str "[" idx "]"))])) ;; (defmethod markdown-macro "footnotes" [macro] ;; "Footnotes!" ;; ) (extend-type com.vladsch.flexmark.ext.xwiki.macros.Macro IBlogHtml (blog-html [this] (markdown-macro this))) (extend-type com.vladsch.flexmark.ext.xwiki.macros.MacroBlock IBlogHtml (blog-html [this] (markdown-macro (.getMacroNode this)))) (extend-type com.vladsch.flexmark.ast.ThematicBreak IBlogHtml (blog-html [this] [:hr])) (defn parse-blog [fname] (-> (slurp fname) parse blog-html)) (defn blog-page [{:keys [title subheading nav src body asset-prefix] :as post}] (let [body (if body body (parse-blog src))] [:html {:lang "en"} [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1, shrink-to-fit=no"}] ;; [:meta {:name "description" :content ""}] [:meta {:name "author" :content "Adrian Smith"}] ;; <link rel="icon" href="../../favicon.ico"> [:link {:rel "icon" :href (str asset-prefix "favicon.ico")}] [:title title] [:link {:href (str asset-prefix "bootstrap.min.css") :rel "stylesheet"}] [:link {:href (str asset-prefix "blog.css") :rel "stylesheet"}] [:style {:type "text/css"} (glow/generate-css {:exception "#f00" :repeat "#f00" :conditional "#30a" :variable "black" :core-fn "#30a" :definition "#00f" :reader-char "#555" :special-form "#30a" :macro "#05a" :number "#164" :boolean "#164" :nil "#164" :s-exp "#997" :keyword "#708" :comment "#a50" :string "#a11" :character "#f50" :regex "#f50"} ) " div.syntax { padding: 4px ; background-color: #f8f8f8; margin-bottom: 18px }" " div.syntax pre { margin-bottom: 0 }"] ] [:body (when nav [:div {:class "blog-masthead"} nav]) [:div.blog-header [:div.container [:h1.blog-title title] [:p.lead.blog-description subheading]]] [:div.container [:div.row [:div.col-sm-8.blog-main [:div.blog-post body]]]] ]]) ) #_(defpost functional-ui-post {:id :functional-ui :title "Rethinking Functional UI Software design" :subheading "The div must die" :nav nil #_[:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link.active {:href "#"} "Treemaps are awesome!"] [:a.nav-link {:href "treemap-demo.html"} "Treemap Demo"] [:a.nav-link {:href "https://github.com/phronmophobic/treemap-clj"} "Code on Github"]]] :src "markdown/functional-ui.md" :out "functional-ui.html"}) (defpost what-is-a-ui {:id :what-is-a-ui :title "What is a User Interface?" :subheading "How to build a functional UI library from scratch: Part I" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "what-is-a-user-interface/" :src "markdown/what-is-a-user-interface.md" :out "what-is-a-user-interface.html"}) (defpost ui-model {:id :ui-model :title "Implementing a Functional UI Model" :subheading "How to build a functional UI library from scratch: Part II" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "ui-model/" :src "markdown/ui-model.md" :out "ui-model.html"}) (defpost reusable-ui-components {:id :reusable-ui-components :title "Reusable UI Components" :subheading "How to build a functional UI library from scratch: Part III" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "ui-model/" :src "markdown/reusable-ui-components.md" :out "reusable-ui-components.html"}) (defpost html-tax-post {:id :html-tax :title "The HTML Tax" :subheading "Html is a poor medium for specifying user interfaces" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "html-tax/" :src "markdown/html-tax.md" :out "html-tax.html"}) (defpost treemap-post {:id :treemap :title "Treemaps are awesome!" :subheading "An alternative to pprint for generically visualizing heterogeneous, hierarchical data" :asset-prefix "treemaps-are-awesome/" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"] [:a.nav-link.active {:href "#"} "Treemaps are awesome!"] [:a.nav-link {:href "treemap-demo.html"} "Treemap Demo"] [:a.nav-link {:href "https://github.com/phronmophobic/treemap-clj"} "Code on Github"]]] :src "markdown/treemaps-are-awesome.md" :out "treemaps-are-awesome.html"}) (defn render-post! [{:keys [title subheading nav src out] :as post}] (let [page-html (blog-page post) html-str (html page-html)] (spit (str "resources/public/" (:out post)) html-str))) (defonce running? (atom false)) (defn watch-blog [post-id] (let [post (get @POSTS post-id) _ (assert post (str "No post for id " (pr-str post-id) ". \n" (clojure.string/join "\n" (keys @POSTS))) ) f (clojure.java.io/file (:src post)) get-val #(.lastModified f)] (when (not @running?) (reset! running? true) @(future (loop [last-val nil] (let [current-val (get-val)] (when @running? (when (not= current-val last-val) (print "rendering blog...") (flush) (try (render-post! post) (print " done.\n") (catch Exception e (println "error: \n") (prn e))) (flush)) (Thread/sleep 500 ) (recur current-val)))))))) (defn render-index [] (let [page-html (blog-page {:title "Phronemophobic's Blog" :body [:div (for [post (vals @POSTS)] [:div [:a {:href (:out post)} (:title post)]])] :asset-prefix "/"}) html-str (html page-html)] (spit "resources/public/index.html" html-str))) (defn render-all! [] (render-index) (run! render-post! (vals @POSTS))) (defn -main [ & args] (watch-blog (keyword (first args)))) ;; for fenced code blog ;; (.getinfo adsf) to find lang (comment(-> (parse "```foo (+ 1 2) ``` ") doc->zip z/next z/node (.getInfo) ))
3429
(ns blog.mdown (:require [clojure.zip :as z] [membrane.ui :as ui :refer [horizontal-layout vertical-layout spacer on]] [membrane.skia :as skia] [membrane.component :refer [defui defeffect] :as component] [membrane.basic-components :as basic :refer [textarea checkbox]] [glow.core :as glow] glow.parse glow.html [glow.colorschemes] [hiccup.core :refer [html] :as hiccup]) (:import com.vladsch.flexmark.util.ast.Node com.vladsch.flexmark.html.HtmlRenderer com.vladsch.flexmark.parser.Parser com.vladsch.flexmark.ext.attributes.AttributesExtension com.vladsch.flexmark.ext.xwiki.macros.MacroExtension com.vladsch.flexmark.util.data.MutableDataSet com.phronemophobic.blog.HiccupNode)) ;; //options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create())); (def POSTS (atom {})) (defmacro defpost [name val] `(let [v# (def ~name ~val)] (swap! POSTS assoc (:id ~name) ~name) v#)) (defn doc->tree-seq [doc] (tree-seq #(.hasChildren %) #(seq (.getChildren %)) doc)) (defn doc->zip [doc] (z/zipper #(.hasChildren %) #(seq (.getChildren %)) (fn [node children] (.removeChildren node) (doseq [child children] (.appendChild node child)) node) doc)) (defn children [doc] (seq (.getChildren doc))) (def ^:dynamic *parse-state*) (defn zip-walk "Depth first walk of zip. edit each loc with f" [zip f] (loop [zip zip] (if (z/end? zip) (z/root zip) (recur (-> (z/edit zip f) z/next))))) (declare hiccup-node) (defmulti macroexpand1-doc (fn [m] (if (instance? com.vladsch.flexmark.ext.xwiki.macros.Macro m) (.getName m) (if (instance? com.vladsch.flexmark.ext.xwiki.macros.MacroBlock m) (.getName (.getMacroNode m)) (type m))))) (defmethod macroexpand1-doc :default [node] node) (defn inc-footnote-count [] (let [k [::footnote-macro ::footnote-index]] (set! *parse-state* (update-in *parse-state* k (fnil inc 0))) (get-in *parse-state* k))) (defn add-footnote [hiccup] (set! *parse-state* (update-in *parse-state* [::footnote-macro ::footnotes] (fnil conj []) hiccup))) (declare blog-html) (defmethod macroexpand1-doc "footnote" [macro] (let [idx (inc-footnote-count) childs (->> (children macro) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.MacroClose %)) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.Macro %)))] (add-footnote (map blog-html childs)) (hiccup-node [:sup [:a {:href (str "#footnote-" idx) :name (str "footnote-ref-" idx) :title (clojure.string/join (map #(.getChars %) childs))} idx]]))) (defn get-footnotes [] (get-in *parse-state* [::footnote-macro ::footnotes])) (defmethod macroexpand1-doc "footnotes" [macro] (hiccup-node [:div.footnotes (for [[i footnote] (map-indexed vector (get-footnotes)) :let [idx (inc i)]] [:div [:a {:name (str "footnote-" idx) :href (str "#footnote-ref-" idx)} idx] ". " footnote])])) (defn preprocess-footnotes [doc] (binding [*parse-state* nil] (zip-walk (doc->zip doc) macroexpand1-doc))) (defn header->tag-name [header] (let [tag-chars (clojure.string/join (map #(.getChars %) (children header))) tag-name (-> tag-chars (clojure.string/replace #"[ ]" "-") (clojure.string/replace #"[^A-Z\-a-z0-9]" ""))] tag-name)) (defn make-toc [] (z/zipper (constantly true) #(get % :children []) (fn [node children] (assoc node :children children)) {})) (defn add-section [toc header] (loop [toc toc] (let [p (z/up toc) level (.getLevel header)] (if (and p (>= (get (z/node toc) :level) level)) (recur p) (let [res (-> toc (z/append-child {:title (clojure.string/join (map #(.getChars %) (children header))) :name (header->tag-name header) :level level}) z/down z/rightmost)] res))))) (defn gen-table-of-contents [doc] (loop [zip (doc->zip doc) toc (make-toc)] (if (z/end? zip) (z/root toc) (let [node (z/node zip)] (if (instance? com.vladsch.flexmark.ast.Heading node) (recur (z/next zip) (add-section toc node)) (recur (z/next zip) toc)))))) (defn gen-toc-html [toc] (let [html () html (if-let [childs (:children toc)] (cons [:ul (map gen-toc-html childs)] html) html) html (if-let [title (:title toc)] (cons [:li [:a {:href (str "#" (:name toc))} title]] html) html)] html)) (defn preprocess-table-of-contents [doc] (let [toc (gen-table-of-contents doc) toc-html (gen-toc-html toc)] (zip-walk (doc->zip doc) (fn [node] (if (instance? com.vladsch.flexmark.ext.xwiki.macros.MacroBlock node) (if (= (.getName (.getMacroNode node)) "table-of-contents") (hiccup-node toc-html) node) node))))) (defn parse [s] (let [options (doto (MutableDataSet.) (.set Parser/EXTENSIONS [(AttributesExtension/create) (MacroExtension/create)])) parser (-> (Parser/builder options) (.build)) doc (.parse parser s) doc (-> doc (preprocess-footnotes) (preprocess-table-of-contents))] doc)) (defprotocol IBlogHtml (blog-html [this])) (extend-type Object IBlogHtml (blog-html [this] (println "No implementation of method :blog-html found for class: " (type this)) (println "line: " (.getLineNumber this)) (let [s (str (.getChars this))] (println (subs s 0 (min 30 (count s))))) (throw (Exception. "")))) (defn hiccup-node [content] (HiccupNode. content)) #_(defn doall* [s] (dorun (tree-seq #(do (prn %) (seqable? %)) seq s)) s) (extend-type HiccupNode IBlogHtml (blog-html [this] (.hiccup this))) (extend-type com.vladsch.flexmark.util.ast.Document IBlogHtml (blog-html [this] [:div {} (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.Paragraph IBlogHtml (blog-html [this] [:p {} (map blog-html (children this)) ])) (extend-type com.vladsch.flexmark.ast.Heading IBlogHtml (blog-html [this] (let [tag (keyword (str "h" (.getLevel this)))] [tag {:id (header->tag-name this)} (map blog-html (children this))]))) (extend-type com.vladsch.flexmark.ast.StrongEmphasis IBlogHtml (blog-html [this] [:strong (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.Emphasis IBlogHtml (blog-html [this] [:em (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.BlockQuote IBlogHtml (blog-html [this] [:blockquote.blockquote (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.FencedCodeBlock IBlogHtml (blog-html [this] (case (.getInfo this) "clojure" (let [source (clojure.string/join (map #(.getChars %) (children this)))] (glow/highlight-html source)) ;; else [:pre [:code (map blog-html (children this))]] ) )) (extend-type com.vladsch.flexmark.ast.Code IBlogHtml (blog-html [this] [:code (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.Text IBlogHtml (blog-html [this] (hiccup/h (str (.getChars this))))) (extend-type com.vladsch.flexmark.ast.Link IBlogHtml (blog-html [this] [:a {:href (-> this .getUrl str)} (-> this (.getText) str)])) (extend-type com.vladsch.flexmark.ast.AutoLink IBlogHtml (blog-html [this] [:a {:href (-> this .getUrl str)} (-> this (.getText) str)])) (extend-type com.vladsch.flexmark.ast.Image IBlogHtml (blog-html [this] [:img {:src (-> this .getUrl str) :alt (-> this (.getText) str) :style "max-width: 90vw;height:auto"}])) (extend-type com.vladsch.flexmark.ast.SoftLineBreak IBlogHtml (blog-html [this] [:br])) (extend-type com.vladsch.flexmark.ast.OrderedList IBlogHtml (blog-html [this] [:ol (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.OrderedListItem IBlogHtml (blog-html [this] [:li (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.BulletList IBlogHtml (blog-html [this] [:ul (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.BulletListItem IBlogHtml (blog-html [this] [:li (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.HtmlCommentBlock IBlogHtml (blog-html [this] nil)) (extend-type com.vladsch.flexmark.ast.HtmlInlineComment IBlogHtml (blog-html [this] nil)) ;; (extend-type com.vladsch.flexmark.ast.OrderedList ;; IBlogHtml ;; (blog-html [this] ;; [:ol.list-group (map blog-html (children this))])) ;; com.vladsch.flexmark.ast.BulletList (defmulti markdown-macro (fn [macro] (.getName macro))) (defmethod markdown-macro "tableflip" [macro] [:p {:title "table flip"} "(╯°□°)╯︵ ┻━┻"]) (defmethod markdown-macro "blockquote-footer" [macro] [:footer.blockquote-footer (map blog-html (drop-last (children macro)))]) (defmethod markdown-macro "contemplation-break" [macro] [:div {:style "width: 90%;height: 500px;border-top: #c4c4c4 1px solid;border-bottom: #c4c4c4 1px solid;margin-bottom:30px;" :title "This space intentionally left blank for contemplation."}]) (defmethod markdown-macro "shoot-in-the-foots" [macro] [:span {:title "everybody is each shooting just one foot in this metaphor"} "foots"]) (defmethod markdown-macro "square-bracket-left" [macro] "[") (defmethod markdown-macro "square-bracket-right" [macro] "]") (defmethod markdown-macro "quote" [macro] (let [childs (->> (children macro) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.MacroClose %)) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.Macro %)))] (hiccup/h (clojure.string/join (map #(.getChars %) childs))))) ;; (defmethod markdown-macro "footnote" [macro] ;; (let [idx ] ;; [:a {:href "#"} ;; (hiccup/h (str "[" idx "]"))])) ;; (defmethod markdown-macro "footnotes" [macro] ;; "Footnotes!" ;; ) (extend-type com.vladsch.flexmark.ext.xwiki.macros.Macro IBlogHtml (blog-html [this] (markdown-macro this))) (extend-type com.vladsch.flexmark.ext.xwiki.macros.MacroBlock IBlogHtml (blog-html [this] (markdown-macro (.getMacroNode this)))) (extend-type com.vladsch.flexmark.ast.ThematicBreak IBlogHtml (blog-html [this] [:hr])) (defn parse-blog [fname] (-> (slurp fname) parse blog-html)) (defn blog-page [{:keys [title subheading nav src body asset-prefix] :as post}] (let [body (if body body (parse-blog src))] [:html {:lang "en"} [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1, shrink-to-fit=no"}] ;; [:meta {:name "description" :content ""}] [:meta {:name "author" :content "<NAME>"}] ;; <link rel="icon" href="../../favicon.ico"> [:link {:rel "icon" :href (str asset-prefix "favicon.ico")}] [:title title] [:link {:href (str asset-prefix "bootstrap.min.css") :rel "stylesheet"}] [:link {:href (str asset-prefix "blog.css") :rel "stylesheet"}] [:style {:type "text/css"} (glow/generate-css {:exception "#f00" :repeat "#f00" :conditional "#30a" :variable "black" :core-fn "#30a" :definition "#00f" :reader-char "#555" :special-form "#30a" :macro "#05a" :number "#164" :boolean "#164" :nil "#164" :s-exp "#997" :keyword "#708" :comment "#a50" :string "#a11" :character "#f50" :regex "#f50"} ) " div.syntax { padding: 4px ; background-color: #f8f8f8; margin-bottom: 18px }" " div.syntax pre { margin-bottom: 0 }"] ] [:body (when nav [:div {:class "blog-masthead"} nav]) [:div.blog-header [:div.container [:h1.blog-title title] [:p.lead.blog-description subheading]]] [:div.container [:div.row [:div.col-sm-8.blog-main [:div.blog-post body]]]] ]]) ) #_(defpost functional-ui-post {:id :functional-ui :title "Rethinking Functional UI Software design" :subheading "The div must die" :nav nil #_[:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link.active {:href "#"} "Treemaps are awesome!"] [:a.nav-link {:href "treemap-demo.html"} "Treemap Demo"] [:a.nav-link {:href "https://github.com/phronmophobic/treemap-clj"} "Code on Github"]]] :src "markdown/functional-ui.md" :out "functional-ui.html"}) (defpost what-is-a-ui {:id :what-is-a-ui :title "What is a User Interface?" :subheading "How to build a functional UI library from scratch: Part I" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "what-is-a-user-interface/" :src "markdown/what-is-a-user-interface.md" :out "what-is-a-user-interface.html"}) (defpost ui-model {:id :ui-model :title "Implementing a Functional UI Model" :subheading "How to build a functional UI library from scratch: Part II" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "ui-model/" :src "markdown/ui-model.md" :out "ui-model.html"}) (defpost reusable-ui-components {:id :reusable-ui-components :title "Reusable UI Components" :subheading "How to build a functional UI library from scratch: Part III" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "ui-model/" :src "markdown/reusable-ui-components.md" :out "reusable-ui-components.html"}) (defpost html-tax-post {:id :html-tax :title "The HTML Tax" :subheading "Html is a poor medium for specifying user interfaces" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "html-tax/" :src "markdown/html-tax.md" :out "html-tax.html"}) (defpost treemap-post {:id :treemap :title "Treemaps are awesome!" :subheading "An alternative to pprint for generically visualizing heterogeneous, hierarchical data" :asset-prefix "treemaps-are-awesome/" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"] [:a.nav-link.active {:href "#"} "Treemaps are awesome!"] [:a.nav-link {:href "treemap-demo.html"} "Treemap Demo"] [:a.nav-link {:href "https://github.com/phronmophobic/treemap-clj"} "Code on Github"]]] :src "markdown/treemaps-are-awesome.md" :out "treemaps-are-awesome.html"}) (defn render-post! [{:keys [title subheading nav src out] :as post}] (let [page-html (blog-page post) html-str (html page-html)] (spit (str "resources/public/" (:out post)) html-str))) (defonce running? (atom false)) (defn watch-blog [post-id] (let [post (get @POSTS post-id) _ (assert post (str "No post for id " (pr-str post-id) ". \n" (clojure.string/join "\n" (keys @POSTS))) ) f (clojure.java.io/file (:src post)) get-val #(.lastModified f)] (when (not @running?) (reset! running? true) @(future (loop [last-val nil] (let [current-val (get-val)] (when @running? (when (not= current-val last-val) (print "rendering blog...") (flush) (try (render-post! post) (print " done.\n") (catch Exception e (println "error: \n") (prn e))) (flush)) (Thread/sleep 500 ) (recur current-val)))))))) (defn render-index [] (let [page-html (blog-page {:title "Phronemophobic's Blog" :body [:div (for [post (vals @POSTS)] [:div [:a {:href (:out post)} (:title post)]])] :asset-prefix "/"}) html-str (html page-html)] (spit "resources/public/index.html" html-str))) (defn render-all! [] (render-index) (run! render-post! (vals @POSTS))) (defn -main [ & args] (watch-blog (keyword (first args)))) ;; for fenced code blog ;; (.getinfo adsf) to find lang (comment(-> (parse "```foo (+ 1 2) ``` ") doc->zip z/next z/node (.getInfo) ))
true
(ns blog.mdown (:require [clojure.zip :as z] [membrane.ui :as ui :refer [horizontal-layout vertical-layout spacer on]] [membrane.skia :as skia] [membrane.component :refer [defui defeffect] :as component] [membrane.basic-components :as basic :refer [textarea checkbox]] [glow.core :as glow] glow.parse glow.html [glow.colorschemes] [hiccup.core :refer [html] :as hiccup]) (:import com.vladsch.flexmark.util.ast.Node com.vladsch.flexmark.html.HtmlRenderer com.vladsch.flexmark.parser.Parser com.vladsch.flexmark.ext.attributes.AttributesExtension com.vladsch.flexmark.ext.xwiki.macros.MacroExtension com.vladsch.flexmark.util.data.MutableDataSet com.phronemophobic.blog.HiccupNode)) ;; //options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create())); (def POSTS (atom {})) (defmacro defpost [name val] `(let [v# (def ~name ~val)] (swap! POSTS assoc (:id ~name) ~name) v#)) (defn doc->tree-seq [doc] (tree-seq #(.hasChildren %) #(seq (.getChildren %)) doc)) (defn doc->zip [doc] (z/zipper #(.hasChildren %) #(seq (.getChildren %)) (fn [node children] (.removeChildren node) (doseq [child children] (.appendChild node child)) node) doc)) (defn children [doc] (seq (.getChildren doc))) (def ^:dynamic *parse-state*) (defn zip-walk "Depth first walk of zip. edit each loc with f" [zip f] (loop [zip zip] (if (z/end? zip) (z/root zip) (recur (-> (z/edit zip f) z/next))))) (declare hiccup-node) (defmulti macroexpand1-doc (fn [m] (if (instance? com.vladsch.flexmark.ext.xwiki.macros.Macro m) (.getName m) (if (instance? com.vladsch.flexmark.ext.xwiki.macros.MacroBlock m) (.getName (.getMacroNode m)) (type m))))) (defmethod macroexpand1-doc :default [node] node) (defn inc-footnote-count [] (let [k [::footnote-macro ::footnote-index]] (set! *parse-state* (update-in *parse-state* k (fnil inc 0))) (get-in *parse-state* k))) (defn add-footnote [hiccup] (set! *parse-state* (update-in *parse-state* [::footnote-macro ::footnotes] (fnil conj []) hiccup))) (declare blog-html) (defmethod macroexpand1-doc "footnote" [macro] (let [idx (inc-footnote-count) childs (->> (children macro) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.MacroClose %)) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.Macro %)))] (add-footnote (map blog-html childs)) (hiccup-node [:sup [:a {:href (str "#footnote-" idx) :name (str "footnote-ref-" idx) :title (clojure.string/join (map #(.getChars %) childs))} idx]]))) (defn get-footnotes [] (get-in *parse-state* [::footnote-macro ::footnotes])) (defmethod macroexpand1-doc "footnotes" [macro] (hiccup-node [:div.footnotes (for [[i footnote] (map-indexed vector (get-footnotes)) :let [idx (inc i)]] [:div [:a {:name (str "footnote-" idx) :href (str "#footnote-ref-" idx)} idx] ". " footnote])])) (defn preprocess-footnotes [doc] (binding [*parse-state* nil] (zip-walk (doc->zip doc) macroexpand1-doc))) (defn header->tag-name [header] (let [tag-chars (clojure.string/join (map #(.getChars %) (children header))) tag-name (-> tag-chars (clojure.string/replace #"[ ]" "-") (clojure.string/replace #"[^A-Z\-a-z0-9]" ""))] tag-name)) (defn make-toc [] (z/zipper (constantly true) #(get % :children []) (fn [node children] (assoc node :children children)) {})) (defn add-section [toc header] (loop [toc toc] (let [p (z/up toc) level (.getLevel header)] (if (and p (>= (get (z/node toc) :level) level)) (recur p) (let [res (-> toc (z/append-child {:title (clojure.string/join (map #(.getChars %) (children header))) :name (header->tag-name header) :level level}) z/down z/rightmost)] res))))) (defn gen-table-of-contents [doc] (loop [zip (doc->zip doc) toc (make-toc)] (if (z/end? zip) (z/root toc) (let [node (z/node zip)] (if (instance? com.vladsch.flexmark.ast.Heading node) (recur (z/next zip) (add-section toc node)) (recur (z/next zip) toc)))))) (defn gen-toc-html [toc] (let [html () html (if-let [childs (:children toc)] (cons [:ul (map gen-toc-html childs)] html) html) html (if-let [title (:title toc)] (cons [:li [:a {:href (str "#" (:name toc))} title]] html) html)] html)) (defn preprocess-table-of-contents [doc] (let [toc (gen-table-of-contents doc) toc-html (gen-toc-html toc)] (zip-walk (doc->zip doc) (fn [node] (if (instance? com.vladsch.flexmark.ext.xwiki.macros.MacroBlock node) (if (= (.getName (.getMacroNode node)) "table-of-contents") (hiccup-node toc-html) node) node))))) (defn parse [s] (let [options (doto (MutableDataSet.) (.set Parser/EXTENSIONS [(AttributesExtension/create) (MacroExtension/create)])) parser (-> (Parser/builder options) (.build)) doc (.parse parser s) doc (-> doc (preprocess-footnotes) (preprocess-table-of-contents))] doc)) (defprotocol IBlogHtml (blog-html [this])) (extend-type Object IBlogHtml (blog-html [this] (println "No implementation of method :blog-html found for class: " (type this)) (println "line: " (.getLineNumber this)) (let [s (str (.getChars this))] (println (subs s 0 (min 30 (count s))))) (throw (Exception. "")))) (defn hiccup-node [content] (HiccupNode. content)) #_(defn doall* [s] (dorun (tree-seq #(do (prn %) (seqable? %)) seq s)) s) (extend-type HiccupNode IBlogHtml (blog-html [this] (.hiccup this))) (extend-type com.vladsch.flexmark.util.ast.Document IBlogHtml (blog-html [this] [:div {} (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.Paragraph IBlogHtml (blog-html [this] [:p {} (map blog-html (children this)) ])) (extend-type com.vladsch.flexmark.ast.Heading IBlogHtml (blog-html [this] (let [tag (keyword (str "h" (.getLevel this)))] [tag {:id (header->tag-name this)} (map blog-html (children this))]))) (extend-type com.vladsch.flexmark.ast.StrongEmphasis IBlogHtml (blog-html [this] [:strong (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.Emphasis IBlogHtml (blog-html [this] [:em (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.BlockQuote IBlogHtml (blog-html [this] [:blockquote.blockquote (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.FencedCodeBlock IBlogHtml (blog-html [this] (case (.getInfo this) "clojure" (let [source (clojure.string/join (map #(.getChars %) (children this)))] (glow/highlight-html source)) ;; else [:pre [:code (map blog-html (children this))]] ) )) (extend-type com.vladsch.flexmark.ast.Code IBlogHtml (blog-html [this] [:code (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.Text IBlogHtml (blog-html [this] (hiccup/h (str (.getChars this))))) (extend-type com.vladsch.flexmark.ast.Link IBlogHtml (blog-html [this] [:a {:href (-> this .getUrl str)} (-> this (.getText) str)])) (extend-type com.vladsch.flexmark.ast.AutoLink IBlogHtml (blog-html [this] [:a {:href (-> this .getUrl str)} (-> this (.getText) str)])) (extend-type com.vladsch.flexmark.ast.Image IBlogHtml (blog-html [this] [:img {:src (-> this .getUrl str) :alt (-> this (.getText) str) :style "max-width: 90vw;height:auto"}])) (extend-type com.vladsch.flexmark.ast.SoftLineBreak IBlogHtml (blog-html [this] [:br])) (extend-type com.vladsch.flexmark.ast.OrderedList IBlogHtml (blog-html [this] [:ol (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.OrderedListItem IBlogHtml (blog-html [this] [:li (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.BulletList IBlogHtml (blog-html [this] [:ul (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.BulletListItem IBlogHtml (blog-html [this] [:li (map blog-html (children this))])) (extend-type com.vladsch.flexmark.ast.HtmlCommentBlock IBlogHtml (blog-html [this] nil)) (extend-type com.vladsch.flexmark.ast.HtmlInlineComment IBlogHtml (blog-html [this] nil)) ;; (extend-type com.vladsch.flexmark.ast.OrderedList ;; IBlogHtml ;; (blog-html [this] ;; [:ol.list-group (map blog-html (children this))])) ;; com.vladsch.flexmark.ast.BulletList (defmulti markdown-macro (fn [macro] (.getName macro))) (defmethod markdown-macro "tableflip" [macro] [:p {:title "table flip"} "(╯°□°)╯︵ ┻━┻"]) (defmethod markdown-macro "blockquote-footer" [macro] [:footer.blockquote-footer (map blog-html (drop-last (children macro)))]) (defmethod markdown-macro "contemplation-break" [macro] [:div {:style "width: 90%;height: 500px;border-top: #c4c4c4 1px solid;border-bottom: #c4c4c4 1px solid;margin-bottom:30px;" :title "This space intentionally left blank for contemplation."}]) (defmethod markdown-macro "shoot-in-the-foots" [macro] [:span {:title "everybody is each shooting just one foot in this metaphor"} "foots"]) (defmethod markdown-macro "square-bracket-left" [macro] "[") (defmethod markdown-macro "square-bracket-right" [macro] "]") (defmethod markdown-macro "quote" [macro] (let [childs (->> (children macro) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.MacroClose %)) (remove #(instance? com.vladsch.flexmark.ext.xwiki.macros.Macro %)))] (hiccup/h (clojure.string/join (map #(.getChars %) childs))))) ;; (defmethod markdown-macro "footnote" [macro] ;; (let [idx ] ;; [:a {:href "#"} ;; (hiccup/h (str "[" idx "]"))])) ;; (defmethod markdown-macro "footnotes" [macro] ;; "Footnotes!" ;; ) (extend-type com.vladsch.flexmark.ext.xwiki.macros.Macro IBlogHtml (blog-html [this] (markdown-macro this))) (extend-type com.vladsch.flexmark.ext.xwiki.macros.MacroBlock IBlogHtml (blog-html [this] (markdown-macro (.getMacroNode this)))) (extend-type com.vladsch.flexmark.ast.ThematicBreak IBlogHtml (blog-html [this] [:hr])) (defn parse-blog [fname] (-> (slurp fname) parse blog-html)) (defn blog-page [{:keys [title subheading nav src body asset-prefix] :as post}] (let [body (if body body (parse-blog src))] [:html {:lang "en"} [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1, shrink-to-fit=no"}] ;; [:meta {:name "description" :content ""}] [:meta {:name "author" :content "PI:NAME:<NAME>END_PI"}] ;; <link rel="icon" href="../../favicon.ico"> [:link {:rel "icon" :href (str asset-prefix "favicon.ico")}] [:title title] [:link {:href (str asset-prefix "bootstrap.min.css") :rel "stylesheet"}] [:link {:href (str asset-prefix "blog.css") :rel "stylesheet"}] [:style {:type "text/css"} (glow/generate-css {:exception "#f00" :repeat "#f00" :conditional "#30a" :variable "black" :core-fn "#30a" :definition "#00f" :reader-char "#555" :special-form "#30a" :macro "#05a" :number "#164" :boolean "#164" :nil "#164" :s-exp "#997" :keyword "#708" :comment "#a50" :string "#a11" :character "#f50" :regex "#f50"} ) " div.syntax { padding: 4px ; background-color: #f8f8f8; margin-bottom: 18px }" " div.syntax pre { margin-bottom: 0 }"] ] [:body (when nav [:div {:class "blog-masthead"} nav]) [:div.blog-header [:div.container [:h1.blog-title title] [:p.lead.blog-description subheading]]] [:div.container [:div.row [:div.col-sm-8.blog-main [:div.blog-post body]]]] ]]) ) #_(defpost functional-ui-post {:id :functional-ui :title "Rethinking Functional UI Software design" :subheading "The div must die" :nav nil #_[:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link.active {:href "#"} "Treemaps are awesome!"] [:a.nav-link {:href "treemap-demo.html"} "Treemap Demo"] [:a.nav-link {:href "https://github.com/phronmophobic/treemap-clj"} "Code on Github"]]] :src "markdown/functional-ui.md" :out "functional-ui.html"}) (defpost what-is-a-ui {:id :what-is-a-ui :title "What is a User Interface?" :subheading "How to build a functional UI library from scratch: Part I" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "what-is-a-user-interface/" :src "markdown/what-is-a-user-interface.md" :out "what-is-a-user-interface.html"}) (defpost ui-model {:id :ui-model :title "Implementing a Functional UI Model" :subheading "How to build a functional UI library from scratch: Part II" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "ui-model/" :src "markdown/ui-model.md" :out "ui-model.html"}) (defpost reusable-ui-components {:id :reusable-ui-components :title "Reusable UI Components" :subheading "How to build a functional UI library from scratch: Part III" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "ui-model/" :src "markdown/reusable-ui-components.md" :out "reusable-ui-components.html"}) (defpost html-tax-post {:id :html-tax :title "The HTML Tax" :subheading "Html is a poor medium for specifying user interfaces" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"]]] :asset-prefix "html-tax/" :src "markdown/html-tax.md" :out "html-tax.html"}) (defpost treemap-post {:id :treemap :title "Treemaps are awesome!" :subheading "An alternative to pprint for generically visualizing heterogeneous, hierarchical data" :asset-prefix "treemaps-are-awesome/" :nav [:div {:class "container"} [:nav.nav.blog-nav [:a.nav-link {:href "/"} "Home"] [:a.nav-link.active {:href "#"} "Treemaps are awesome!"] [:a.nav-link {:href "treemap-demo.html"} "Treemap Demo"] [:a.nav-link {:href "https://github.com/phronmophobic/treemap-clj"} "Code on Github"]]] :src "markdown/treemaps-are-awesome.md" :out "treemaps-are-awesome.html"}) (defn render-post! [{:keys [title subheading nav src out] :as post}] (let [page-html (blog-page post) html-str (html page-html)] (spit (str "resources/public/" (:out post)) html-str))) (defonce running? (atom false)) (defn watch-blog [post-id] (let [post (get @POSTS post-id) _ (assert post (str "No post for id " (pr-str post-id) ". \n" (clojure.string/join "\n" (keys @POSTS))) ) f (clojure.java.io/file (:src post)) get-val #(.lastModified f)] (when (not @running?) (reset! running? true) @(future (loop [last-val nil] (let [current-val (get-val)] (when @running? (when (not= current-val last-val) (print "rendering blog...") (flush) (try (render-post! post) (print " done.\n") (catch Exception e (println "error: \n") (prn e))) (flush)) (Thread/sleep 500 ) (recur current-val)))))))) (defn render-index [] (let [page-html (blog-page {:title "Phronemophobic's Blog" :body [:div (for [post (vals @POSTS)] [:div [:a {:href (:out post)} (:title post)]])] :asset-prefix "/"}) html-str (html page-html)] (spit "resources/public/index.html" html-str))) (defn render-all! [] (render-index) (run! render-post! (vals @POSTS))) (defn -main [ & args] (watch-blog (keyword (first args)))) ;; for fenced code blog ;; (.getinfo adsf) to find lang (comment(-> (parse "```foo (+ 1 2) ``` ") doc->zip z/next z/node (.getInfo) ))
[ { "context": ";;\n;; Copyright © 2011-2014 Carlo Sciolla\n;;\n;; Licensed under the Apache License, Version ", "end": 41, "score": 0.9998534321784973, "start": 28, "tag": "NAME", "value": "Carlo Sciolla" }, { "context": "tions under the License.\n;;\n;; Contributors:\n;; Carlo Sciolla - initial implementation\n;; Peter Monks ", "end": 639, "score": 0.9998580813407898, "start": 626, "tag": "NAME", "value": "Carlo Sciolla" }, { "context": " Carlo Sciolla - initial implementation\n;; Peter Monks - contributor\n;; Andreas Steffan - contrib", "end": 684, "score": 0.999844491481781, "start": 673, "tag": "NAME", "value": "Peter Monks" }, { "context": "entation\n;; Peter Monks - contributor\n;; Andreas Steffan - contributor\n\n;; Nice idea, but does not play wi", "end": 724, "score": 0.9998540878295898, "start": 709, "tag": "NAME", "value": "Andreas Steffan" }, { "context": "re/tools.nrepl \"0.2.12\"]\n ;; [com.gfredericks/debug-repl \"0.0.7\"]\n ;; [spyscope", "end": 2210, "score": 0.8477691411972046, "start": 2199, "tag": "USERNAME", "value": "gfredericks" }, { "context": "scope.\n ;; See https://github.com/technomancy/leiningen/issues/741 for an\n ;; e", "end": 2956, "score": 0.996792733669281, "start": 2945, "tag": "USERNAME", "value": "technomancy" }, { "context": "jure.org/jira/browse/NREPL-53\n ;; [com.gfredericks/nrepl-53-monkeypatch \"0.1.0\"]\n ;; [lei", "end": 5766, "score": 0.7264845371246338, "start": 5755, "tag": "USERNAME", "value": "gfredericks" }, { "context": " [org.eclipse.jetty/jetty-server \"9.2.11.v20150529\"]\n ", "end": 8137, "score": 0.9286766052246094, "start": 8131, "tag": "IP_ADDRESS", "value": "9.2.11" }, { "context": " [org.eclipse.jetty.websocket/websocket-server \"9.2.11.v20150529\"]\n ", "end": 8242, "score": 0.9024809002876282, "start": 8236, "tag": "IP_ADDRESS", "value": "9.2.11" }, { "context": " [org.eclipse.jetty/jetty-webapp \"9.2.11.v20150529\"]\n ", "end": 8390, "score": 0.6258409023284912, "start": 8387, "tag": "IP_ADDRESS", "value": "2.1" }, { "context": " [org.eclipse.jetty/jetty-server \"9.2.11.v20150529\"]\n ", "end": 9246, "score": 0.9680739045143127, "start": 9240, "tag": "IP_ADDRESS", "value": "9.2.11" }, { "context": " [org.eclipse.jetty.websocket/websocket-server \"9.2.11.v20150529\"]\n ", "end": 9351, "score": 0.9630709290504456, "start": 9345, "tag": "IP_ADDRESS", "value": "9.2.11" }, { "context": " [org.eclipse.jetty/jetty-webapp \"9.2.11.v20150529\"]\n ", "end": 9442, "score": 0.8186081051826477, "start": 9436, "tag": "IP_ADDRESS", "value": "9.2.11" } ]
project.clj
deas/lambdalf
1
;; ;; Copyright © 2011-2014 Carlo Sciolla ;; ;; 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. ;; ;; Contributors: ;; Carlo Sciolla - initial implementation ;; Peter Monks - contributor ;; Andreas Steffan - contributor ;; Nice idea, but does not play with lein ancient ;; ;; (def alfresco-version "5.1.e") ;; (def alfresco-core-version "5.6") ;; (def spring-version "3.2.14.RELEASE") ;; (def spring-surf-version "5.8") ;; (def h2-version "1.4.190") ;; (def xml-apis-version-override "1.4.01") ;; (def junit-version-override "4.11") ;; (def cider-nrepl-version "0.11.0") ;; (def refactor-nrepl-version "1.2.0") ;; (def jetty-version "9.2.11.v20150529") ;; (def gorilla-repl-version "0.3.5-SNAPSHOT") ;; (def websocket-version "1.0") (defproject org.clojars.deas/lambdalf "1.10.0-SNAPSHOT" :title "lambdalf" :description "Lambdalf -- Clojure support for Alfresco, batteries included" :url "https://github.com/lambdalf/lambdalf" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.4.0" :repositories [["alfresco.public" "https://artifacts.alfresco.com/nexus/content/groups/public/"]] ;; To keep things simple for now, we put all the tooling here as well ;; http://jakemccrary.com/blog/2015/01/11/overview-of-my-leiningen-profiles-dot-clj/ ;; parinfer/0.1.0-SNAPSHOT/parinfer-0.1.0-SNAPSHOT :dependencies [[org.clojure/tools.logging "0.3.1"] [org.clojure/tools.namespace "0.2.10"] [org.clojure/tools.trace "0.7.9"] [org.clojure/clojure "1.9.0-alpha13"] [org.clojure/tools.nrepl "0.2.12"] ;; [com.gfredericks/debug-repl "0.0.7"] ;; [spyscope "0.1.5"] [evalive "1.1.0"] [org.clojure/java.classpath "0.2.3"] [org.clojure/java.jmx "0.3.1"] ;; schmetterling introduces deps conflicting with alfresco ;; [schmetterling "0.0.8"] ;; SNAPSHOTS do not build uberjars? [cider/cider-nrepl "0.14.0" #_~cider-nrepl-version] ; 8.0-SNAPSHOT"] [refactor-nrepl "1.2.0" #_~refactor-nrepl-version] ;; WARNING: do _not_ add test, provided or runtime dependencies ;; here as they will be included in the uberjar, regardless of scope. ;; See https://github.com/technomancy/leiningen/issues/741 for an ;; explanation of why this occurs. [com.stuartsierra/component "0.3.1"] ;; Weeding out deps here! [ring/ring-core "1.4.0" :exclusions [ring/ring-codec commons-fileupload crypto-random clj-time commons-io]] [clj-time "0.9.0" :exclusions [joda-time]] [ring/ring-codec "1.0.0" :exclusions [commons-codec]] [crypto-random "1.2.0" :exclusions [commons-codec]] [compojure "1.4.0" :exclusions [ring/ring-core]] [org.clojars.deas/gorilla-repl-ng "0.3.6" :exclusions [*/*] #_[http-kit org.slf4j/slf4j-api javax.servlet/servlet-api grimradical/clj-semver ch.qos.logback/logback-classic org.clojure/data.codec org.clojure/tools.logging]] ;; A ton of deps :exclusions [com.sun.jdmk/jmxtools] [ring/ring-servlet "1.4.0"] [org.clojure/data.json "0.2.6"] ;; [ring/ring-json "0.4.0"] ;; [cheshire "5.5.0" :exclusions [*/*]] ;; for gorilla websocket-relay ;; jackson-core "2.5.3", alfresco jackson-core-2.3.2 #_[com.fasterxml.jackson.dataformat/jackson-dataformat-smile "2.3.2" :exclusions [*/*]] #_[com.fasterxml.jackson.dataformat/jackson-dataformat-cbor "2.3.2" :exclusions [*/*]] [org.clojars.deas/gorilla-plot "0.2.0"] [org.clojars.deas/gorilla-middleware "0.1.2"] [clojail "1.0.6"] [com.cemerick/pomegranate "0.3.1"] [ring-middleware-format "0.7.0"] ;; TODO Untangle those two in gorilla-repl [http-kit "2.2.0"] [grimradical/clj-semver "0.3.0" :exclusions [org.clojure/clojure]] [ring-cors "0.1.8"] ;; Additional stuff for gorilla ;; incanter could add a whole lot of stuff for gorilla ;; [incanter/incanter-core "1.9.1"] ] :aot [gorilla-repl.servlet] ;; :aot [contentreich.ring-servlet] :javac-options ["-target" "1.7" "-source" "1.7"] :plugins [[cider/cider-nrepl "0.14.0"] [refactor-nrepl "1.2.0" #_~refactor-nrepl-version] ;; http://dev.clojure.org/jira/browse/NREPL-53 ;; [com.gfredericks/nrepl-53-monkeypatch "0.1.0"] ;; [lein-cljsbuild "1.1.0"] ;; [lein-figwheel "0.4.0"] ] :repl-options { :timeout 120000 :nrepl-middleware [;; com.gfredericks.debug-repl/wrap-debug-repl ;; [cider.nrepl.middleware.classpath/wrap-classpath ;; cider.nrepl.middleware.complete/wrap-complete ;; cider.nrepl.middleware.info/wrap-info ;; cider.nrepl.middleware.inspect/wrap-inspect ;; cider.nrepl.middleware.macroexpand/wrap-macroexpand ;; cider.nrepl.middleware.stacktrace/wrap-stacktrace ;; cider.nrepl.middleware.test/wrap-test ;; cider.nrepl.middleware.trace/wrap-trace ;; cider.nrepl.middleware.undef/wrap-undef] ] ;; :init-ns scratch ;; :init (create-application-context) } :profiles {:dev {:plugins [ ;; [lein-midje "3.1.3"] ] ;;[lein-amp "0.3.0"]]} :source-paths ["src/clojure"] ;; "dev" :dependencies [ [org.alfresco/alfresco-repository "5.1.e" :classifier "h2scripts" :exclusions [ commons-codec ;; commons-fileupload ]] ;; [spyscope "0.1.5"] [com.h2database/h2 "1.4.190" #_~h2-version] [clj-http "2.1.0" :exclusions [ commons-codec ] ] [org.eclipse.jetty/jetty-server "9.2.11.v20150529"] [org.eclipse.jetty.websocket/websocket-server "9.2.11.v20150529"] ;; [midje "1.8.3"] [org.eclipse.jetty/jetty-webapp "9.2.11.v20150529"] [org.eclipse.jetty/jetty-util "9.2.11.v20150529"] ]} ;; :uberjar { :aot :all } :test {:dependencies [ [org.alfresco/alfresco-repository "5.1.e" :classifier "h2scripts" :exclusions [ ;; commons-codec ;; commons-fileupload ]] [com.h2database/h2 "1.4.190" #_~h2-version] [clj-http "2.1.0"] [org.eclipse.jetty/jetty-server "9.2.11.v20150529"] [org.eclipse.jetty.websocket/websocket-server "9.2.11.v20150529"] [org.eclipse.jetty/jetty-webapp "9.2.11.v20150529"] [org.eclipse.jetty/jetty-util "9.2.11.v20150529"] [junit/junit "4.11"]]} :provided {:dependencies [ ;; [org.clojure/clojurescript "1.7.122"] ;; We need to fiddle around with the deps so the clojure deps chain shows up [org.alfresco/alfresco-core "5.6" :exclusions [ ;; commons-codec ;; joda-time ]] [org.alfresco/alfresco-data-model "5.1.e" ;; :exclusions [org.apache.tika/tika-parsers] ] [org.alfresco/alfresco-mbeans "5.1.e"] [org.alfresco/alfresco-remote-api "5.1.e"] [org.alfresco/alfresco-repository "5.1.e" :exclusions [commons-collections ;; commons-codec ;; joda-time ;; commons-fileupload ]] ;; You have to build the web-client yourself for now ;; "mvn -f pom-alfresco-web-client.xml install" in web-client/ ;; [org.alfresco/alfresco-web-client "5.1.e"#_~alfresco.version] [org.springframework/spring-context "3.2.14.RELEASE"] [org.springframework/spring-beans "3.2.14.RELEASE"] [org.springframework.extensions.surf/spring-webscripts "5.8" :exclusions [ ;; commons-fileupload ]] ;; The deps alfresco really wants ;; override wrong dep from core causing RTE when starting up the context [commons-collections "3.2.2"] ;; Weeding out fileupload, joda, commons-io does not work - comes in via clj(!) deps [commons-fileupload "1.3.1"] [joda-time "2.8.1"] [commons-io "2.4"] [commons-codec "1.10"] [javax.websocket/javax.websocket-api "1.0"] [javax.servlet/javax.servlet-api "3.1.0"] [xml-apis/xml-apis "1.4.01"]]}} ;; :aot [alfresco] :source-paths ["src/clojure"] :java-source-paths ["src/java"] :resource-paths ["src/resource"] ;; :amp-source-path "src/amp" ;; :amp-target-war [org.alfresco/alfresco "5.1.e"#_~alfresco.version :extension "war" :javac-target "1.7" ;; Beware !!! refactor-nrepl middleware can kick off midje integration tests! :test-paths ["itest" "test"] ;; ["itest" "test"] ;; :injections [(require 'spyscope.core)] ;; http://www.jayway.com/2014/09/09/integration-testing-setup-with-midje-and-leiningen/ :aliases {"itest" ["midje" ":filters" "it"] ;;"src/clojure" "test" "itest" "test" ["midje"] "utest" ["midje" ":filters" "-it"]} )
107566
;; ;; Copyright © 2011-2014 <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. ;; ;; Contributors: ;; <NAME> - initial implementation ;; <NAME> - contributor ;; <NAME> - contributor ;; Nice idea, but does not play with lein ancient ;; ;; (def alfresco-version "5.1.e") ;; (def alfresco-core-version "5.6") ;; (def spring-version "3.2.14.RELEASE") ;; (def spring-surf-version "5.8") ;; (def h2-version "1.4.190") ;; (def xml-apis-version-override "1.4.01") ;; (def junit-version-override "4.11") ;; (def cider-nrepl-version "0.11.0") ;; (def refactor-nrepl-version "1.2.0") ;; (def jetty-version "9.2.11.v20150529") ;; (def gorilla-repl-version "0.3.5-SNAPSHOT") ;; (def websocket-version "1.0") (defproject org.clojars.deas/lambdalf "1.10.0-SNAPSHOT" :title "lambdalf" :description "Lambdalf -- Clojure support for Alfresco, batteries included" :url "https://github.com/lambdalf/lambdalf" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.4.0" :repositories [["alfresco.public" "https://artifacts.alfresco.com/nexus/content/groups/public/"]] ;; To keep things simple for now, we put all the tooling here as well ;; http://jakemccrary.com/blog/2015/01/11/overview-of-my-leiningen-profiles-dot-clj/ ;; parinfer/0.1.0-SNAPSHOT/parinfer-0.1.0-SNAPSHOT :dependencies [[org.clojure/tools.logging "0.3.1"] [org.clojure/tools.namespace "0.2.10"] [org.clojure/tools.trace "0.7.9"] [org.clojure/clojure "1.9.0-alpha13"] [org.clojure/tools.nrepl "0.2.12"] ;; [com.gfredericks/debug-repl "0.0.7"] ;; [spyscope "0.1.5"] [evalive "1.1.0"] [org.clojure/java.classpath "0.2.3"] [org.clojure/java.jmx "0.3.1"] ;; schmetterling introduces deps conflicting with alfresco ;; [schmetterling "0.0.8"] ;; SNAPSHOTS do not build uberjars? [cider/cider-nrepl "0.14.0" #_~cider-nrepl-version] ; 8.0-SNAPSHOT"] [refactor-nrepl "1.2.0" #_~refactor-nrepl-version] ;; WARNING: do _not_ add test, provided or runtime dependencies ;; here as they will be included in the uberjar, regardless of scope. ;; See https://github.com/technomancy/leiningen/issues/741 for an ;; explanation of why this occurs. [com.stuartsierra/component "0.3.1"] ;; Weeding out deps here! [ring/ring-core "1.4.0" :exclusions [ring/ring-codec commons-fileupload crypto-random clj-time commons-io]] [clj-time "0.9.0" :exclusions [joda-time]] [ring/ring-codec "1.0.0" :exclusions [commons-codec]] [crypto-random "1.2.0" :exclusions [commons-codec]] [compojure "1.4.0" :exclusions [ring/ring-core]] [org.clojars.deas/gorilla-repl-ng "0.3.6" :exclusions [*/*] #_[http-kit org.slf4j/slf4j-api javax.servlet/servlet-api grimradical/clj-semver ch.qos.logback/logback-classic org.clojure/data.codec org.clojure/tools.logging]] ;; A ton of deps :exclusions [com.sun.jdmk/jmxtools] [ring/ring-servlet "1.4.0"] [org.clojure/data.json "0.2.6"] ;; [ring/ring-json "0.4.0"] ;; [cheshire "5.5.0" :exclusions [*/*]] ;; for gorilla websocket-relay ;; jackson-core "2.5.3", alfresco jackson-core-2.3.2 #_[com.fasterxml.jackson.dataformat/jackson-dataformat-smile "2.3.2" :exclusions [*/*]] #_[com.fasterxml.jackson.dataformat/jackson-dataformat-cbor "2.3.2" :exclusions [*/*]] [org.clojars.deas/gorilla-plot "0.2.0"] [org.clojars.deas/gorilla-middleware "0.1.2"] [clojail "1.0.6"] [com.cemerick/pomegranate "0.3.1"] [ring-middleware-format "0.7.0"] ;; TODO Untangle those two in gorilla-repl [http-kit "2.2.0"] [grimradical/clj-semver "0.3.0" :exclusions [org.clojure/clojure]] [ring-cors "0.1.8"] ;; Additional stuff for gorilla ;; incanter could add a whole lot of stuff for gorilla ;; [incanter/incanter-core "1.9.1"] ] :aot [gorilla-repl.servlet] ;; :aot [contentreich.ring-servlet] :javac-options ["-target" "1.7" "-source" "1.7"] :plugins [[cider/cider-nrepl "0.14.0"] [refactor-nrepl "1.2.0" #_~refactor-nrepl-version] ;; http://dev.clojure.org/jira/browse/NREPL-53 ;; [com.gfredericks/nrepl-53-monkeypatch "0.1.0"] ;; [lein-cljsbuild "1.1.0"] ;; [lein-figwheel "0.4.0"] ] :repl-options { :timeout 120000 :nrepl-middleware [;; com.gfredericks.debug-repl/wrap-debug-repl ;; [cider.nrepl.middleware.classpath/wrap-classpath ;; cider.nrepl.middleware.complete/wrap-complete ;; cider.nrepl.middleware.info/wrap-info ;; cider.nrepl.middleware.inspect/wrap-inspect ;; cider.nrepl.middleware.macroexpand/wrap-macroexpand ;; cider.nrepl.middleware.stacktrace/wrap-stacktrace ;; cider.nrepl.middleware.test/wrap-test ;; cider.nrepl.middleware.trace/wrap-trace ;; cider.nrepl.middleware.undef/wrap-undef] ] ;; :init-ns scratch ;; :init (create-application-context) } :profiles {:dev {:plugins [ ;; [lein-midje "3.1.3"] ] ;;[lein-amp "0.3.0"]]} :source-paths ["src/clojure"] ;; "dev" :dependencies [ [org.alfresco/alfresco-repository "5.1.e" :classifier "h2scripts" :exclusions [ commons-codec ;; commons-fileupload ]] ;; [spyscope "0.1.5"] [com.h2database/h2 "1.4.190" #_~h2-version] [clj-http "2.1.0" :exclusions [ commons-codec ] ] [org.eclipse.jetty/jetty-server "9.2.11.v20150529"] [org.eclipse.jetty.websocket/websocket-server "9.2.11.v20150529"] ;; [midje "1.8.3"] [org.eclipse.jetty/jetty-webapp "9.2.11.v20150529"] [org.eclipse.jetty/jetty-util "9.2.11.v20150529"] ]} ;; :uberjar { :aot :all } :test {:dependencies [ [org.alfresco/alfresco-repository "5.1.e" :classifier "h2scripts" :exclusions [ ;; commons-codec ;; commons-fileupload ]] [com.h2database/h2 "1.4.190" #_~h2-version] [clj-http "2.1.0"] [org.eclipse.jetty/jetty-server "9.2.11.v20150529"] [org.eclipse.jetty.websocket/websocket-server "9.2.11.v20150529"] [org.eclipse.jetty/jetty-webapp "9.2.11.v20150529"] [org.eclipse.jetty/jetty-util "9.2.11.v20150529"] [junit/junit "4.11"]]} :provided {:dependencies [ ;; [org.clojure/clojurescript "1.7.122"] ;; We need to fiddle around with the deps so the clojure deps chain shows up [org.alfresco/alfresco-core "5.6" :exclusions [ ;; commons-codec ;; joda-time ]] [org.alfresco/alfresco-data-model "5.1.e" ;; :exclusions [org.apache.tika/tika-parsers] ] [org.alfresco/alfresco-mbeans "5.1.e"] [org.alfresco/alfresco-remote-api "5.1.e"] [org.alfresco/alfresco-repository "5.1.e" :exclusions [commons-collections ;; commons-codec ;; joda-time ;; commons-fileupload ]] ;; You have to build the web-client yourself for now ;; "mvn -f pom-alfresco-web-client.xml install" in web-client/ ;; [org.alfresco/alfresco-web-client "5.1.e"#_~alfresco.version] [org.springframework/spring-context "3.2.14.RELEASE"] [org.springframework/spring-beans "3.2.14.RELEASE"] [org.springframework.extensions.surf/spring-webscripts "5.8" :exclusions [ ;; commons-fileupload ]] ;; The deps alfresco really wants ;; override wrong dep from core causing RTE when starting up the context [commons-collections "3.2.2"] ;; Weeding out fileupload, joda, commons-io does not work - comes in via clj(!) deps [commons-fileupload "1.3.1"] [joda-time "2.8.1"] [commons-io "2.4"] [commons-codec "1.10"] [javax.websocket/javax.websocket-api "1.0"] [javax.servlet/javax.servlet-api "3.1.0"] [xml-apis/xml-apis "1.4.01"]]}} ;; :aot [alfresco] :source-paths ["src/clojure"] :java-source-paths ["src/java"] :resource-paths ["src/resource"] ;; :amp-source-path "src/amp" ;; :amp-target-war [org.alfresco/alfresco "5.1.e"#_~alfresco.version :extension "war" :javac-target "1.7" ;; Beware !!! refactor-nrepl middleware can kick off midje integration tests! :test-paths ["itest" "test"] ;; ["itest" "test"] ;; :injections [(require 'spyscope.core)] ;; http://www.jayway.com/2014/09/09/integration-testing-setup-with-midje-and-leiningen/ :aliases {"itest" ["midje" ":filters" "it"] ;;"src/clojure" "test" "itest" "test" ["midje"] "utest" ["midje" ":filters" "-it"]} )
true
;; ;; Copyright © 2011-2014 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. ;; ;; Contributors: ;; PI:NAME:<NAME>END_PI - initial implementation ;; PI:NAME:<NAME>END_PI - contributor ;; PI:NAME:<NAME>END_PI - contributor ;; Nice idea, but does not play with lein ancient ;; ;; (def alfresco-version "5.1.e") ;; (def alfresco-core-version "5.6") ;; (def spring-version "3.2.14.RELEASE") ;; (def spring-surf-version "5.8") ;; (def h2-version "1.4.190") ;; (def xml-apis-version-override "1.4.01") ;; (def junit-version-override "4.11") ;; (def cider-nrepl-version "0.11.0") ;; (def refactor-nrepl-version "1.2.0") ;; (def jetty-version "9.2.11.v20150529") ;; (def gorilla-repl-version "0.3.5-SNAPSHOT") ;; (def websocket-version "1.0") (defproject org.clojars.deas/lambdalf "1.10.0-SNAPSHOT" :title "lambdalf" :description "Lambdalf -- Clojure support for Alfresco, batteries included" :url "https://github.com/lambdalf/lambdalf" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.4.0" :repositories [["alfresco.public" "https://artifacts.alfresco.com/nexus/content/groups/public/"]] ;; To keep things simple for now, we put all the tooling here as well ;; http://jakemccrary.com/blog/2015/01/11/overview-of-my-leiningen-profiles-dot-clj/ ;; parinfer/0.1.0-SNAPSHOT/parinfer-0.1.0-SNAPSHOT :dependencies [[org.clojure/tools.logging "0.3.1"] [org.clojure/tools.namespace "0.2.10"] [org.clojure/tools.trace "0.7.9"] [org.clojure/clojure "1.9.0-alpha13"] [org.clojure/tools.nrepl "0.2.12"] ;; [com.gfredericks/debug-repl "0.0.7"] ;; [spyscope "0.1.5"] [evalive "1.1.0"] [org.clojure/java.classpath "0.2.3"] [org.clojure/java.jmx "0.3.1"] ;; schmetterling introduces deps conflicting with alfresco ;; [schmetterling "0.0.8"] ;; SNAPSHOTS do not build uberjars? [cider/cider-nrepl "0.14.0" #_~cider-nrepl-version] ; 8.0-SNAPSHOT"] [refactor-nrepl "1.2.0" #_~refactor-nrepl-version] ;; WARNING: do _not_ add test, provided or runtime dependencies ;; here as they will be included in the uberjar, regardless of scope. ;; See https://github.com/technomancy/leiningen/issues/741 for an ;; explanation of why this occurs. [com.stuartsierra/component "0.3.1"] ;; Weeding out deps here! [ring/ring-core "1.4.0" :exclusions [ring/ring-codec commons-fileupload crypto-random clj-time commons-io]] [clj-time "0.9.0" :exclusions [joda-time]] [ring/ring-codec "1.0.0" :exclusions [commons-codec]] [crypto-random "1.2.0" :exclusions [commons-codec]] [compojure "1.4.0" :exclusions [ring/ring-core]] [org.clojars.deas/gorilla-repl-ng "0.3.6" :exclusions [*/*] #_[http-kit org.slf4j/slf4j-api javax.servlet/servlet-api grimradical/clj-semver ch.qos.logback/logback-classic org.clojure/data.codec org.clojure/tools.logging]] ;; A ton of deps :exclusions [com.sun.jdmk/jmxtools] [ring/ring-servlet "1.4.0"] [org.clojure/data.json "0.2.6"] ;; [ring/ring-json "0.4.0"] ;; [cheshire "5.5.0" :exclusions [*/*]] ;; for gorilla websocket-relay ;; jackson-core "2.5.3", alfresco jackson-core-2.3.2 #_[com.fasterxml.jackson.dataformat/jackson-dataformat-smile "2.3.2" :exclusions [*/*]] #_[com.fasterxml.jackson.dataformat/jackson-dataformat-cbor "2.3.2" :exclusions [*/*]] [org.clojars.deas/gorilla-plot "0.2.0"] [org.clojars.deas/gorilla-middleware "0.1.2"] [clojail "1.0.6"] [com.cemerick/pomegranate "0.3.1"] [ring-middleware-format "0.7.0"] ;; TODO Untangle those two in gorilla-repl [http-kit "2.2.0"] [grimradical/clj-semver "0.3.0" :exclusions [org.clojure/clojure]] [ring-cors "0.1.8"] ;; Additional stuff for gorilla ;; incanter could add a whole lot of stuff for gorilla ;; [incanter/incanter-core "1.9.1"] ] :aot [gorilla-repl.servlet] ;; :aot [contentreich.ring-servlet] :javac-options ["-target" "1.7" "-source" "1.7"] :plugins [[cider/cider-nrepl "0.14.0"] [refactor-nrepl "1.2.0" #_~refactor-nrepl-version] ;; http://dev.clojure.org/jira/browse/NREPL-53 ;; [com.gfredericks/nrepl-53-monkeypatch "0.1.0"] ;; [lein-cljsbuild "1.1.0"] ;; [lein-figwheel "0.4.0"] ] :repl-options { :timeout 120000 :nrepl-middleware [;; com.gfredericks.debug-repl/wrap-debug-repl ;; [cider.nrepl.middleware.classpath/wrap-classpath ;; cider.nrepl.middleware.complete/wrap-complete ;; cider.nrepl.middleware.info/wrap-info ;; cider.nrepl.middleware.inspect/wrap-inspect ;; cider.nrepl.middleware.macroexpand/wrap-macroexpand ;; cider.nrepl.middleware.stacktrace/wrap-stacktrace ;; cider.nrepl.middleware.test/wrap-test ;; cider.nrepl.middleware.trace/wrap-trace ;; cider.nrepl.middleware.undef/wrap-undef] ] ;; :init-ns scratch ;; :init (create-application-context) } :profiles {:dev {:plugins [ ;; [lein-midje "3.1.3"] ] ;;[lein-amp "0.3.0"]]} :source-paths ["src/clojure"] ;; "dev" :dependencies [ [org.alfresco/alfresco-repository "5.1.e" :classifier "h2scripts" :exclusions [ commons-codec ;; commons-fileupload ]] ;; [spyscope "0.1.5"] [com.h2database/h2 "1.4.190" #_~h2-version] [clj-http "2.1.0" :exclusions [ commons-codec ] ] [org.eclipse.jetty/jetty-server "9.2.11.v20150529"] [org.eclipse.jetty.websocket/websocket-server "9.2.11.v20150529"] ;; [midje "1.8.3"] [org.eclipse.jetty/jetty-webapp "9.2.11.v20150529"] [org.eclipse.jetty/jetty-util "9.2.11.v20150529"] ]} ;; :uberjar { :aot :all } :test {:dependencies [ [org.alfresco/alfresco-repository "5.1.e" :classifier "h2scripts" :exclusions [ ;; commons-codec ;; commons-fileupload ]] [com.h2database/h2 "1.4.190" #_~h2-version] [clj-http "2.1.0"] [org.eclipse.jetty/jetty-server "9.2.11.v20150529"] [org.eclipse.jetty.websocket/websocket-server "9.2.11.v20150529"] [org.eclipse.jetty/jetty-webapp "9.2.11.v20150529"] [org.eclipse.jetty/jetty-util "9.2.11.v20150529"] [junit/junit "4.11"]]} :provided {:dependencies [ ;; [org.clojure/clojurescript "1.7.122"] ;; We need to fiddle around with the deps so the clojure deps chain shows up [org.alfresco/alfresco-core "5.6" :exclusions [ ;; commons-codec ;; joda-time ]] [org.alfresco/alfresco-data-model "5.1.e" ;; :exclusions [org.apache.tika/tika-parsers] ] [org.alfresco/alfresco-mbeans "5.1.e"] [org.alfresco/alfresco-remote-api "5.1.e"] [org.alfresco/alfresco-repository "5.1.e" :exclusions [commons-collections ;; commons-codec ;; joda-time ;; commons-fileupload ]] ;; You have to build the web-client yourself for now ;; "mvn -f pom-alfresco-web-client.xml install" in web-client/ ;; [org.alfresco/alfresco-web-client "5.1.e"#_~alfresco.version] [org.springframework/spring-context "3.2.14.RELEASE"] [org.springframework/spring-beans "3.2.14.RELEASE"] [org.springframework.extensions.surf/spring-webscripts "5.8" :exclusions [ ;; commons-fileupload ]] ;; The deps alfresco really wants ;; override wrong dep from core causing RTE when starting up the context [commons-collections "3.2.2"] ;; Weeding out fileupload, joda, commons-io does not work - comes in via clj(!) deps [commons-fileupload "1.3.1"] [joda-time "2.8.1"] [commons-io "2.4"] [commons-codec "1.10"] [javax.websocket/javax.websocket-api "1.0"] [javax.servlet/javax.servlet-api "3.1.0"] [xml-apis/xml-apis "1.4.01"]]}} ;; :aot [alfresco] :source-paths ["src/clojure"] :java-source-paths ["src/java"] :resource-paths ["src/resource"] ;; :amp-source-path "src/amp" ;; :amp-target-war [org.alfresco/alfresco "5.1.e"#_~alfresco.version :extension "war" :javac-target "1.7" ;; Beware !!! refactor-nrepl middleware can kick off midje integration tests! :test-paths ["itest" "test"] ;; ["itest" "test"] ;; :injections [(require 'spyscope.core)] ;; http://www.jayway.com/2014/09/09/integration-testing-setup-with-midje-and-leiningen/ :aliases {"itest" ["midje" ":filters" "it"] ;;"src/clojure" "test" "itest" "test" ["midje"] "utest" ["midje" ":filters" "-it"]} )
[ { "context": "reScript REPL with nREPL tooling.\"\n :author \"Chas Emerick\"}\n cemerick.piggieback\n (:require [clojure.t", "end": 130, "score": 0.9998847842216492, "start": 118, "tag": "NAME", "value": "Chas Emerick" } ]
server/target/cemerick/piggieback.clj
OctavioBR/healthcheck
0
(ns ^{:doc "nREPL middleware enabling the transparent use of a ClojureScript REPL with nREPL tooling." :author "Chas Emerick"} cemerick.piggieback (:require [clojure.tools.nrepl :as nrepl] (clojure.tools.nrepl [transport :as transport] [server :as server] [misc :refer (returning)] [middleware :refer (set-descriptor!)]) [clojure.tools.nrepl.middleware.load-file :as load-file] [clojure.tools.nrepl.middleware.interruptible-eval :as ieval] [clojure.tools.reader :as reader] [clojure.tools.reader.reader-types :as readers] [cljs.env :as env] [cljs.repl :as cljsrepl] [cljs.analyzer :as ana] [cljs.tagged-literals :as tags] [cljs.repl.rhino :as rhino]) (:import (org.mozilla.javascript Context ScriptableObject) java.io.StringReader)) (def ^:private ^:dynamic *cljs-repl-env* nil) (def ^:private ^:dynamic *eval* nil) (def ^:private ^:dynamic *cljs-repl-options* nil) (def ^:private ^:dynamic *original-clj-ns* nil) (defmacro ^:private squelch-rhino-context-error "Catches and silences the exception thrown by (Context/exit) when it is called without a corresponding (Context/enter). Needed because rhino/repl-env calls Context/enter without a corresponding Context/exit; it assumes: (a) the context will only ever be used on one thread (b) cljsrepl/repl will clean up the context when the command-line cljs repl exits" [& body] `(try ~@body (catch IllegalStateException e# (when-not (-> e# .getMessage (.contains "Context.exit without previous Context.enter")) (throw e#))))) (defmacro ^:private with-rhino-context [& body] `(try (Context/enter) ~@body (finally ; -tear-down for rhino environments always calls Context/exit, so we need ; to kill the resulting error to avoid an exception printing on :cljs/quit (squelch-rhino-context-error (Context/exit))))) (defn- map-stdout [rhino-env out] (ScriptableObject/putProperty (:scope rhino-env) "out" (Context/javaToJS out (:scope rhino-env)))) (defn ^{:deprecated true} rhino-repl-env "Returns a new Rhino ClojureScript REPL environment. This function is deprecated, and simply delegates to `cljs.repl.rhino/repl-env`." [] (assoc (rhino/repl-env) ::env/compiler (env/default-compiler-env))) (defn- quit-cljs-repl [] (squelch-rhino-context-error (cljsrepl/-tear-down *cljs-repl-env*)) (set! *cljs-repl-env* nil) (set! *eval* nil) (set! ana/*cljs-ns* 'cljs.user) (set! *ns* *original-clj-ns*) (set! *original-clj-ns* nil)) (defn cljs-eval "Evaluates the expression [expr] (should already be read) using the given ClojureScript REPL environment [repl-env] and a map of ClojureScript REPL options: :verbose, :warn-on-undeclared, and :special-fns, each with the same acceptable values and semantics as the \"regular\" ClojureScript REPL. This is generally not going to be used by end users; rather, as the basis of alternative (usually not-Rhino, e.g. node/V8) `eval` functions passed to `cljs-repl`." [repl-env expr {:keys [verbose warn-on-undeclared special-fns]}] (env/with-compiler-env (or (::env/compiler repl-env) (env/default-compiler-env)) (let [explicit-ns (when (:ns ieval/*msg*) (symbol (:ns ieval/*msg*))) ; need to let *cljs-ns* escape from the binding scope below iff it differs ; from any explicitly-specified :ns in the request msg escaping-ns (atom ana/*cljs-ns*)] (returning (with-bindings (merge {#'cljsrepl/*cljs-verbose* verbose #'ana/*cljs-warnings* (assoc ana/*cljs-warnings* :undeclared warn-on-undeclared)} (when explicit-ns {#'ana/*cljs-ns* explicit-ns})) (let [special-fns (merge cljsrepl/default-special-fns special-fns) set-ns! #(when (not= explicit-ns ana/*cljs-ns*) (reset! escaping-ns ana/*cljs-ns*))] (cond (= expr :cljs/quit) (do (quit-cljs-repl) :cljs/quit) (and (seq? expr) (find special-fns (first expr))) (returning (apply (get special-fns (first expr)) repl-env (rest expr)) (set-ns!)) :default (let [ret (cljsrepl/evaluate-form repl-env {:context :statement :locals {} :ns (ana/get-namespace ana/*cljs-ns*)} "<cljs repl>" expr (#'cljsrepl/wrap-fn expr))] (set-ns!) (try (read-string ret) (catch Exception _ (when (string? ret) (println ret)))))))) (when *original-clj-ns* (set! ana/*cljs-ns* @escaping-ns) (set! *ns* (create-ns @escaping-ns))))))) (defn- wrap-exprs [& exprs] (for [expr exprs] `(#'*eval* @#'*cljs-repl-env* '~expr @#'*cljs-repl-options*))) (defn- load-file-contents [repl-env code file-path file-name] (binding [ana/*cljs-ns* 'cljs.user] (cljs.repl/load-stream repl-env file-path (java.io.StringReader. code)))) (defn- load-file-code [code file-path file-name] (wrap-exprs (list `load-file-contents code file-path file-name))) (defn- rhino-repl-env? [repl-env] (instance? cljs.repl.rhino.RhinoEnv repl-env)) (defn- setup-rhino-env [rhino-env] (with-rhino-context (doto rhino-env cljsrepl/-setup ; rhino/rhino-setup maps System/out to "out" and therefore the target of ; cljs' *print-fn*! :-( (map-stdout *out*) ; rhino/repl-env calls (Context/enter) without a (Context/exit) (squelch-rhino-context-error (Context/exit))))) (defn cljs-repl "Starts a ClojureScript REPL over top an nREPL session. Accepts all options usually accepted by e.g. cljs.repl/repl. Also accepts optional configuration via kwargs: :repl-env - a ClojureScript REPL environment (defaults to a new Rhino environment [from `rhino-repl-env`]) :eval - a function of three arguments ([repl-env expression cljs-repl-options], corresponding to `cljs-eval`) that is called once for each ClojureScript expression to be evaluated." [& {:keys [repl-env eval] :as options}] (let [repl-env (or repl-env (rhino-repl-env)) eval (or eval (when (rhino-repl-env? repl-env) #(with-rhino-context (apply cljs-eval %&))) #(apply cljs-eval %&))] ; :warn-on-undeclared default from ClojureScript's script/repljs (set! *cljs-repl-options* (-> (merge {:warn-on-undeclared true} options) (update-in [:special-fns] assoc `load-file-contents #'load-file-contents) (dissoc :repl-env :eval))) (set! *cljs-repl-env* repl-env) (set! *eval* eval) (set! ana/*cljs-ns* 'cljs.user) (set! *original-clj-ns* *ns*) (env/with-compiler-env (or (::env/compiler repl-env) (env/default-compiler-env)) (if (rhino-repl-env? repl-env) (setup-rhino-env repl-env) (cljsrepl/-setup repl-env))) (print "Type `") (pr :cljs/quit) (println "` to stop the ClojureScript REPL"))) (defn- prep-code [{:keys [code session ns] :as msg}] (let [code (if-not (string? code) code (let [str-reader (StringReader. code) end (Object.) ns-sym (or (when ns (symbol ns)) ana/*cljs-ns*) repl-env (@session #'*cljs-repl-env*)] (->> #(env/with-compiler-env (or (::env/compiler repl-env) (env/default-compiler-env)) (binding [ana/*cljs-ns* ns-sym *ns* (create-ns ns-sym) reader/*data-readers* tags/*cljs-data-readers* reader/*alias-map* (apply merge ((juxt :requires :require-macros) (ana/get-namespace ns-sym)))] (try (let [rdr (readers/source-logging-push-back-reader (java.io.PushbackReader. str-reader) 1 "NO_SOURCE_FILE")] (reader/read rdr nil end)) (catch Exception e (binding [*out* (@session #'*err*)] (println (.getMessage e)) ::error))))) repeatedly (take-while (complement #{end})) (remove #{::error}))))] (assoc msg :code (apply wrap-exprs code)))) (defn- cljs-ns-transport [transport] (reify clojure.tools.nrepl.transport.Transport (recv [this] (transport/recv transport)) (recv [this timeout] (transport/recv transport timeout)) (send [this resp] (let [resp (if (and *cljs-repl-env* (:ns resp)) (assoc resp :ns (str ana/*cljs-ns*)) resp)] (transport/send transport resp))))) (defn wrap-cljs-repl [h] (fn [{:keys [op session transport] :as msg}] (let [cljs-active? (@session #'*cljs-repl-env*) msg (assoc msg :transport (cljs-ns-transport transport)) msg (if (and cljs-active? (= op "eval")) (prep-code msg) msg)] ; ensure that bindings exist so cljs-repl can set! 'em (when-not (contains? @session #'*cljs-repl-env*) (swap! session (partial merge {#'*cljs-repl-env* *cljs-repl-env* #'*eval* *eval* #'*cljs-repl-options* *cljs-repl-options* #'ana/*cljs-ns* ana/*cljs-ns* #'*original-clj-ns* nil}))) (with-bindings (if cljs-active? {#'load-file/load-file-code load-file-code} {}) (h msg))))) (set-descriptor! #'wrap-cljs-repl {:requires #{"clone"} :expects #{"load-file" "eval"} :handles {}})
38393
(ns ^{:doc "nREPL middleware enabling the transparent use of a ClojureScript REPL with nREPL tooling." :author "<NAME>"} cemerick.piggieback (:require [clojure.tools.nrepl :as nrepl] (clojure.tools.nrepl [transport :as transport] [server :as server] [misc :refer (returning)] [middleware :refer (set-descriptor!)]) [clojure.tools.nrepl.middleware.load-file :as load-file] [clojure.tools.nrepl.middleware.interruptible-eval :as ieval] [clojure.tools.reader :as reader] [clojure.tools.reader.reader-types :as readers] [cljs.env :as env] [cljs.repl :as cljsrepl] [cljs.analyzer :as ana] [cljs.tagged-literals :as tags] [cljs.repl.rhino :as rhino]) (:import (org.mozilla.javascript Context ScriptableObject) java.io.StringReader)) (def ^:private ^:dynamic *cljs-repl-env* nil) (def ^:private ^:dynamic *eval* nil) (def ^:private ^:dynamic *cljs-repl-options* nil) (def ^:private ^:dynamic *original-clj-ns* nil) (defmacro ^:private squelch-rhino-context-error "Catches and silences the exception thrown by (Context/exit) when it is called without a corresponding (Context/enter). Needed because rhino/repl-env calls Context/enter without a corresponding Context/exit; it assumes: (a) the context will only ever be used on one thread (b) cljsrepl/repl will clean up the context when the command-line cljs repl exits" [& body] `(try ~@body (catch IllegalStateException e# (when-not (-> e# .getMessage (.contains "Context.exit without previous Context.enter")) (throw e#))))) (defmacro ^:private with-rhino-context [& body] `(try (Context/enter) ~@body (finally ; -tear-down for rhino environments always calls Context/exit, so we need ; to kill the resulting error to avoid an exception printing on :cljs/quit (squelch-rhino-context-error (Context/exit))))) (defn- map-stdout [rhino-env out] (ScriptableObject/putProperty (:scope rhino-env) "out" (Context/javaToJS out (:scope rhino-env)))) (defn ^{:deprecated true} rhino-repl-env "Returns a new Rhino ClojureScript REPL environment. This function is deprecated, and simply delegates to `cljs.repl.rhino/repl-env`." [] (assoc (rhino/repl-env) ::env/compiler (env/default-compiler-env))) (defn- quit-cljs-repl [] (squelch-rhino-context-error (cljsrepl/-tear-down *cljs-repl-env*)) (set! *cljs-repl-env* nil) (set! *eval* nil) (set! ana/*cljs-ns* 'cljs.user) (set! *ns* *original-clj-ns*) (set! *original-clj-ns* nil)) (defn cljs-eval "Evaluates the expression [expr] (should already be read) using the given ClojureScript REPL environment [repl-env] and a map of ClojureScript REPL options: :verbose, :warn-on-undeclared, and :special-fns, each with the same acceptable values and semantics as the \"regular\" ClojureScript REPL. This is generally not going to be used by end users; rather, as the basis of alternative (usually not-Rhino, e.g. node/V8) `eval` functions passed to `cljs-repl`." [repl-env expr {:keys [verbose warn-on-undeclared special-fns]}] (env/with-compiler-env (or (::env/compiler repl-env) (env/default-compiler-env)) (let [explicit-ns (when (:ns ieval/*msg*) (symbol (:ns ieval/*msg*))) ; need to let *cljs-ns* escape from the binding scope below iff it differs ; from any explicitly-specified :ns in the request msg escaping-ns (atom ana/*cljs-ns*)] (returning (with-bindings (merge {#'cljsrepl/*cljs-verbose* verbose #'ana/*cljs-warnings* (assoc ana/*cljs-warnings* :undeclared warn-on-undeclared)} (when explicit-ns {#'ana/*cljs-ns* explicit-ns})) (let [special-fns (merge cljsrepl/default-special-fns special-fns) set-ns! #(when (not= explicit-ns ana/*cljs-ns*) (reset! escaping-ns ana/*cljs-ns*))] (cond (= expr :cljs/quit) (do (quit-cljs-repl) :cljs/quit) (and (seq? expr) (find special-fns (first expr))) (returning (apply (get special-fns (first expr)) repl-env (rest expr)) (set-ns!)) :default (let [ret (cljsrepl/evaluate-form repl-env {:context :statement :locals {} :ns (ana/get-namespace ana/*cljs-ns*)} "<cljs repl>" expr (#'cljsrepl/wrap-fn expr))] (set-ns!) (try (read-string ret) (catch Exception _ (when (string? ret) (println ret)))))))) (when *original-clj-ns* (set! ana/*cljs-ns* @escaping-ns) (set! *ns* (create-ns @escaping-ns))))))) (defn- wrap-exprs [& exprs] (for [expr exprs] `(#'*eval* @#'*cljs-repl-env* '~expr @#'*cljs-repl-options*))) (defn- load-file-contents [repl-env code file-path file-name] (binding [ana/*cljs-ns* 'cljs.user] (cljs.repl/load-stream repl-env file-path (java.io.StringReader. code)))) (defn- load-file-code [code file-path file-name] (wrap-exprs (list `load-file-contents code file-path file-name))) (defn- rhino-repl-env? [repl-env] (instance? cljs.repl.rhino.RhinoEnv repl-env)) (defn- setup-rhino-env [rhino-env] (with-rhino-context (doto rhino-env cljsrepl/-setup ; rhino/rhino-setup maps System/out to "out" and therefore the target of ; cljs' *print-fn*! :-( (map-stdout *out*) ; rhino/repl-env calls (Context/enter) without a (Context/exit) (squelch-rhino-context-error (Context/exit))))) (defn cljs-repl "Starts a ClojureScript REPL over top an nREPL session. Accepts all options usually accepted by e.g. cljs.repl/repl. Also accepts optional configuration via kwargs: :repl-env - a ClojureScript REPL environment (defaults to a new Rhino environment [from `rhino-repl-env`]) :eval - a function of three arguments ([repl-env expression cljs-repl-options], corresponding to `cljs-eval`) that is called once for each ClojureScript expression to be evaluated." [& {:keys [repl-env eval] :as options}] (let [repl-env (or repl-env (rhino-repl-env)) eval (or eval (when (rhino-repl-env? repl-env) #(with-rhino-context (apply cljs-eval %&))) #(apply cljs-eval %&))] ; :warn-on-undeclared default from ClojureScript's script/repljs (set! *cljs-repl-options* (-> (merge {:warn-on-undeclared true} options) (update-in [:special-fns] assoc `load-file-contents #'load-file-contents) (dissoc :repl-env :eval))) (set! *cljs-repl-env* repl-env) (set! *eval* eval) (set! ana/*cljs-ns* 'cljs.user) (set! *original-clj-ns* *ns*) (env/with-compiler-env (or (::env/compiler repl-env) (env/default-compiler-env)) (if (rhino-repl-env? repl-env) (setup-rhino-env repl-env) (cljsrepl/-setup repl-env))) (print "Type `") (pr :cljs/quit) (println "` to stop the ClojureScript REPL"))) (defn- prep-code [{:keys [code session ns] :as msg}] (let [code (if-not (string? code) code (let [str-reader (StringReader. code) end (Object.) ns-sym (or (when ns (symbol ns)) ana/*cljs-ns*) repl-env (@session #'*cljs-repl-env*)] (->> #(env/with-compiler-env (or (::env/compiler repl-env) (env/default-compiler-env)) (binding [ana/*cljs-ns* ns-sym *ns* (create-ns ns-sym) reader/*data-readers* tags/*cljs-data-readers* reader/*alias-map* (apply merge ((juxt :requires :require-macros) (ana/get-namespace ns-sym)))] (try (let [rdr (readers/source-logging-push-back-reader (java.io.PushbackReader. str-reader) 1 "NO_SOURCE_FILE")] (reader/read rdr nil end)) (catch Exception e (binding [*out* (@session #'*err*)] (println (.getMessage e)) ::error))))) repeatedly (take-while (complement #{end})) (remove #{::error}))))] (assoc msg :code (apply wrap-exprs code)))) (defn- cljs-ns-transport [transport] (reify clojure.tools.nrepl.transport.Transport (recv [this] (transport/recv transport)) (recv [this timeout] (transport/recv transport timeout)) (send [this resp] (let [resp (if (and *cljs-repl-env* (:ns resp)) (assoc resp :ns (str ana/*cljs-ns*)) resp)] (transport/send transport resp))))) (defn wrap-cljs-repl [h] (fn [{:keys [op session transport] :as msg}] (let [cljs-active? (@session #'*cljs-repl-env*) msg (assoc msg :transport (cljs-ns-transport transport)) msg (if (and cljs-active? (= op "eval")) (prep-code msg) msg)] ; ensure that bindings exist so cljs-repl can set! 'em (when-not (contains? @session #'*cljs-repl-env*) (swap! session (partial merge {#'*cljs-repl-env* *cljs-repl-env* #'*eval* *eval* #'*cljs-repl-options* *cljs-repl-options* #'ana/*cljs-ns* ana/*cljs-ns* #'*original-clj-ns* nil}))) (with-bindings (if cljs-active? {#'load-file/load-file-code load-file-code} {}) (h msg))))) (set-descriptor! #'wrap-cljs-repl {:requires #{"clone"} :expects #{"load-file" "eval"} :handles {}})
true
(ns ^{:doc "nREPL middleware enabling the transparent use of a ClojureScript REPL with nREPL tooling." :author "PI:NAME:<NAME>END_PI"} cemerick.piggieback (:require [clojure.tools.nrepl :as nrepl] (clojure.tools.nrepl [transport :as transport] [server :as server] [misc :refer (returning)] [middleware :refer (set-descriptor!)]) [clojure.tools.nrepl.middleware.load-file :as load-file] [clojure.tools.nrepl.middleware.interruptible-eval :as ieval] [clojure.tools.reader :as reader] [clojure.tools.reader.reader-types :as readers] [cljs.env :as env] [cljs.repl :as cljsrepl] [cljs.analyzer :as ana] [cljs.tagged-literals :as tags] [cljs.repl.rhino :as rhino]) (:import (org.mozilla.javascript Context ScriptableObject) java.io.StringReader)) (def ^:private ^:dynamic *cljs-repl-env* nil) (def ^:private ^:dynamic *eval* nil) (def ^:private ^:dynamic *cljs-repl-options* nil) (def ^:private ^:dynamic *original-clj-ns* nil) (defmacro ^:private squelch-rhino-context-error "Catches and silences the exception thrown by (Context/exit) when it is called without a corresponding (Context/enter). Needed because rhino/repl-env calls Context/enter without a corresponding Context/exit; it assumes: (a) the context will only ever be used on one thread (b) cljsrepl/repl will clean up the context when the command-line cljs repl exits" [& body] `(try ~@body (catch IllegalStateException e# (when-not (-> e# .getMessage (.contains "Context.exit without previous Context.enter")) (throw e#))))) (defmacro ^:private with-rhino-context [& body] `(try (Context/enter) ~@body (finally ; -tear-down for rhino environments always calls Context/exit, so we need ; to kill the resulting error to avoid an exception printing on :cljs/quit (squelch-rhino-context-error (Context/exit))))) (defn- map-stdout [rhino-env out] (ScriptableObject/putProperty (:scope rhino-env) "out" (Context/javaToJS out (:scope rhino-env)))) (defn ^{:deprecated true} rhino-repl-env "Returns a new Rhino ClojureScript REPL environment. This function is deprecated, and simply delegates to `cljs.repl.rhino/repl-env`." [] (assoc (rhino/repl-env) ::env/compiler (env/default-compiler-env))) (defn- quit-cljs-repl [] (squelch-rhino-context-error (cljsrepl/-tear-down *cljs-repl-env*)) (set! *cljs-repl-env* nil) (set! *eval* nil) (set! ana/*cljs-ns* 'cljs.user) (set! *ns* *original-clj-ns*) (set! *original-clj-ns* nil)) (defn cljs-eval "Evaluates the expression [expr] (should already be read) using the given ClojureScript REPL environment [repl-env] and a map of ClojureScript REPL options: :verbose, :warn-on-undeclared, and :special-fns, each with the same acceptable values and semantics as the \"regular\" ClojureScript REPL. This is generally not going to be used by end users; rather, as the basis of alternative (usually not-Rhino, e.g. node/V8) `eval` functions passed to `cljs-repl`." [repl-env expr {:keys [verbose warn-on-undeclared special-fns]}] (env/with-compiler-env (or (::env/compiler repl-env) (env/default-compiler-env)) (let [explicit-ns (when (:ns ieval/*msg*) (symbol (:ns ieval/*msg*))) ; need to let *cljs-ns* escape from the binding scope below iff it differs ; from any explicitly-specified :ns in the request msg escaping-ns (atom ana/*cljs-ns*)] (returning (with-bindings (merge {#'cljsrepl/*cljs-verbose* verbose #'ana/*cljs-warnings* (assoc ana/*cljs-warnings* :undeclared warn-on-undeclared)} (when explicit-ns {#'ana/*cljs-ns* explicit-ns})) (let [special-fns (merge cljsrepl/default-special-fns special-fns) set-ns! #(when (not= explicit-ns ana/*cljs-ns*) (reset! escaping-ns ana/*cljs-ns*))] (cond (= expr :cljs/quit) (do (quit-cljs-repl) :cljs/quit) (and (seq? expr) (find special-fns (first expr))) (returning (apply (get special-fns (first expr)) repl-env (rest expr)) (set-ns!)) :default (let [ret (cljsrepl/evaluate-form repl-env {:context :statement :locals {} :ns (ana/get-namespace ana/*cljs-ns*)} "<cljs repl>" expr (#'cljsrepl/wrap-fn expr))] (set-ns!) (try (read-string ret) (catch Exception _ (when (string? ret) (println ret)))))))) (when *original-clj-ns* (set! ana/*cljs-ns* @escaping-ns) (set! *ns* (create-ns @escaping-ns))))))) (defn- wrap-exprs [& exprs] (for [expr exprs] `(#'*eval* @#'*cljs-repl-env* '~expr @#'*cljs-repl-options*))) (defn- load-file-contents [repl-env code file-path file-name] (binding [ana/*cljs-ns* 'cljs.user] (cljs.repl/load-stream repl-env file-path (java.io.StringReader. code)))) (defn- load-file-code [code file-path file-name] (wrap-exprs (list `load-file-contents code file-path file-name))) (defn- rhino-repl-env? [repl-env] (instance? cljs.repl.rhino.RhinoEnv repl-env)) (defn- setup-rhino-env [rhino-env] (with-rhino-context (doto rhino-env cljsrepl/-setup ; rhino/rhino-setup maps System/out to "out" and therefore the target of ; cljs' *print-fn*! :-( (map-stdout *out*) ; rhino/repl-env calls (Context/enter) without a (Context/exit) (squelch-rhino-context-error (Context/exit))))) (defn cljs-repl "Starts a ClojureScript REPL over top an nREPL session. Accepts all options usually accepted by e.g. cljs.repl/repl. Also accepts optional configuration via kwargs: :repl-env - a ClojureScript REPL environment (defaults to a new Rhino environment [from `rhino-repl-env`]) :eval - a function of three arguments ([repl-env expression cljs-repl-options], corresponding to `cljs-eval`) that is called once for each ClojureScript expression to be evaluated." [& {:keys [repl-env eval] :as options}] (let [repl-env (or repl-env (rhino-repl-env)) eval (or eval (when (rhino-repl-env? repl-env) #(with-rhino-context (apply cljs-eval %&))) #(apply cljs-eval %&))] ; :warn-on-undeclared default from ClojureScript's script/repljs (set! *cljs-repl-options* (-> (merge {:warn-on-undeclared true} options) (update-in [:special-fns] assoc `load-file-contents #'load-file-contents) (dissoc :repl-env :eval))) (set! *cljs-repl-env* repl-env) (set! *eval* eval) (set! ana/*cljs-ns* 'cljs.user) (set! *original-clj-ns* *ns*) (env/with-compiler-env (or (::env/compiler repl-env) (env/default-compiler-env)) (if (rhino-repl-env? repl-env) (setup-rhino-env repl-env) (cljsrepl/-setup repl-env))) (print "Type `") (pr :cljs/quit) (println "` to stop the ClojureScript REPL"))) (defn- prep-code [{:keys [code session ns] :as msg}] (let [code (if-not (string? code) code (let [str-reader (StringReader. code) end (Object.) ns-sym (or (when ns (symbol ns)) ana/*cljs-ns*) repl-env (@session #'*cljs-repl-env*)] (->> #(env/with-compiler-env (or (::env/compiler repl-env) (env/default-compiler-env)) (binding [ana/*cljs-ns* ns-sym *ns* (create-ns ns-sym) reader/*data-readers* tags/*cljs-data-readers* reader/*alias-map* (apply merge ((juxt :requires :require-macros) (ana/get-namespace ns-sym)))] (try (let [rdr (readers/source-logging-push-back-reader (java.io.PushbackReader. str-reader) 1 "NO_SOURCE_FILE")] (reader/read rdr nil end)) (catch Exception e (binding [*out* (@session #'*err*)] (println (.getMessage e)) ::error))))) repeatedly (take-while (complement #{end})) (remove #{::error}))))] (assoc msg :code (apply wrap-exprs code)))) (defn- cljs-ns-transport [transport] (reify clojure.tools.nrepl.transport.Transport (recv [this] (transport/recv transport)) (recv [this timeout] (transport/recv transport timeout)) (send [this resp] (let [resp (if (and *cljs-repl-env* (:ns resp)) (assoc resp :ns (str ana/*cljs-ns*)) resp)] (transport/send transport resp))))) (defn wrap-cljs-repl [h] (fn [{:keys [op session transport] :as msg}] (let [cljs-active? (@session #'*cljs-repl-env*) msg (assoc msg :transport (cljs-ns-transport transport)) msg (if (and cljs-active? (= op "eval")) (prep-code msg) msg)] ; ensure that bindings exist so cljs-repl can set! 'em (when-not (contains? @session #'*cljs-repl-env*) (swap! session (partial merge {#'*cljs-repl-env* *cljs-repl-env* #'*eval* *eval* #'*cljs-repl-options* *cljs-repl-options* #'ana/*cljs-ns* ana/*cljs-ns* #'*original-clj-ns* nil}))) (with-bindings (if cljs-active? {#'load-file/load-file-code load-file-code} {}) (h msg))))) (set-descriptor! #'wrap-cljs-repl {:requires #{"clone"} :expects #{"load-file" "eval"} :handles {}})
[ { "context": "\" \"VipObject.0.Person.0.DateOfBirth.1\"\n \"Barak\" \"VipObject.0.Person.0.FirstName.2\"\n \"Obama", "end": 2217, "score": 0.677727222442627, "start": 2215, "tag": "NAME", "value": "ak" } ]
test/vip/data_processor/db/translations/v5_2/people_postgres_test.clj
votinginfoproject/data-processor
10
(ns vip.data-processor.db.translations.v5-2.people-postgres-test (:require [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.postgres :as postgres] [vip.data-processor.db.translations.v5-2.people :as p] [vip.data-processor.errors.process :as process] [vip.data-processor.pipeline :as pipeline] [vip.data-processor.validation.csv :as csv] [vip.data-processor.validation.data-spec :as data-spec] [vip.data-processor.validation.data-spec.v5-2 :as v5-2] [clojure.core.async :as a])) (use-fixtures :once setup-postgres) (deftest ^:postgres candidates-transforms-test (testing "person.txt is loaded and transformed" (let [errors-chan (a/chan 100) ctx {:csv-source-file-paths (csv-inputs ["5-2/contact_information.txt" "5-2/person.txt"]) :errors-chan errors-chan :spec-version "5.2" :spec-family "5.2" :pipeline [postgres/start-run (data-spec/add-data-specs v5-2/data-specs) postgres/prep-v5-2-run process/process-v5-validations csv/load-csvs p/transformer]} out-ctx (pipeline/run-pipeline ctx) errors (all-errors errors-chan)] (assert-no-problems errors {}) (are-xml-tree-values out-ctx "per50001" "VipObject.0.Person.0.id" "ci10861a" "VipObject.0.Person.0.ContactInformation.0.label" "1600 Pennsylvania Ave NW" "VipObject.0.Person.0.ContactInformation.0.AddressLine.0" "Washington" "VipObject.0.Person.0.ContactInformation.0.AddressLine.1" "DC 20006 USA" "VipObject.0.Person.0.ContactInformation.0.AddressLine.2" "Head Southeast of the General Rochambeau statue" "VipObject.0.Person.0.ContactInformation.0.Directions.3.Text.0" "en" "VipObject.0.Person.0.ContactInformation.0.Directions.3.Text.0.language" "38.899" "VipObject.0.Person.0.ContactInformation.0.LatLng.8.Latitude.0" "1961-08-04" "VipObject.0.Person.0.DateOfBirth.1" "Barak" "VipObject.0.Person.0.FirstName.2" "Obama" "VipObject.0.Person.0.LastName.4" "The Rock" "VipObject.0.Person.0.Nickname.6" "par002" "VipObject.0.Person.0.PartyId.7" "Mr. President" "VipObject.0.Person.0.Title.10.Text.0" "en" "VipObject.0.Person.0.Title.10.Text.0.language"))))
115294
(ns vip.data-processor.db.translations.v5-2.people-postgres-test (:require [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.postgres :as postgres] [vip.data-processor.db.translations.v5-2.people :as p] [vip.data-processor.errors.process :as process] [vip.data-processor.pipeline :as pipeline] [vip.data-processor.validation.csv :as csv] [vip.data-processor.validation.data-spec :as data-spec] [vip.data-processor.validation.data-spec.v5-2 :as v5-2] [clojure.core.async :as a])) (use-fixtures :once setup-postgres) (deftest ^:postgres candidates-transforms-test (testing "person.txt is loaded and transformed" (let [errors-chan (a/chan 100) ctx {:csv-source-file-paths (csv-inputs ["5-2/contact_information.txt" "5-2/person.txt"]) :errors-chan errors-chan :spec-version "5.2" :spec-family "5.2" :pipeline [postgres/start-run (data-spec/add-data-specs v5-2/data-specs) postgres/prep-v5-2-run process/process-v5-validations csv/load-csvs p/transformer]} out-ctx (pipeline/run-pipeline ctx) errors (all-errors errors-chan)] (assert-no-problems errors {}) (are-xml-tree-values out-ctx "per50001" "VipObject.0.Person.0.id" "ci10861a" "VipObject.0.Person.0.ContactInformation.0.label" "1600 Pennsylvania Ave NW" "VipObject.0.Person.0.ContactInformation.0.AddressLine.0" "Washington" "VipObject.0.Person.0.ContactInformation.0.AddressLine.1" "DC 20006 USA" "VipObject.0.Person.0.ContactInformation.0.AddressLine.2" "Head Southeast of the General Rochambeau statue" "VipObject.0.Person.0.ContactInformation.0.Directions.3.Text.0" "en" "VipObject.0.Person.0.ContactInformation.0.Directions.3.Text.0.language" "38.899" "VipObject.0.Person.0.ContactInformation.0.LatLng.8.Latitude.0" "1961-08-04" "VipObject.0.Person.0.DateOfBirth.1" "Bar<NAME>" "VipObject.0.Person.0.FirstName.2" "Obama" "VipObject.0.Person.0.LastName.4" "The Rock" "VipObject.0.Person.0.Nickname.6" "par002" "VipObject.0.Person.0.PartyId.7" "Mr. President" "VipObject.0.Person.0.Title.10.Text.0" "en" "VipObject.0.Person.0.Title.10.Text.0.language"))))
true
(ns vip.data-processor.db.translations.v5-2.people-postgres-test (:require [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.postgres :as postgres] [vip.data-processor.db.translations.v5-2.people :as p] [vip.data-processor.errors.process :as process] [vip.data-processor.pipeline :as pipeline] [vip.data-processor.validation.csv :as csv] [vip.data-processor.validation.data-spec :as data-spec] [vip.data-processor.validation.data-spec.v5-2 :as v5-2] [clojure.core.async :as a])) (use-fixtures :once setup-postgres) (deftest ^:postgres candidates-transforms-test (testing "person.txt is loaded and transformed" (let [errors-chan (a/chan 100) ctx {:csv-source-file-paths (csv-inputs ["5-2/contact_information.txt" "5-2/person.txt"]) :errors-chan errors-chan :spec-version "5.2" :spec-family "5.2" :pipeline [postgres/start-run (data-spec/add-data-specs v5-2/data-specs) postgres/prep-v5-2-run process/process-v5-validations csv/load-csvs p/transformer]} out-ctx (pipeline/run-pipeline ctx) errors (all-errors errors-chan)] (assert-no-problems errors {}) (are-xml-tree-values out-ctx "per50001" "VipObject.0.Person.0.id" "ci10861a" "VipObject.0.Person.0.ContactInformation.0.label" "1600 Pennsylvania Ave NW" "VipObject.0.Person.0.ContactInformation.0.AddressLine.0" "Washington" "VipObject.0.Person.0.ContactInformation.0.AddressLine.1" "DC 20006 USA" "VipObject.0.Person.0.ContactInformation.0.AddressLine.2" "Head Southeast of the General Rochambeau statue" "VipObject.0.Person.0.ContactInformation.0.Directions.3.Text.0" "en" "VipObject.0.Person.0.ContactInformation.0.Directions.3.Text.0.language" "38.899" "VipObject.0.Person.0.ContactInformation.0.LatLng.8.Latitude.0" "1961-08-04" "VipObject.0.Person.0.DateOfBirth.1" "BarPI:NAME:<NAME>END_PI" "VipObject.0.Person.0.FirstName.2" "Obama" "VipObject.0.Person.0.LastName.4" "The Rock" "VipObject.0.Person.0.Nickname.6" "par002" "VipObject.0.Person.0.PartyId.7" "Mr. President" "VipObject.0.Person.0.Title.10.Text.0" "en" "VipObject.0.Person.0.Title.10.Text.0.language"))))
[ { "context": " \"3\"} [1 3])\n\n (are\n [q ret]\n (= (grep q [\"fred\" \"bob\" \"ethel\"]) ret)\n\n 'fred [\"fred\"]\n 'b", "end": 345, "score": 0.9950394630432129, "start": 341, "tag": "NAME", "value": "fred" }, { "context": "\n (are\n [q ret]\n (= (grep q [\"fred\" \"bob\" \"ethel\"]) ret)\n\n 'fred [\"fred\"]\n 'bo* [\"bob\"]\n ", "end": 359, "score": 0.648945689201355, "start": 354, "tag": "NAME", "value": "ethel" }, { "context": "(grep q [\"fred\" \"bob\" \"ethel\"]) ret)\n\n 'fred [\"fred\"]\n 'bo* [\"bob\"]\n #\"(fr|)e.*\" [\"fred\" \"eth", "end": 385, "score": 0.9990552067756653, "start": 381, "tag": "NAME", "value": "fred" }, { "context": "b\" \"ethel\"]) ret)\n\n 'fred [\"fred\"]\n 'bo* [\"bob\"]\n #\"(fr|)e.*\" [\"fred\" \"ethel\"]\n '*thel [", "end": 403, "score": 0.9118677377700806, "start": 400, "tag": "NAME", "value": "bob" }, { "context": "red [\"fred\"]\n 'bo* [\"bob\"]\n #\"(fr|)e.*\" [\"fred\" \"ethel\"]\n '*thel [\"ethel\"])\n\n (let [fred {:", "end": 429, "score": 0.9964331388473511, "start": 425, "tag": "NAME", "value": "fred" }, { "context": "red\"]\n 'bo* [\"bob\"]\n #\"(fr|)e.*\" [\"fred\" \"ethel\"]\n '*thel [\"ethel\"])\n\n (let [fred {:name \"fr", "end": 437, "score": 0.9474292993545532, "start": 432, "tag": "NAME", "value": "ethel" }, { "context": " #\"(fr|)e.*\" [\"fred\" \"ethel\"]\n '*thel [\"ethel\"])\n\n (let [fred {:name \"fred\"\n :fri", "end": 459, "score": 0.6975953578948975, "start": 456, "tag": "NAME", "value": "hel" }, { "context": "[\"fred\" \"ethel\"]\n '*thel [\"ethel\"])\n\n (let [fred {:name \"fred\"\n :friends #{\"bob\"}\n ", "end": 476, "score": 0.6295965909957886, "start": 473, "tag": "NAME", "value": "red" }, { "context": "el\"]\n '*thel [\"ethel\"])\n\n (let [fred {:name \"fred\"\n :friends #{\"bob\"}\n :a", "end": 489, "score": 0.9995879530906677, "start": 485, "tag": "NAME", "value": "fred" }, { "context": "let [fred {:name \"fred\"\n :friends #{\"bob\"}\n :age 22}\n\n bob {:name \"bob", "end": 520, "score": 0.9959790706634521, "start": 517, "tag": "NAME", "value": "bob" }, { "context": "bob\"}\n :age 22}\n\n bob {:name \"bob\"\n :friends #{\"fred\" \"mary\"}\n ", "end": 570, "score": 0.9996352195739746, "start": 567, "tag": "NAME", "value": "bob" }, { "context": " bob {:name \"bob\"\n :friends #{\"fred\" \"mary\"}\n :age 60}\n\n mary {:na", "end": 601, "score": 0.9993482828140259, "start": 597, "tag": "NAME", "value": "fred" }, { "context": " bob {:name \"bob\"\n :friends #{\"fred\" \"mary\"}\n :age 60}\n\n mary {:name \"mar", "end": 608, "score": 0.9994316697120667, "start": 604, "tag": "NAME", "value": "mary" }, { "context": "ds #{\"fred\" \"mary\"}\n :age 60}\n\n mary {:name \"mary\"\n :friends #{\"fred\"}", "end": 643, "score": 0.6566531658172607, "start": 642, "tag": "NAME", "value": "m" }, { "context": "ary\"}\n :age 60}\n\n mary {:name \"mary\"\n :friends #{\"fred\"}\n :", "end": 659, "score": 0.9996901154518127, "start": 655, "tag": "NAME", "value": "mary" }, { "context": " mary {:name \"mary\"\n :friends #{\"fred\"}\n :age 82}]\n (are\n [q ret]\n", "end": 691, "score": 0.9992886781692505, "start": 687, "tag": "NAME", "value": "fred" }, { "context": "age 82}]\n (are\n [q ret]\n (= (grep q [fred bob mary]) ret)\n\n \"fred\" [fred bob mary]\n", "end": 760, "score": 0.5764804482460022, "start": 759, "tag": "NAME", "value": "f" }, { "context": "]\n (= (grep q [fred bob mary]) ret)\n\n \"fred\" [fred bob mary]\n\n {:name \"fred\"} [fred]\n ", "end": 792, "score": 0.7628238201141357, "start": 789, "tag": "NAME", "value": "red" }, { "context": "ret)\n\n \"fred\" [fred bob mary]\n\n {:name \"fred\"} [fred]\n {:name '*ob} [bob]\n {:age eve", "end": 829, "score": 0.9988920092582703, "start": 825, "tag": "NAME", "value": "fred" }, { "context": " \"fred\" [fred bob mary]\n\n {:name \"fred\"} [fred]\n {:name '*ob} [bob]\n {:age even?} [fre", "end": 837, "score": 0.6836567521095276, "start": 833, "tag": "NAME", "value": "fred" }, { "context": " bob mary]\n {:age odd?} []\n\n {:friends \"bob\"} [fred]\n {:friends [\"fred\" \"mary\"]} [bob]\n ", "end": 941, "score": 0.9374136924743652, "start": 938, "tag": "NAME", "value": "bob" }, { "context": "ry]\n {:age odd?} []\n\n {:friends \"bob\"} [fred]\n {:friends [\"fred\" \"mary\"]} [bob]\n {:f", "end": 949, "score": 0.8500633239746094, "start": 945, "tag": "NAME", "value": "fred" }, { "context": "\n\n {:friends \"bob\"} [fred]\n {:friends [\"fred\" \"mary\"]} [bob]\n {:friends #{\"fred\" \"mary\"}}", "end": 973, "score": 0.9995533227920532, "start": 969, "tag": "NAME", "value": "fred" }, { "context": " {:friends \"bob\"} [fred]\n {:friends [\"fred\" \"mary\"]} [bob]\n {:friends #{\"fred\" \"mary\"}} [bob m", "end": 980, "score": 0.9993746876716614, "start": 976, "tag": "NAME", "value": "mary" }, { "context": "friends [\"fred\" \"mary\"]} [bob]\n {:friends #{\"fred\" \"mary\"}} [bob mary]\n {:friends '(= #{\"fred\"", "end": 1013, "score": 0.9995760917663574, "start": 1009, "tag": "NAME", "value": "fred" }, { "context": " [\"fred\" \"mary\"]} [bob]\n {:friends #{\"fred\" \"mary\"}} [bob mary]\n {:friends '(= #{\"fred\" \"mary\"", "end": 1020, "score": 0.9990409016609192, "start": 1016, "tag": "NAME", "value": "mary" }, { "context": "\"]} [bob]\n {:friends #{\"fred\" \"mary\"}} [bob mary]\n {:friends '(= #{\"fred\" \"mary\"})} [bob])))\n", "end": 1033, "score": 0.6790352463722229, "start": 1030, "tag": "NAME", "value": "ary" }, { "context": "\"fred\" \"mary\"}} [bob mary]\n {:friends '(= #{\"fred\" \"mary\"})} [bob])))\n", "end": 1062, "score": 0.9991389513015747, "start": 1058, "tag": "NAME", "value": "fred" }, { "context": "\"mary\"}} [bob mary]\n {:friends '(= #{\"fred\" \"mary\"})} [bob])))\n", "end": 1069, "score": 0.9992547035217285, "start": 1065, "tag": "NAME", "value": "mary" } ]
test/riverford/datagrep/core_test.clj
riverford/datagrep
18
(ns riverford.datagrep.core-test (:require [clojure.test :refer :all] [riverford.datagrep.core :refer :all])) (deftest sanity-test (are [q ret] (= (grep q [1 2 3]) ret) some? [1 2 3] 1 [1] 2 [2] 3 [3] even? [2] '(< 2) [1] "2" [2] #{1 "3"} [1 3]) (are [q ret] (= (grep q ["fred" "bob" "ethel"]) ret) 'fred ["fred"] 'bo* ["bob"] #"(fr|)e.*" ["fred" "ethel"] '*thel ["ethel"]) (let [fred {:name "fred" :friends #{"bob"} :age 22} bob {:name "bob" :friends #{"fred" "mary"} :age 60} mary {:name "mary" :friends #{"fred"} :age 82}] (are [q ret] (= (grep q [fred bob mary]) ret) "fred" [fred bob mary] {:name "fred"} [fred] {:name '*ob} [bob] {:age even?} [fred bob mary] {:age odd?} [] {:friends "bob"} [fred] {:friends ["fred" "mary"]} [bob] {:friends #{"fred" "mary"}} [bob mary] {:friends '(= #{"fred" "mary"})} [bob])))
89271
(ns riverford.datagrep.core-test (:require [clojure.test :refer :all] [riverford.datagrep.core :refer :all])) (deftest sanity-test (are [q ret] (= (grep q [1 2 3]) ret) some? [1 2 3] 1 [1] 2 [2] 3 [3] even? [2] '(< 2) [1] "2" [2] #{1 "3"} [1 3]) (are [q ret] (= (grep q ["<NAME>" "bob" "<NAME>"]) ret) 'fred ["<NAME>"] 'bo* ["<NAME>"] #"(fr|)e.*" ["<NAME>" "<NAME>"] '*thel ["et<NAME>"]) (let [f<NAME> {:name "<NAME>" :friends #{"<NAME>"} :age 22} bob {:name "<NAME>" :friends #{"<NAME>" "<NAME>"} :age 60} <NAME>ary {:name "<NAME>" :friends #{"<NAME>"} :age 82}] (are [q ret] (= (grep q [<NAME>red bob mary]) ret) "f<NAME>" [fred bob mary] {:name "<NAME>"} [<NAME>] {:name '*ob} [bob] {:age even?} [fred bob mary] {:age odd?} [] {:friends "<NAME>"} [<NAME>] {:friends ["<NAME>" "<NAME>"]} [bob] {:friends #{"<NAME>" "<NAME>"}} [bob m<NAME>] {:friends '(= #{"<NAME>" "<NAME>"})} [bob])))
true
(ns riverford.datagrep.core-test (:require [clojure.test :refer :all] [riverford.datagrep.core :refer :all])) (deftest sanity-test (are [q ret] (= (grep q [1 2 3]) ret) some? [1 2 3] 1 [1] 2 [2] 3 [3] even? [2] '(< 2) [1] "2" [2] #{1 "3"} [1 3]) (are [q ret] (= (grep q ["PI:NAME:<NAME>END_PI" "bob" "PI:NAME:<NAME>END_PI"]) ret) 'fred ["PI:NAME:<NAME>END_PI"] 'bo* ["PI:NAME:<NAME>END_PI"] #"(fr|)e.*" ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] '*thel ["etPI:NAME:<NAME>END_PI"]) (let [fPI:NAME:<NAME>END_PI {:name "PI:NAME:<NAME>END_PI" :friends #{"PI:NAME:<NAME>END_PI"} :age 22} bob {:name "PI:NAME:<NAME>END_PI" :friends #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"} :age 60} PI:NAME:<NAME>END_PIary {:name "PI:NAME:<NAME>END_PI" :friends #{"PI:NAME:<NAME>END_PI"} :age 82}] (are [q ret] (= (grep q [PI:NAME:<NAME>END_PIred bob mary]) ret) "fPI:NAME:<NAME>END_PI" [fred bob mary] {:name "PI:NAME:<NAME>END_PI"} [PI:NAME:<NAME>END_PI] {:name '*ob} [bob] {:age even?} [fred bob mary] {:age odd?} [] {:friends "PI:NAME:<NAME>END_PI"} [PI:NAME:<NAME>END_PI] {:friends ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]} [bob] {:friends #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"}} [bob mPI:NAME:<NAME>END_PI] {:friends '(= #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"})} [bob])))
[ { "context": " :body {:data [{:id \"1\", :attributes {:name \"foo\", :id 1}, :type \"bars\"}]\n :jsonapi {", "end": 510, "score": 0.755476713180542, "start": 507, "tag": "NAME", "value": "foo" }, { "context": "}\n {:status 200\n :body [{:id 1, :name \"foo\"}]\n ::jsonapi/id-key :id\n ::jsonapi/r", "end": 629, "score": 0.7279942035675049, "start": 626, "tag": "NAME", "value": "foo" }, { "context": " :body {:data {:id \"1\", :attributes {:name \"foo\", :id 1}, :type \"bars\"},\n :jsonapi {", "end": 773, "score": 0.7628104090690613, "start": 770, "tag": "NAME", "value": "foo" }, { "context": "}}\n {:status 200\n :body {:id 1, :name \"foo\"}\n ::jsonapi/id-key :id\n ::jsonapi/re", "end": 891, "score": 0.648849606513977, "start": 888, "tag": "NAME", "value": "foo" }, { "context": " :body {:data [{:id \"1\", :attributes {:name \"foo\", :id 1}, :type \"bars\"}]\n :jsonapi {", "end": 1035, "score": 0.8229631185531616, "start": 1032, "tag": "NAME", "value": "foo" }, { "context": "}\n {:status 200\n :body [{:id 1, :name \"foo\"}]\n ::jsonapi/id-key :id\n ::jsonapi/r", "end": 1185, "score": 0.6899874806404114, "start": 1182, "tag": "NAME", "value": "foo" }, { "context": " \"bars\"\n :attributes {:name \"foo\", :id 1}\n :links {:self \"htt", "end": 1562, "score": 0.6350111961364746, "start": 1559, "tag": "NAME", "value": "foo" } ]
test/ring/middleware/jsonapi_test.clj
scij/ring.middleware.jsonapi
0
(ns ring.middleware.jsonapi-test (:require [clojure.test :as t] [jsonapi.core :as jsonapi] [ring.middleware.jsonapi :as m-jsonapi])) (t/deftest wrap-response-test (t/testing "should work with default options" (t/are [expected response] (= expected (let [handler (m-jsonapi/wrap-response (constantly response))] (handler {:headers {"accept" "application/vnd.api+json"}}))) {:status 200 :body {:data [{:id "1", :attributes {:name "foo", :id 1}, :type "bars"}] :jsonapi {:version "1.0"}}} {:status 200 :body [{:id 1, :name "foo"}] ::jsonapi/id-key :id ::jsonapi/resource-name "bars"} {:status 200 :body {:data {:id "1", :attributes {:name "foo", :id 1}, :type "bars"}, :jsonapi {:version "1.0"}}} {:status 200 :body {:id 1, :name "foo"} ::jsonapi/id-key :id ::jsonapi/resource-name "bars"} {:status 200 :body {:data [{:id "1", :attributes {:name "foo", :id 1}, :type "bars"}] :jsonapi {:version "1.0"} :meta {:total 1}}} {:status 200 :body [{:id 1, :name "foo"}] ::jsonapi/id-key :id ::jsonapi/resource-name "bars" ::jsonapi/meta {:total 1}})) (t/testing "should decorate response with a links object" (t/is (= {:status 201 :body {:jsonapi {:version "1.0"} :data {:id "1" :type "bars" :attributes {:name "foo", :id 1} :links {:self "http://foo"}}}} (let [handler (m-jsonapi/wrap-response (constantly {:status 201 :body {:id 1 :name "foo" ::jsonapi/links {:self "http://foo"}} ::jsonapi/id-key :id ::jsonapi/resource-name "bars"}))] (handler {:headers {"accept" "application/vnd.api+json"}}))))) (t/testing "should not decorate response, error response code" (t/is (= {:status 400 :body {:id 1, :name "foo"}} (let [handler (m-jsonapi/wrap-response (constantly {:status 400 :body {:id 1, :name "foo"}}))] (handler {:headers {"accept" "application/vnd.api+json"}}))))) (t/testing "should not decorate response, no accept header" (t/is (= {:status 200 :body {:id 1, :name "foo"}} (let [handler (m-jsonapi/wrap-response (constantly {:status 200 :body {:id 1, :name "foo"}}))] (handler {}))))) (t/testing "should not decorate response, accept header doesn't match" (t/is (= {:status 200, :body ""} (let [handler (m-jsonapi/wrap-response (constantly {:status 200, :body ""}))] (handler {:headers {"accept" "text/html"}}))))) (t/testing "should not decorate response, excluded URI" (t/is (= {:status 200, :body ""} (let [handler (m-jsonapi/wrap-response (constantly {:status 200, :body ""}) {:excluded-uris #{"/login"}})] (handler {:uri "/login"}))))) (t/testing "should not decorate response, no response code" (t/is (= {:body ""} (let [handler (m-jsonapi/wrap-response (constantly {:body ""}))] (handler {:uri "/login"})))))) (t/deftest wrap-request-test (t/testing "should work with default options" (t/are [expected request] (let [handler (m-jsonapi/wrap-request (fn [req] (t/is (= expected req))))] (handler request)) {:headers {"content-type" "application/vnd.api+json"} :body {:name "foo"}} {:headers {"content-type" "application/vnd.api+json"} :body {:data {:attributes {:name "foo"}, :type "bars"}}} {:headers {"content-type" "application/vnd.api+json"} :body-params {:name "foo"}} {:headers {"content-type" "application/vnd.api+json"} :body-params {:data {:attributes {:name "foo"}, :type "bars"}}})) (t/testing "should not work, no content type" (let [request {:body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))))] (handler request))) (t/testing "should not work, excluded URI" (let [request {:uri "/bars", :body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))) {:excluded-uris #{"/bars"}})] (handler request))) (t/testing "should not work, no content type" (let [request {:body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))))] (handler request))) (t/testing "should not work, no content type regular expression" (let [request {:headers {"content-type" "application/json"} :body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))) {:content-type-regexp nil})] (handler request))))
5815
(ns ring.middleware.jsonapi-test (:require [clojure.test :as t] [jsonapi.core :as jsonapi] [ring.middleware.jsonapi :as m-jsonapi])) (t/deftest wrap-response-test (t/testing "should work with default options" (t/are [expected response] (= expected (let [handler (m-jsonapi/wrap-response (constantly response))] (handler {:headers {"accept" "application/vnd.api+json"}}))) {:status 200 :body {:data [{:id "1", :attributes {:name "<NAME>", :id 1}, :type "bars"}] :jsonapi {:version "1.0"}}} {:status 200 :body [{:id 1, :name "<NAME>"}] ::jsonapi/id-key :id ::jsonapi/resource-name "bars"} {:status 200 :body {:data {:id "1", :attributes {:name "<NAME>", :id 1}, :type "bars"}, :jsonapi {:version "1.0"}}} {:status 200 :body {:id 1, :name "<NAME>"} ::jsonapi/id-key :id ::jsonapi/resource-name "bars"} {:status 200 :body {:data [{:id "1", :attributes {:name "<NAME>", :id 1}, :type "bars"}] :jsonapi {:version "1.0"} :meta {:total 1}}} {:status 200 :body [{:id 1, :name "<NAME>"}] ::jsonapi/id-key :id ::jsonapi/resource-name "bars" ::jsonapi/meta {:total 1}})) (t/testing "should decorate response with a links object" (t/is (= {:status 201 :body {:jsonapi {:version "1.0"} :data {:id "1" :type "bars" :attributes {:name "<NAME>", :id 1} :links {:self "http://foo"}}}} (let [handler (m-jsonapi/wrap-response (constantly {:status 201 :body {:id 1 :name "foo" ::jsonapi/links {:self "http://foo"}} ::jsonapi/id-key :id ::jsonapi/resource-name "bars"}))] (handler {:headers {"accept" "application/vnd.api+json"}}))))) (t/testing "should not decorate response, error response code" (t/is (= {:status 400 :body {:id 1, :name "foo"}} (let [handler (m-jsonapi/wrap-response (constantly {:status 400 :body {:id 1, :name "foo"}}))] (handler {:headers {"accept" "application/vnd.api+json"}}))))) (t/testing "should not decorate response, no accept header" (t/is (= {:status 200 :body {:id 1, :name "foo"}} (let [handler (m-jsonapi/wrap-response (constantly {:status 200 :body {:id 1, :name "foo"}}))] (handler {}))))) (t/testing "should not decorate response, accept header doesn't match" (t/is (= {:status 200, :body ""} (let [handler (m-jsonapi/wrap-response (constantly {:status 200, :body ""}))] (handler {:headers {"accept" "text/html"}}))))) (t/testing "should not decorate response, excluded URI" (t/is (= {:status 200, :body ""} (let [handler (m-jsonapi/wrap-response (constantly {:status 200, :body ""}) {:excluded-uris #{"/login"}})] (handler {:uri "/login"}))))) (t/testing "should not decorate response, no response code" (t/is (= {:body ""} (let [handler (m-jsonapi/wrap-response (constantly {:body ""}))] (handler {:uri "/login"})))))) (t/deftest wrap-request-test (t/testing "should work with default options" (t/are [expected request] (let [handler (m-jsonapi/wrap-request (fn [req] (t/is (= expected req))))] (handler request)) {:headers {"content-type" "application/vnd.api+json"} :body {:name "foo"}} {:headers {"content-type" "application/vnd.api+json"} :body {:data {:attributes {:name "foo"}, :type "bars"}}} {:headers {"content-type" "application/vnd.api+json"} :body-params {:name "foo"}} {:headers {"content-type" "application/vnd.api+json"} :body-params {:data {:attributes {:name "foo"}, :type "bars"}}})) (t/testing "should not work, no content type" (let [request {:body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))))] (handler request))) (t/testing "should not work, excluded URI" (let [request {:uri "/bars", :body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))) {:excluded-uris #{"/bars"}})] (handler request))) (t/testing "should not work, no content type" (let [request {:body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))))] (handler request))) (t/testing "should not work, no content type regular expression" (let [request {:headers {"content-type" "application/json"} :body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))) {:content-type-regexp nil})] (handler request))))
true
(ns ring.middleware.jsonapi-test (:require [clojure.test :as t] [jsonapi.core :as jsonapi] [ring.middleware.jsonapi :as m-jsonapi])) (t/deftest wrap-response-test (t/testing "should work with default options" (t/are [expected response] (= expected (let [handler (m-jsonapi/wrap-response (constantly response))] (handler {:headers {"accept" "application/vnd.api+json"}}))) {:status 200 :body {:data [{:id "1", :attributes {:name "PI:NAME:<NAME>END_PI", :id 1}, :type "bars"}] :jsonapi {:version "1.0"}}} {:status 200 :body [{:id 1, :name "PI:NAME:<NAME>END_PI"}] ::jsonapi/id-key :id ::jsonapi/resource-name "bars"} {:status 200 :body {:data {:id "1", :attributes {:name "PI:NAME:<NAME>END_PI", :id 1}, :type "bars"}, :jsonapi {:version "1.0"}}} {:status 200 :body {:id 1, :name "PI:NAME:<NAME>END_PI"} ::jsonapi/id-key :id ::jsonapi/resource-name "bars"} {:status 200 :body {:data [{:id "1", :attributes {:name "PI:NAME:<NAME>END_PI", :id 1}, :type "bars"}] :jsonapi {:version "1.0"} :meta {:total 1}}} {:status 200 :body [{:id 1, :name "PI:NAME:<NAME>END_PI"}] ::jsonapi/id-key :id ::jsonapi/resource-name "bars" ::jsonapi/meta {:total 1}})) (t/testing "should decorate response with a links object" (t/is (= {:status 201 :body {:jsonapi {:version "1.0"} :data {:id "1" :type "bars" :attributes {:name "PI:NAME:<NAME>END_PI", :id 1} :links {:self "http://foo"}}}} (let [handler (m-jsonapi/wrap-response (constantly {:status 201 :body {:id 1 :name "foo" ::jsonapi/links {:self "http://foo"}} ::jsonapi/id-key :id ::jsonapi/resource-name "bars"}))] (handler {:headers {"accept" "application/vnd.api+json"}}))))) (t/testing "should not decorate response, error response code" (t/is (= {:status 400 :body {:id 1, :name "foo"}} (let [handler (m-jsonapi/wrap-response (constantly {:status 400 :body {:id 1, :name "foo"}}))] (handler {:headers {"accept" "application/vnd.api+json"}}))))) (t/testing "should not decorate response, no accept header" (t/is (= {:status 200 :body {:id 1, :name "foo"}} (let [handler (m-jsonapi/wrap-response (constantly {:status 200 :body {:id 1, :name "foo"}}))] (handler {}))))) (t/testing "should not decorate response, accept header doesn't match" (t/is (= {:status 200, :body ""} (let [handler (m-jsonapi/wrap-response (constantly {:status 200, :body ""}))] (handler {:headers {"accept" "text/html"}}))))) (t/testing "should not decorate response, excluded URI" (t/is (= {:status 200, :body ""} (let [handler (m-jsonapi/wrap-response (constantly {:status 200, :body ""}) {:excluded-uris #{"/login"}})] (handler {:uri "/login"}))))) (t/testing "should not decorate response, no response code" (t/is (= {:body ""} (let [handler (m-jsonapi/wrap-response (constantly {:body ""}))] (handler {:uri "/login"})))))) (t/deftest wrap-request-test (t/testing "should work with default options" (t/are [expected request] (let [handler (m-jsonapi/wrap-request (fn [req] (t/is (= expected req))))] (handler request)) {:headers {"content-type" "application/vnd.api+json"} :body {:name "foo"}} {:headers {"content-type" "application/vnd.api+json"} :body {:data {:attributes {:name "foo"}, :type "bars"}}} {:headers {"content-type" "application/vnd.api+json"} :body-params {:name "foo"}} {:headers {"content-type" "application/vnd.api+json"} :body-params {:data {:attributes {:name "foo"}, :type "bars"}}})) (t/testing "should not work, no content type" (let [request {:body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))))] (handler request))) (t/testing "should not work, excluded URI" (let [request {:uri "/bars", :body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))) {:excluded-uris #{"/bars"}})] (handler request))) (t/testing "should not work, no content type" (let [request {:body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))))] (handler request))) (t/testing "should not work, no content type regular expression" (let [request {:headers {"content-type" "application/json"} :body {:data {:attributes {:name "foo"}, :type "bars"}}} handler (m-jsonapi/wrap-request (fn [req] (t/is (= request req))) {:content-type-regexp nil})] (handler request))))
[ { "context": " protected (wrap-allow-ips handler {:allow-list [\"10.0.0.0/8\"]})]\n (testing \"remote-addr only\"\n (is ", "end": 300, "score": 0.9993929862976074, "start": 292, "tag": "IP_ADDRESS", "value": "10.0.0.0" }, { "context": " (is (= 200 (:status (protected {:remote-addr \"10.20.206.46\"}))))\n (is (= 403 (:status (protected {:remo", "end": 404, "score": 0.9997013211250305, "start": 392, "tag": "IP_ADDRESS", "value": "10.20.206.46" }, { "context": " (is (= 403 (:status (protected {:remote-addr \"192.1.1.1\"})))))\n (testing \"remote and forwarded\"\n ", "end": 472, "score": 0.9997313022613525, "start": 463, "tag": "IP_ADDRESS", "value": "192.1.1.1" }, { "context": "atus (protected {:headers {\"x-forwarded-for\" \"10.20.205.24\"}\n :remote-a", "end": 599, "score": 0.9997194409370422, "start": 587, "tag": "IP_ADDRESS", "value": "10.20.205.24" }, { "context": " :remote-addr \"10.20.206.46\"}))))\n (is (= 403 (:status (protected {:head", "end": 666, "score": 0.9996955990791321, "start": 654, "tag": "IP_ADDRESS", "value": "10.20.206.46" }, { "context": "atus (protected {:headers {\"x-forwarded-for\" \"10.20.205.24,192.10.1.1\"}\n ", "end": 756, "score": 0.9997184872627258, "start": 744, "tag": "IP_ADDRESS", "value": "10.20.205.24" }, { "context": "ed {:headers {\"x-forwarded-for\" \"10.20.205.24,192.10.1.1\"}\n :remote-a", "end": 767, "score": 0.9997321367263794, "start": 757, "tag": "IP_ADDRESS", "value": "192.10.1.1" }, { "context": " :remote-addr \"10.20.206.46\"})))))))\n\n(deftest wrap-deny-ips-test\n (let [han", "end": 834, "score": 0.9997000098228455, "start": 822, "tag": "IP_ADDRESS", "value": "10.20.206.46" }, { "context": " protected (wrap-deny-ips handler {:deny-list [\"10.0.0.0/8\"]})]\n (testing \"remote-addr only\"\n (is ", "end": 1004, "score": 0.999351978302002, "start": 996, "tag": "IP_ADDRESS", "value": "10.0.0.0" }, { "context": " (is (= 403 (:status (protected {:remote-addr \"10.20.206.46\"}))))\n (is (= 200 (:status (protected {:remo", "end": 1108, "score": 0.999711811542511, "start": 1096, "tag": "IP_ADDRESS", "value": "10.20.206.46" }, { "context": " (is (= 200 (:status (protected {:remote-addr \"192.1.1.1\"})))))\n\n (testing \"remote and forwarded\"\n ", "end": 1176, "score": 0.9997369050979614, "start": 1167, "tag": "IP_ADDRESS", "value": "192.1.1.1" }, { "context": "atus (protected {:headers {\"x-forwarded-for\" \"192.1.1.2\"}\n :remote-a", "end": 1301, "score": 0.9997451305389404, "start": 1292, "tag": "IP_ADDRESS", "value": "192.1.1.2" }, { "context": " :remote-addr \"192.1.1.1\"}))))\n (is (= 403 (:status (protected {:head", "end": 1365, "score": 0.9997351765632629, "start": 1356, "tag": "IP_ADDRESS", "value": "192.1.1.1" }, { "context": "atus (protected {:headers {\"x-forwarded-for\" \"10.20.205.24,192.10.1.2\"}\n ", "end": 1455, "score": 0.999725341796875, "start": 1443, "tag": "IP_ADDRESS", "value": "10.20.205.24" }, { "context": "ed {:headers {\"x-forwarded-for\" \"10.20.205.24,192.10.1.2\"}\n :remote-a", "end": 1466, "score": 0.9997374415397644, "start": 1456, "tag": "IP_ADDRESS", "value": "192.10.1.2" }, { "context": " :remote-addr \"192.1.1.1\"})))))))\n\n(deftest wrap-blocking-concurrency-limi", "end": 1530, "score": 0.9997450709342957, "start": 1521, "tag": "IP_ADDRESS", "value": "192.1.1.1" } ]
test/ring_firewall_middleware/core_test.clj
RutledgePaulV/ring-firewall-middleware
13
(ns ring-firewall-middleware.core-test (:require [clojure.test :refer :all] [ring-firewall-middleware.core :refer :all])) (deftest wrap-allow-ips-test (let [handler (fn [req] {:status 200 :body "You have access!"}) protected (wrap-allow-ips handler {:allow-list ["10.0.0.0/8"]})] (testing "remote-addr only" (is (= 200 (:status (protected {:remote-addr "10.20.206.46"})))) (is (= 403 (:status (protected {:remote-addr "192.1.1.1"}))))) (testing "remote and forwarded" (is (= 200 (:status (protected {:headers {"x-forwarded-for" "10.20.205.24"} :remote-addr "10.20.206.46"})))) (is (= 403 (:status (protected {:headers {"x-forwarded-for" "10.20.205.24,192.10.1.1"} :remote-addr "10.20.206.46"}))))))) (deftest wrap-deny-ips-test (let [handler (fn [req] {:status 200 :body "You have access!"}) protected (wrap-deny-ips handler {:deny-list ["10.0.0.0/8"]})] (testing "remote-addr only" (is (= 403 (:status (protected {:remote-addr "10.20.206.46"})))) (is (= 200 (:status (protected {:remote-addr "192.1.1.1"}))))) (testing "remote and forwarded" (is (= 200 (:status (protected {:headers {"x-forwarded-for" "192.1.1.2"} :remote-addr "192.1.1.1"})))) (is (= 403 (:status (protected {:headers {"x-forwarded-for" "10.20.205.24,192.10.1.2"} :remote-addr "192.1.1.1"}))))))) (deftest wrap-blocking-concurrency-limit-test (let [handler (fn [req] (Thread/sleep 1000) {:status 200 :body "Response!"}) protected (wrap-concurrency-throttle handler {:max-concurrent 1}) start (System/currentTimeMillis) one (future (protected {})) two (future (protected {}))] (deref one) (deref two) (is (<= 2000 (- (System/currentTimeMillis) start))))) (deftest wrap-rejecting-concurrency-limit-test (let [handler (fn [req] (Thread/sleep 1000) {:status 200 :body "Response!"}) protected (wrap-concurrency-limit handler {:max-concurrent 1}) one (future (protected {})) two (future (protected {})) responses [(deref one) (deref two)]] (is (not-empty (filter #(= 429 (:status %)) responses))) (is (not-empty (filter #(= 200 (:status %)) responses))))) (deftest wrap-maintenance-mode-test (let [handler (fn [request] (when (number? request) (Thread/sleep request)) {:status 200 :body "Under the hood"}) protected (wrap-maintenance-limit handler) started (promise) finished (promise)] (is (= 200 (:status (protected {})))) (future (with-maintenance-mode :world (deliver started true) (Thread/sleep 2000)) (deliver finished true)) (deref started) (is (= 503 (:status (protected {})))) (deref finished) (is (= 200 (:status (protected {}))))))
81554
(ns ring-firewall-middleware.core-test (:require [clojure.test :refer :all] [ring-firewall-middleware.core :refer :all])) (deftest wrap-allow-ips-test (let [handler (fn [req] {:status 200 :body "You have access!"}) protected (wrap-allow-ips handler {:allow-list ["10.0.0.0/8"]})] (testing "remote-addr only" (is (= 200 (:status (protected {:remote-addr "10.20.206.46"})))) (is (= 403 (:status (protected {:remote-addr "192.168.3.11"}))))) (testing "remote and forwarded" (is (= 200 (:status (protected {:headers {"x-forwarded-for" "10.20.205.24"} :remote-addr "10.20.206.46"})))) (is (= 403 (:status (protected {:headers {"x-forwarded-for" "10.20.205.24,172.16.31.10"} :remote-addr "10.20.206.46"}))))))) (deftest wrap-deny-ips-test (let [handler (fn [req] {:status 200 :body "You have access!"}) protected (wrap-deny-ips handler {:deny-list ["10.0.0.0/8"]})] (testing "remote-addr only" (is (= 403 (:status (protected {:remote-addr "10.20.206.46"})))) (is (= 200 (:status (protected {:remote-addr "192.168.3.11"}))))) (testing "remote and forwarded" (is (= 200 (:status (protected {:headers {"x-forwarded-for" "192.168.127.12"} :remote-addr "192.168.3.11"})))) (is (= 403 (:status (protected {:headers {"x-forwarded-for" "10.20.205.24,192.168.3.11"} :remote-addr "192.168.3.11"}))))))) (deftest wrap-blocking-concurrency-limit-test (let [handler (fn [req] (Thread/sleep 1000) {:status 200 :body "Response!"}) protected (wrap-concurrency-throttle handler {:max-concurrent 1}) start (System/currentTimeMillis) one (future (protected {})) two (future (protected {}))] (deref one) (deref two) (is (<= 2000 (- (System/currentTimeMillis) start))))) (deftest wrap-rejecting-concurrency-limit-test (let [handler (fn [req] (Thread/sleep 1000) {:status 200 :body "Response!"}) protected (wrap-concurrency-limit handler {:max-concurrent 1}) one (future (protected {})) two (future (protected {})) responses [(deref one) (deref two)]] (is (not-empty (filter #(= 429 (:status %)) responses))) (is (not-empty (filter #(= 200 (:status %)) responses))))) (deftest wrap-maintenance-mode-test (let [handler (fn [request] (when (number? request) (Thread/sleep request)) {:status 200 :body "Under the hood"}) protected (wrap-maintenance-limit handler) started (promise) finished (promise)] (is (= 200 (:status (protected {})))) (future (with-maintenance-mode :world (deliver started true) (Thread/sleep 2000)) (deliver finished true)) (deref started) (is (= 503 (:status (protected {})))) (deref finished) (is (= 200 (:status (protected {}))))))
true
(ns ring-firewall-middleware.core-test (:require [clojure.test :refer :all] [ring-firewall-middleware.core :refer :all])) (deftest wrap-allow-ips-test (let [handler (fn [req] {:status 200 :body "You have access!"}) protected (wrap-allow-ips handler {:allow-list ["10.0.0.0/8"]})] (testing "remote-addr only" (is (= 200 (:status (protected {:remote-addr "10.20.206.46"})))) (is (= 403 (:status (protected {:remote-addr "PI:IP_ADDRESS:192.168.3.11END_PI"}))))) (testing "remote and forwarded" (is (= 200 (:status (protected {:headers {"x-forwarded-for" "10.20.205.24"} :remote-addr "10.20.206.46"})))) (is (= 403 (:status (protected {:headers {"x-forwarded-for" "10.20.205.24,PI:IP_ADDRESS:172.16.31.10END_PI"} :remote-addr "10.20.206.46"}))))))) (deftest wrap-deny-ips-test (let [handler (fn [req] {:status 200 :body "You have access!"}) protected (wrap-deny-ips handler {:deny-list ["10.0.0.0/8"]})] (testing "remote-addr only" (is (= 403 (:status (protected {:remote-addr "10.20.206.46"})))) (is (= 200 (:status (protected {:remote-addr "PI:IP_ADDRESS:192.168.3.11END_PI"}))))) (testing "remote and forwarded" (is (= 200 (:status (protected {:headers {"x-forwarded-for" "PI:IP_ADDRESS:192.168.127.12END_PI"} :remote-addr "PI:IP_ADDRESS:192.168.3.11END_PI"})))) (is (= 403 (:status (protected {:headers {"x-forwarded-for" "10.20.205.24,PI:IP_ADDRESS:192.168.3.11END_PI"} :remote-addr "PI:IP_ADDRESS:192.168.3.11END_PI"}))))))) (deftest wrap-blocking-concurrency-limit-test (let [handler (fn [req] (Thread/sleep 1000) {:status 200 :body "Response!"}) protected (wrap-concurrency-throttle handler {:max-concurrent 1}) start (System/currentTimeMillis) one (future (protected {})) two (future (protected {}))] (deref one) (deref two) (is (<= 2000 (- (System/currentTimeMillis) start))))) (deftest wrap-rejecting-concurrency-limit-test (let [handler (fn [req] (Thread/sleep 1000) {:status 200 :body "Response!"}) protected (wrap-concurrency-limit handler {:max-concurrent 1}) one (future (protected {})) two (future (protected {})) responses [(deref one) (deref two)]] (is (not-empty (filter #(= 429 (:status %)) responses))) (is (not-empty (filter #(= 200 (:status %)) responses))))) (deftest wrap-maintenance-mode-test (let [handler (fn [request] (when (number? request) (Thread/sleep request)) {:status 200 :body "Under the hood"}) protected (wrap-maintenance-limit handler) started (promise) finished (promise)] (is (= 200 (:status (protected {})))) (future (with-maintenance-mode :world (deliver started true) (Thread/sleep 2000)) (deliver finished true)) (deref started) (is (= 503 (:status (protected {})))) (deref finished) (is (= 200 (:status (protected {}))))))
[ { "context": "power \"AC\"}\n {:name \"Luke\"\n :home_world \"Tato", "end": 788, "score": 0.9950241446495056, "start": 784, "tag": "NAME", "value": "Luke" }, { "context": " \"Tatooine\"\n :name \"Luke\"}]}}\n\n (q \"query {\n\n characters", "end": 1207, "score": 0.9942564964294434, "start": 1203, "tag": "NAME", "value": "Luke" }, { "context": " \"Tatooine\"\n :name \"Luke\"}]}}\n\n (q \"query {\n\n characters", "end": 1702, "score": 0.994848370552063, "start": 1698, "tag": "NAME", "value": "Luke" } ]
test/com/walmartlabs/lacinia/fragments_tests.clj
gusbicalho/lacinia
0
(ns com.walmartlabs.lacinia.fragments-tests (:require [clojure.test :refer [deftest is]] [com.walmartlabs.lacinia :refer [execute]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.test-utils :as utils])) (defn ^:private resolve-characters [_ _ _] [(schema/tag-with-type {:name "R2-D2" :power "AC"} :droid) (schema/tag-with-type {:name "Luke" :home_world "Tatooine"} :human)]) (def ^:private schema (utils/compile-schema "fragments-schema.edn" {:resolve-characters resolve-characters})) (defn ^:private q [query] (utils/simplify (execute schema query nil nil))) (deftest inline-fragments (is (= {:data {:characters [{:name "R2-D2" :power "AC"} {:name "Luke" :home_world "Tatooine"}]}} (q "{ characters { name ... on droid { power } ... on human { home_world } } }")))) (deftest named-fragments (is (= {:data {:characters [{:name "R2-D2" :power "AC"} {:home_world "Tatooine" :name "Luke"}]}} (q "query { characters { name ... droidFragment ... humanFragment } } fragment droidFragment on droid { power } fragment humanFragment on human { home_world } ")))) (deftest nested-fragments (is (= {:data {:characters [{:name "R2-D2" :power "AC"} {:home_world "Tatooine" :name "Luke"}]}} (q "query { characters { ... characterFragment } } fragment characterFragment on character { name ... droidFragment ... humanFragment } fragment droidFragment on droid { power } fragment humanFragment on human { home_world } "))))
41504
(ns com.walmartlabs.lacinia.fragments-tests (:require [clojure.test :refer [deftest is]] [com.walmartlabs.lacinia :refer [execute]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.test-utils :as utils])) (defn ^:private resolve-characters [_ _ _] [(schema/tag-with-type {:name "R2-D2" :power "AC"} :droid) (schema/tag-with-type {:name "Luke" :home_world "Tatooine"} :human)]) (def ^:private schema (utils/compile-schema "fragments-schema.edn" {:resolve-characters resolve-characters})) (defn ^:private q [query] (utils/simplify (execute schema query nil nil))) (deftest inline-fragments (is (= {:data {:characters [{:name "R2-D2" :power "AC"} {:name "<NAME>" :home_world "Tatooine"}]}} (q "{ characters { name ... on droid { power } ... on human { home_world } } }")))) (deftest named-fragments (is (= {:data {:characters [{:name "R2-D2" :power "AC"} {:home_world "Tatooine" :name "<NAME>"}]}} (q "query { characters { name ... droidFragment ... humanFragment } } fragment droidFragment on droid { power } fragment humanFragment on human { home_world } ")))) (deftest nested-fragments (is (= {:data {:characters [{:name "R2-D2" :power "AC"} {:home_world "Tatooine" :name "<NAME>"}]}} (q "query { characters { ... characterFragment } } fragment characterFragment on character { name ... droidFragment ... humanFragment } fragment droidFragment on droid { power } fragment humanFragment on human { home_world } "))))
true
(ns com.walmartlabs.lacinia.fragments-tests (:require [clojure.test :refer [deftest is]] [com.walmartlabs.lacinia :refer [execute]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.test-utils :as utils])) (defn ^:private resolve-characters [_ _ _] [(schema/tag-with-type {:name "R2-D2" :power "AC"} :droid) (schema/tag-with-type {:name "Luke" :home_world "Tatooine"} :human)]) (def ^:private schema (utils/compile-schema "fragments-schema.edn" {:resolve-characters resolve-characters})) (defn ^:private q [query] (utils/simplify (execute schema query nil nil))) (deftest inline-fragments (is (= {:data {:characters [{:name "R2-D2" :power "AC"} {:name "PI:NAME:<NAME>END_PI" :home_world "Tatooine"}]}} (q "{ characters { name ... on droid { power } ... on human { home_world } } }")))) (deftest named-fragments (is (= {:data {:characters [{:name "R2-D2" :power "AC"} {:home_world "Tatooine" :name "PI:NAME:<NAME>END_PI"}]}} (q "query { characters { name ... droidFragment ... humanFragment } } fragment droidFragment on droid { power } fragment humanFragment on human { home_world } ")))) (deftest nested-fragments (is (= {:data {:characters [{:name "R2-D2" :power "AC"} {:home_world "Tatooine" :name "PI:NAME:<NAME>END_PI"}]}} (q "query { characters { ... characterFragment } } fragment characterFragment on character { name ... droidFragment ... humanFragment } fragment droidFragment on droid { power } fragment humanFragment on human { home_world } "))))
[ { "context": ";; Copyright 2017 7bridges s.r.l.\n;;\n;; Licensed under the Apache License, V", "end": 26, "score": 0.8890994191169739, "start": 18, "tag": "USERNAME", "value": "7bridges" }, { "context": "[:operation 1]\n [:session-id -1]\n [:username username]\n [:password password]]))\n\n(defn shutdown-resp", "end": 1071, "score": 0.9948939085006714, "start": 1063, "tag": "USERNAME", "value": "username" }, { "context": "ion-id -1]\n [:username username]\n [:password password]]))\n\n(defn shutdown-response\n [^DataInputStream ", "end": 1096, "score": 0.9982383251190186, "start": 1088, "tag": "PASSWORD", "value": "password" }, { "context": "h false]\n [:collect-stats false]\n [:username username]\n [:password password]]))\n\n(defn connect-respo", "end": 1590, "score": 0.9892573952674866, "start": 1582, "tag": "USERNAME", "value": "username" }, { "context": "ats false]\n [:username username]\n [:password password]]))\n\n(defn connect-response\n [^DataInputStream i", "end": 1615, "score": 0.9979819655418396, "start": 1607, "tag": "PASSWORD", "value": "password" }, { "context": "false]\n [:database-name db-name]\n [:username username]\n [:password password]]))\n\n(defn db-open-respo", "end": 2183, "score": 0.9979346394538879, "start": 2175, "tag": "USERNAME", "value": "username" }, { "context": "e db-name]\n [:username username]\n [:password password]]))\n\n(defn db-open-response\n [^DataInputStream i", "end": 2208, "score": 0.9992852807044983, "start": 2200, "tag": "PASSWORD", "value": "password" } ]
src/clj_odbp/operations/db.clj
7BridgesEu/clj-odbp
0
;; Copyright 2017 7bridges s.r.l. ;; ;; 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 clj-odbp.operations.db (:require [clj-odbp [constants :as consts] [utils :refer [decode encode]]] [clj-odbp.network.sessions :as sessions] [clj-odbp.operations.specs.db :as specs] [clj-odbp.constants :as const]) (:import java.io.DataInputStream)) ;; REQUEST_SHUTDOWN (defn shutdown-request [username password] (encode specs/shutdown-request [[:operation 1] [:session-id -1] [:username username] [:password password]])) (defn shutdown-response [^DataInputStream in] {}) ;; REQUEST_CONNECT (defn connect-request [username password] (encode specs/connect-request [[:operation 2] [:session-id -1] [:driver-name const/driver-name] [:driver-version const/driver-version] [:protocol-version const/protocol-version] [:client-id ""] [:serialization const/serialization-name] [:token-session true] [:support-push false] [:collect-stats false] [:username username] [:password password]])) (defn connect-response [^DataInputStream in] (decode in specs/connect-response)) ;; REQUEST_DB_OPEN (defn db-open-request [db-name username password] (encode specs/db-open-request [[:operation 3] [:session-id -1] [:driver-name const/driver-name] [:driver-version const/driver-version] [:protocol-version const/protocol-version] [:client-id ""] [:serialization const/serialization-name] [:token-session true] [:support-push false] [:collect-stats false] [:database-name db-name] [:username username] [:password password]])) (defn db-open-response [^DataInputStream in] (decode in specs/db-open-response)) ;; REQUEST_DB_CREATE (defn db-create-request [connection db-name {:keys [db-type storage-type backup-path] :or {db-type "graph" storage-type "plocal" backup-path ""}}] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-create-request [[:operation 4] [:session-id session-id] [:token token] [:database-name db-name] [:database-type db-type] [:storage-type storage-type] [:backup-path backup-path]]))) (defn db-create-response [^DataInputStream in] (let [response (decode in specs/db-create-response)] (when-not (empty? (:token response)) (sessions/reset-session! :db) (sessions/put-session! response :db)))) ;; REQUEST_DB_CLOSE (defn db-close-request [] (encode specs/db-close-request [[:operation 5]])) (defn db-close-response [^DataInputStream in] (let [response (decode in specs/db-close-response)] (when-not (empty? (:token response)) (sessions/reset-session! :db) (sessions/put-session! response :db)))) ;; REQUEST_DB_EXIST (defn db-exist-request [connection db-name] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-exist-request [[:operation 6] [:session-id session-id] [:token token] [:database-name db-name] [:server-storage-type consts/storage-type-plocal]]))) (defn db-exist-response [^DataInputStream in] (let [response (decode in specs/db-exist-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response)) ;; REQUEST_DB_DROP (defn db-drop-request [connection db-name] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-drop-request [[:operation 7] [:session-id session-id] [:token token] [:database-name db-name] [:storage-type consts/storage-type-plocal]]))) (defn db-drop-response [^DataInputStream in] (let [response (decode in specs/db-drop-response)] (when-not (empty? (:token response)) (sessions/reset-session! :db) (sessions/put-session! response :db)))) ;; REQUEST_DB_SIZE (defn db-size-request [connection] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-size-request [[:operation 8] [:session-id session-id] [:token token]]))) (defn db-size-response [^DataInputStream in] (let [response (decode in specs/db-size-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response)) ;; REQUEST_DB_COUNTRECORDS (defn db-countrecords-request [connection] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-countrecords-request [[:operation 9] [:session-id session-id] [:token token]]))) (defn db-countrecords-response [^DataInputStream in] (let [response (decode in specs/db-countrecords-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response)) ;; REQUEST_DB_RELOAD (defn db-reload-request [connection] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-reload-request [[:operation 73] [:session-id session-id] [:token token]]))) (defn db-reload-response [^DataInputStream in] (let [response (decode in specs/db-reload-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response))
100421
;; Copyright 2017 7bridges s.r.l. ;; ;; 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 clj-odbp.operations.db (:require [clj-odbp [constants :as consts] [utils :refer [decode encode]]] [clj-odbp.network.sessions :as sessions] [clj-odbp.operations.specs.db :as specs] [clj-odbp.constants :as const]) (:import java.io.DataInputStream)) ;; REQUEST_SHUTDOWN (defn shutdown-request [username password] (encode specs/shutdown-request [[:operation 1] [:session-id -1] [:username username] [:password <PASSWORD>]])) (defn shutdown-response [^DataInputStream in] {}) ;; REQUEST_CONNECT (defn connect-request [username password] (encode specs/connect-request [[:operation 2] [:session-id -1] [:driver-name const/driver-name] [:driver-version const/driver-version] [:protocol-version const/protocol-version] [:client-id ""] [:serialization const/serialization-name] [:token-session true] [:support-push false] [:collect-stats false] [:username username] [:password <PASSWORD>]])) (defn connect-response [^DataInputStream in] (decode in specs/connect-response)) ;; REQUEST_DB_OPEN (defn db-open-request [db-name username password] (encode specs/db-open-request [[:operation 3] [:session-id -1] [:driver-name const/driver-name] [:driver-version const/driver-version] [:protocol-version const/protocol-version] [:client-id ""] [:serialization const/serialization-name] [:token-session true] [:support-push false] [:collect-stats false] [:database-name db-name] [:username username] [:password <PASSWORD>]])) (defn db-open-response [^DataInputStream in] (decode in specs/db-open-response)) ;; REQUEST_DB_CREATE (defn db-create-request [connection db-name {:keys [db-type storage-type backup-path] :or {db-type "graph" storage-type "plocal" backup-path ""}}] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-create-request [[:operation 4] [:session-id session-id] [:token token] [:database-name db-name] [:database-type db-type] [:storage-type storage-type] [:backup-path backup-path]]))) (defn db-create-response [^DataInputStream in] (let [response (decode in specs/db-create-response)] (when-not (empty? (:token response)) (sessions/reset-session! :db) (sessions/put-session! response :db)))) ;; REQUEST_DB_CLOSE (defn db-close-request [] (encode specs/db-close-request [[:operation 5]])) (defn db-close-response [^DataInputStream in] (let [response (decode in specs/db-close-response)] (when-not (empty? (:token response)) (sessions/reset-session! :db) (sessions/put-session! response :db)))) ;; REQUEST_DB_EXIST (defn db-exist-request [connection db-name] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-exist-request [[:operation 6] [:session-id session-id] [:token token] [:database-name db-name] [:server-storage-type consts/storage-type-plocal]]))) (defn db-exist-response [^DataInputStream in] (let [response (decode in specs/db-exist-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response)) ;; REQUEST_DB_DROP (defn db-drop-request [connection db-name] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-drop-request [[:operation 7] [:session-id session-id] [:token token] [:database-name db-name] [:storage-type consts/storage-type-plocal]]))) (defn db-drop-response [^DataInputStream in] (let [response (decode in specs/db-drop-response)] (when-not (empty? (:token response)) (sessions/reset-session! :db) (sessions/put-session! response :db)))) ;; REQUEST_DB_SIZE (defn db-size-request [connection] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-size-request [[:operation 8] [:session-id session-id] [:token token]]))) (defn db-size-response [^DataInputStream in] (let [response (decode in specs/db-size-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response)) ;; REQUEST_DB_COUNTRECORDS (defn db-countrecords-request [connection] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-countrecords-request [[:operation 9] [:session-id session-id] [:token token]]))) (defn db-countrecords-response [^DataInputStream in] (let [response (decode in specs/db-countrecords-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response)) ;; REQUEST_DB_RELOAD (defn db-reload-request [connection] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-reload-request [[:operation 73] [:session-id session-id] [:token token]]))) (defn db-reload-response [^DataInputStream in] (let [response (decode in specs/db-reload-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response))
true
;; Copyright 2017 7bridges s.r.l. ;; ;; 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 clj-odbp.operations.db (:require [clj-odbp [constants :as consts] [utils :refer [decode encode]]] [clj-odbp.network.sessions :as sessions] [clj-odbp.operations.specs.db :as specs] [clj-odbp.constants :as const]) (:import java.io.DataInputStream)) ;; REQUEST_SHUTDOWN (defn shutdown-request [username password] (encode specs/shutdown-request [[:operation 1] [:session-id -1] [:username username] [:password PI:PASSWORD:<PASSWORD>END_PI]])) (defn shutdown-response [^DataInputStream in] {}) ;; REQUEST_CONNECT (defn connect-request [username password] (encode specs/connect-request [[:operation 2] [:session-id -1] [:driver-name const/driver-name] [:driver-version const/driver-version] [:protocol-version const/protocol-version] [:client-id ""] [:serialization const/serialization-name] [:token-session true] [:support-push false] [:collect-stats false] [:username username] [:password PI:PASSWORD:<PASSWORD>END_PI]])) (defn connect-response [^DataInputStream in] (decode in specs/connect-response)) ;; REQUEST_DB_OPEN (defn db-open-request [db-name username password] (encode specs/db-open-request [[:operation 3] [:session-id -1] [:driver-name const/driver-name] [:driver-version const/driver-version] [:protocol-version const/protocol-version] [:client-id ""] [:serialization const/serialization-name] [:token-session true] [:support-push false] [:collect-stats false] [:database-name db-name] [:username username] [:password PI:PASSWORD:<PASSWORD>END_PI]])) (defn db-open-response [^DataInputStream in] (decode in specs/db-open-response)) ;; REQUEST_DB_CREATE (defn db-create-request [connection db-name {:keys [db-type storage-type backup-path] :or {db-type "graph" storage-type "plocal" backup-path ""}}] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-create-request [[:operation 4] [:session-id session-id] [:token token] [:database-name db-name] [:database-type db-type] [:storage-type storage-type] [:backup-path backup-path]]))) (defn db-create-response [^DataInputStream in] (let [response (decode in specs/db-create-response)] (when-not (empty? (:token response)) (sessions/reset-session! :db) (sessions/put-session! response :db)))) ;; REQUEST_DB_CLOSE (defn db-close-request [] (encode specs/db-close-request [[:operation 5]])) (defn db-close-response [^DataInputStream in] (let [response (decode in specs/db-close-response)] (when-not (empty? (:token response)) (sessions/reset-session! :db) (sessions/put-session! response :db)))) ;; REQUEST_DB_EXIST (defn db-exist-request [connection db-name] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-exist-request [[:operation 6] [:session-id session-id] [:token token] [:database-name db-name] [:server-storage-type consts/storage-type-plocal]]))) (defn db-exist-response [^DataInputStream in] (let [response (decode in specs/db-exist-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response)) ;; REQUEST_DB_DROP (defn db-drop-request [connection db-name] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-drop-request [[:operation 7] [:session-id session-id] [:token token] [:database-name db-name] [:storage-type consts/storage-type-plocal]]))) (defn db-drop-response [^DataInputStream in] (let [response (decode in specs/db-drop-response)] (when-not (empty? (:token response)) (sessions/reset-session! :db) (sessions/put-session! response :db)))) ;; REQUEST_DB_SIZE (defn db-size-request [connection] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-size-request [[:operation 8] [:session-id session-id] [:token token]]))) (defn db-size-response [^DataInputStream in] (let [response (decode in specs/db-size-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response)) ;; REQUEST_DB_COUNTRECORDS (defn db-countrecords-request [connection] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-countrecords-request [[:operation 9] [:session-id session-id] [:token token]]))) (defn db-countrecords-response [^DataInputStream in] (let [response (decode in specs/db-countrecords-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response)) ;; REQUEST_DB_RELOAD (defn db-reload-request [connection] (let [session-id (:session-id connection) token (:token connection)] (encode specs/db-reload-request [[:operation 73] [:session-id session-id] [:token token]]))) (defn db-reload-response [^DataInputStream in] (let [response (decode in specs/db-reload-response) session (select-keys response [:session-id :token])] (when-not (empty? (:token session)) (sessions/reset-session! :db) (sessions/put-session! session :db)) response))
[ { "context": "til/camel->kebab \"AbaCaba\"))))\n\n\n;; Copyright 2018 Frederic Merizen\n;;\n;; Licensed under the Apache License, Version ", "end": 1447, "score": 0.9998766183853149, "start": 1431, "tag": "NAME", "value": "Frederic Merizen" } ]
test/ferje/util_test.clj
chourave/clojyday
0
;; Copyright and license information at end of file (ns ferje.util-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [ferje.spec-test-utils :refer [instrument-fixture]] [ferje.util :as util] [orchestra.spec.test :refer [instrument]])) ;; Fixtures (use-fixtures :once instrument-fixture) ;; Basic type predicates (deftest string-array?-test (testing "only instancs of String[] are string arrays" (is (util/string-array? (into-array ["blah"]))) (is (not (util/string-array? ["bli"]))) (is (not (util/string-array? (object-array ["blah"])))))) ;; Utility functions (deftest $-test (testing "$ is just function application" (is (= 3 (util/$ inc 2))) (is (= "3" (util/$ str 3))))) ;; String manipulation (deftest lowercase?-test (is (util/lowercase? "abc")) (is (util/lowercase? "abc-def")) (is (util/lowercase? "/$+*")) (is (not (util/lowercase? "B")))) (deftest uppercase?-test (is (util/uppercase? "ABC")) (is (util/uppercase? "ABC-DEF")) (is (util/uppercase? "/$+*")) (is (not (util/uppercase? "b")))) (deftest kebab->camel-test (is (= "abacaba" (util/kebab->camel "abacaba"))) (is (= "abaCaba" (util/kebab->camel "aba-caba")))) (deftest camel->kebab-test (is (= "abacaba" (util/camel->kebab "abacaba"))) (is (= "aba-caba" (util/camel->kebab "abaCaba"))) (is (= "aba-caba" (util/camel->kebab "AbaCaba")))) ;; Copyright 2018 Frederic Merizen ;; ;; 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.
102085
;; Copyright and license information at end of file (ns ferje.util-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [ferje.spec-test-utils :refer [instrument-fixture]] [ferje.util :as util] [orchestra.spec.test :refer [instrument]])) ;; Fixtures (use-fixtures :once instrument-fixture) ;; Basic type predicates (deftest string-array?-test (testing "only instancs of String[] are string arrays" (is (util/string-array? (into-array ["blah"]))) (is (not (util/string-array? ["bli"]))) (is (not (util/string-array? (object-array ["blah"])))))) ;; Utility functions (deftest $-test (testing "$ is just function application" (is (= 3 (util/$ inc 2))) (is (= "3" (util/$ str 3))))) ;; String manipulation (deftest lowercase?-test (is (util/lowercase? "abc")) (is (util/lowercase? "abc-def")) (is (util/lowercase? "/$+*")) (is (not (util/lowercase? "B")))) (deftest uppercase?-test (is (util/uppercase? "ABC")) (is (util/uppercase? "ABC-DEF")) (is (util/uppercase? "/$+*")) (is (not (util/uppercase? "b")))) (deftest kebab->camel-test (is (= "abacaba" (util/kebab->camel "abacaba"))) (is (= "abaCaba" (util/kebab->camel "aba-caba")))) (deftest camel->kebab-test (is (= "abacaba" (util/camel->kebab "abacaba"))) (is (= "aba-caba" (util/camel->kebab "abaCaba"))) (is (= "aba-caba" (util/camel->kebab "AbaCaba")))) ;; Copyright 2018 <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.
true
;; Copyright and license information at end of file (ns ferje.util-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [ferje.spec-test-utils :refer [instrument-fixture]] [ferje.util :as util] [orchestra.spec.test :refer [instrument]])) ;; Fixtures (use-fixtures :once instrument-fixture) ;; Basic type predicates (deftest string-array?-test (testing "only instancs of String[] are string arrays" (is (util/string-array? (into-array ["blah"]))) (is (not (util/string-array? ["bli"]))) (is (not (util/string-array? (object-array ["blah"])))))) ;; Utility functions (deftest $-test (testing "$ is just function application" (is (= 3 (util/$ inc 2))) (is (= "3" (util/$ str 3))))) ;; String manipulation (deftest lowercase?-test (is (util/lowercase? "abc")) (is (util/lowercase? "abc-def")) (is (util/lowercase? "/$+*")) (is (not (util/lowercase? "B")))) (deftest uppercase?-test (is (util/uppercase? "ABC")) (is (util/uppercase? "ABC-DEF")) (is (util/uppercase? "/$+*")) (is (not (util/uppercase? "b")))) (deftest kebab->camel-test (is (= "abacaba" (util/kebab->camel "abacaba"))) (is (= "abaCaba" (util/kebab->camel "aba-caba")))) (deftest camel->kebab-test (is (= "abacaba" (util/camel->kebab "abacaba"))) (is (= "aba-caba" (util/camel->kebab "abaCaba"))) (is (= "aba-caba" (util/camel->kebab "AbaCaba")))) ;; Copyright 2018 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.
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.basal.core\n\n \"U", "end": 597, "score": 0.9998613595962524, "start": 584, "tag": "NAME", "value": "Kenneth Leung" } ]
src/main/clojure/czlab/basal/core.clj
llnek/xlib
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.basal.core "Useful additions to clojure core & string." (:refer-clojure :exclude [send next]) (:require [clojure.set :as ct] [clojure.string :as cs] [io.aviso.ansi :as ansi] [clojure.tools.logging :as l]) (:import [java.util Date] [java.lang System StringBuilder])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;; #^"[Ljava.lang.Object;" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:doc "Log flag(toggle) used internally."} LOG-FLAG (not (.equals "false" (System/getProperty "czlabloggerflag")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private t-bad "FAILED") (def ^:private t-ok "passed") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defmacro- "Same as defmacro but private." {:arglists '([name & more])} [name & more] (list* `defmacro (with-meta name (assoc (meta name) :private true)) more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defonce- "Same as defonce but private." {:arglists '([name & more])} [name & more] (list* `defonce (with-meta name (assoc (meta name) :private true)) more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro def- "Same as def but private." {:arglists '([name & more])} [name & more] (list* `def (with-meta name (assoc (meta name) :private true)) more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-long-var "Define a long array[1] for local operation" ([] `(decl-long-var 0)) ([n] `(long-array 1 ~n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-int-var "Define a int array[1] for local operation" ([] `(decl-int-var 0)) ([n] `(int-array 1 ~n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn int-var "" ([^ints arr v] (aset arr 0 (int v)) (int v)) ([^ints arr] (aget arr 0)) ([^ints arr op nv] (let [v (int (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn long-var "" ([^longs arr ^long v] (aset arr 0 v) v) ([^longs arr] (aget arr 0)) ([^longs arr op nv] (let [v (long (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-var-docstring "Add docstring to var" [v s] `(alter-meta! ~v assoc :doc ~s)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-var-private "Make var private" [v] `(alter-meta! ~v assoc :private true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-object<> "Define a simple type" [name & more] `(defrecord ~name [] ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol JEnumProto "Mimic Java Enum" (lookup-enum-str [_ s] "Get enum from string") (get-enum-str [_ e] "Get string value of enum") (lookup-enum-int [_ n] "Get enum from int")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;Loose equivalent of a Java Enum (decl-object<> JEnum JEnumProto (get-enum-str [me e] (if (contains? me e) (cs/replace (str e) #"^:" ""))) (lookup-enum-str [me s] (let [kee (keyword s)] (some #(if (= kee (first %)) (first %)) me))) (lookup-enum-int [me n] (some #(if (= n (last %)) (first %)) me))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-generic-enum "e.g. (decl-generic-enum weather hot cold)" [name base & more] (assert (and (not-empty more) (integer? base))) `(def ~name (czlab.basal.core/object<> czlab.basal.core.JEnum (-> {} ~@(reduce #(conj %1 `(assoc (keyword (str *ns*) ~(str %2)) ~(+ base (count %1)))) [] more))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;how to make it private ;;(alter-meta! #'weather assoc :private true) (defmacro decl-special-enum "e.g. (decl-special-enum weather hot 3 cold 7)" [name & more] (assert (even? (count more))) (let [ps (partition 2 more)] `(def ~name (czlab.basal.core/object<> czlab.basal.core.JEnum (-> {} ~@(mapv #(do `(assoc (keyword (str *ns*) ~(str (first %))) ~(last %))) ps)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro trace "Logging at TRACE level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :trace ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro debug "Logging at DEBUG level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :debug ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro info "Logging at INFO level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :info ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro warn "Logging at WARN level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :warn ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro error "Logging at ERROR level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :error ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fatal "Logging at FATAL level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :fatal ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn exception "Log an exception at ERROR level." {:arglists '([e])} [e] (when czlab.basal.core/LOG-FLAG (clojure.tools.logging/logf :error e "") (clojure.tools.logging/logf :error "%s" "exception thrown."))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def BOOLS #{"true" "yes" "on" "ok" "active" "1"}) (def ^String HEX-CHAR-STR "0123456789ABCDEF") (def ^String hex-char-str "0123456789abcdef") (def ^{:tag "[C"} HEX-CHARS (.toCharArray HEX-CHAR-STR)) (def ^{:tag "[C"} hex-chars (.toCharArray hex-char-str)) (def ^String USASCII "ISO-8859-1") (def ^String UTF16 "UTF-16") (def ^String UTF8 "UTF-8") (def OneK 1024) (def FourK (* 4 OneK)) (def KiloBytes OneK) (def BUF-SZ (* 4 KiloBytes)) (def MegaBytes (* KiloBytes KiloBytes)) (def GigaBytes (* KiloBytes KiloBytes KiloBytes)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro funcit?? "Maybe run a function with args." {:arglists '([f & args])} [f & args] `(let [f# ~f] (if (fn? f#) (f# ~@args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro pre "Like :pre, assert conditions." {:arglists '([& conds])} [& conds] `(assert (and ~@conds) "precond failed.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro atom? "If obj is an atom?" {:arglists '([x])} [x] `(instance? clojure.lang.Atom ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro n#-even? "Count of collection even?" {:arglists '([coll])} [coll] `(even? (count ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !sas? "Same as not-satisfies?" {:arglists '([proto obj])} [proto obj] `(not (satisfies? ~proto ~obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sas? "Same as satisfies?" {:arglists '([proto obj])} [proto obj] `(satisfies? ~proto ~obj)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !is? "Same as not-instance?" {:arglists '([clazz obj])} [clazz obj] `(not (instance? ~clazz ~obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro is? "Same as instance?" {:arglists '([clazz obj])} [clazz obj] `(instance? ~clazz ~obj)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro map-> "Same as into {}." {:arglists '([& more])} [& more] `(into {} ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vec-> "Same as into []." {:arglists '([& more])} [& more] `(into [] ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro set-> "Same as into #{}." {:arglists '([& more])} [& more] `(into #{} ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cc+1 "Prepend an item to collection(s)." {:arglists '([a & more])} [a & more] `(concat [~a] ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cc+ "Same as concat." {:arglists '([& more])} [& more] `(concat ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _2 "Same as second." {:arglists '([coll])} [coll] `(second ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _1 "Same as first." {:arglists '([coll])} [coll] `(first ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _3 "Get the 3rd item." {:arglists '([coll])} [coll] `(nth ~coll 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _E "Same as last." {:arglists '([coll])} [coll] `(last ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _NE "Get the last item via nth." {:arglists '([coll])} [coll] `(let [x# ~coll] (nth x# (- (count x#) 1)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !zero? "Same as not-zero?" {:arglists '([n])} [n] `(not (zero? ~n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro n# "Same as count." {:arglists '([coll])} [coll] `(count ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro car "Same as first." {:arglists '([coll])} [coll] `(first ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cdr "Same as rest." {:arglists '([coll])} [coll] `(rest ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro one? "If count() is 1?" {:arglists '([coll])} [coll] `(== 1 (count ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro two? "If count() is 2?" {:arglists '([coll])} [coll] `(== 2 (count ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro one+? "If count() is more than 1?" {:arglists '([coll])} [coll] `(> (count ~coll) 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro or?? "(or?? [= a] b c) => (or (= b a) (= c a))." {:arglists '([bindings & args])} [bindings & args] (let [op (gensym) arg (gensym) [p1 p2] bindings] `(let [~op ~p1 ~arg ~p2] (or ~@(map (fn [n] `(~op ~n ~arg)) args))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro dissoc!! "Mutable dissoc (atom)." {:arglists '([a & args])} [a & args] (let [X (gensym)] `(let [~X ~a] (swap! ~X dissoc ~@args) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro assoc!! "Mutable assoc (atom)." {:arglists '([a & args])} [a & args] (let [X (gensym)] `(let [~X ~a] (swap! ~X assoc ~@args) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_* "Wrap code into a fn(...)." {:arglists '([& forms])} [& forms] `(fn [& ~'____xs] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_3 "Wrap code into a fn(a1,a2,a3)." {:arglists '([& forms])} [& forms] `(fn [~'____1 ~'____2 ~'____3] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_2 "Wrap code into a fn(a1,a2)." {:arglists '([& forms])} [& forms] `(fn [~'____1 ~'____2] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_1 "Wrap code into a fn(a1)." {:arglists '([& forms])} [& forms] `(fn [~'____1] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_0 "Wrap code into a fn()." {:arglists '([& forms])} [& forms] `(fn [] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro tset* "A transient set." {:arglists '([] [x])} ([] `(tset* nil)) ([x] `(transient (or ~x #{})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro tvec* "A transient vector." {:arglists '([] [x])} ([] `(tvec* nil)) ([x] `(transient (or ~x [])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro tmap* "A transient map." {:arglists '([] [x])} ([] `(tmap* nil)) ([x] `(transient (or ~x {})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro persist! "Same as persistent!." {:arglists '([coll])} [coll] `(persistent! ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro atomic "Atomize fields as map." {:arglists '([& args])} [& args] `(atom (array-map ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro mapfv "Apply a binary-op to the value over the forms. e.g. (+ 3 1 (+ 2 2)) => [4 7]." {:arglists '([op value & forms])} [op value & forms] `(vector ~@(map (fn [f] `(~op ~f ~value)) forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro last-index "count less 1." {:arglists '([coll])} [coll] `(- (count ~coll) 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro nexth "The nth item after i." {:arglists '([coll i])} [coll i] `(nth ~coll (+ 1 ~i))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro chop "Same as partition." {:arglists '([& args])} [& args] `(partition ~@args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro inc* "One plus, x+1." {:arglists '([x])} [x] `(+ 1 ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro dec* "One less, x-1." {:arglists '([x])} [x] `(- ~x 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do->false "Do returns false." {:arglists '([& forms])} [& forms] `(do ~@forms false)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do->true "Do returns true." {:arglists '([& forms])} [& forms] `(do ~@forms true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do->nil "Do returns nil." {:arglists '([& forms])} [& forms] `(do ~@forms nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro let->false "Let returns false." {:arglists '([& forms])} [& forms] `(let ~@forms false)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro let->true "Let returns true." {:arglists '([& forms])} [& forms] `(let ~@forms true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro let->nil "Let returns nil." {:arglists '([& forms])} [& forms] `(let ~@forms nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defenum "Enum definition. e.g. (defenum ^:private xyz 1 a b c) will generate (def ^:private xyz-a 1) (def ^:private xyz-b 2) (def ^:private xyz-c 3)." {:arglists '([ename start & args])} [ename start & args] (let [mm (meta ename)] (assert (number? start) "Enum expecting a number.") `(do ~@(loop [v start [m & ms] args out []] (if (nil? m) out (let [m' (meta m) z (str (name ename) "-" (name m))] (recur (+ 1 v) ms (conj out `(def ~(with-meta (symbol z) (merge m' mm)) ~v))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro condp?? "condp without throwing exception." {:arglists '([pred expr & clauses])} [pred expr & clauses] (let [c (count clauses) z (count (filter #(and (keyword? %) (= :>> %)) clauses)) d (- c z) xs (if-not (even? d) clauses (concat clauses ['nil]))] `(condp ~pred ~expr ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro case?? "case without throwing exception." {:arglists '([expr & clauses])} [expr & clauses] (let [c (count clauses) xs (if-not (even? c) clauses (concat clauses ['nil]))] `(case ~expr ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-xxx?? {:arglists '([F bindings then] [F bindings then else])} ([F bindings then] `(if-xxx?? ~F ~bindings ~then nil)) ([F bindings then else & oldform] (let [_ (assert (== 2 (count bindings)) "Too many (> 2) in bindings.") X (gensym) f1 (first bindings)] (assert (symbol? f1)) `(let [~X ~(last bindings) ~f1 ~X] (if (~F ~X) ~then ~else))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-inst "If expr is instance of class, execute `then`, otherwise `else`." {:arglists '([clazz expr then] [clazz expr then else])} ([clazz expr then] `(if-inst ~clazz ~expr ~then nil)) ([clazz expr then else & oldform] `(if (instance? ~clazz ~expr) ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-inst "If expr is instance of class, execute `body`." {:arglists '([clazz expr & body])} [clazz expr & body] `(if (instance? ~clazz ~expr) (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-proto "If expr satisfies the protocol, execute `then`, otherwise `else`." {:arglists '([proto expr then] [proto expr then else])} ([proto expr then] `(if-proto ~proto ~expr ~then nil)) ([proto expr then else & oldform] `(if (satisfies? ~proto ~expr) ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-proto "If expr satisfies the protocol, execute `body`." {:arglists '([proto expr & body])} [proto expr & body] `(if (satisfies? ~proto ~expr) (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-nil "If expr evals to nil, execute `then`, otherwise `else`." {:arglists '([expr then] [expr then else])} ([expr then] `(if-nil ~expr ~then nil)) ([expr then else & oldform] `(if (nil? ~expr) ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-nil "If expr evals to nil, execute `body`." {:arglists '([expr & body])} [expr & body] `(if (nil? ~expr) (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn is-throwable? "If object is a Throwable?" {:arglists '([x])} [x] (instance? Throwable x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-throw "bindings => binding-form test If test is a Throwable, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-throw ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? czlab.basal.core/is-throwable? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-throw "bindings => binding-form test If test is a Throwable, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-throw ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-var "bindings => binding-form test If test is a var, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-var ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? var? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-var "bindings => binding-form test If test is a var, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-var ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-number "bindings => binding-form test If test is a number, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-number ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? number? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-number "bindings => binding-form test If test is a number, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-number ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-string "bindings => binding-form test If test is a string, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-string ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? string? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-string "bindings => binding-form test If test is a string, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-string ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro nloop "Loop over code n times." {:arglists '([n & forms])} [n & forms] (let [x (gensym)] `(dotimes [~x ~n] ~@forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro each* "Evals function for each element, indexed." {:arglists '([func coll])} [func coll] (let [C (gensym) I (gensym) T (gensym)] `(let [~C ~coll ~T (count ~C)] (dotimes [~I ~T] (~func (nth ~C ~I) ~I))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro each "Evals function for each element." {:arglists '([func coll])} [func coll] (let [I (gensym)] `(doseq [~I ~coll] (~func ~I)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro mget "Java map.get()." {:arglists '([m k])} [m k] `(.get ~(with-meta m {:tag 'java.util.Map}) ~k)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mdel! "Java map.remove()." {:arglists '([m k])} [m k] (.remove ^java.util.Map m k)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro mput! "Java map.put()." {:arglists '([m k v])} [m k v] `(.put ~(with-meta m {:tag 'java.util.Map}) ~k ~v)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;testing stuff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro deftest "A bunch of test-cases grouped together." {:arglists '([name & body])} [name & body] `(def ~name (fn [] (filter #(not (nil? %)) [~@body])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ensure?? "Assert test was ok." {:arglists '([msg form])} [msg form] `(czlab.basal.core/ensure-test ~form ~msg)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ensure-thrown?? "Assert an error was thrown." {:arglists '([msg expected form])} [msg expected form] `(try ~form (czlab.basal.core/ensure-thrown ~msg) (catch Throwable e# (czlab.basal.core/ensure-thrown ~expected e# ~msg)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro prn!! "Println with format." {:arglists '([fmt & args])} [fmt & args] `(println (format ~fmt ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro prn! "Print with format." {:arglists '([fmt & args])} [fmt & args] `(print (format ~fmt ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (defmacro- make-fn "Hack to wrap a macro as fn so one can use *apply* on it." [m] `(fn [& xs#] (eval (cons '~m xs#))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro object<> "Create a new record instance. e.g. (object<> ClazzA) (object<> ClazzA {:a 1}) (object<> ClazzA :a 1 :b 2)" {:arglists '([z] [z m] [z ab & more])} ([z] `(new ~z)) ([z m] `(merge (new ~z) ~m)) ([z a b & more] `(assoc (new ~z) ~a ~b ~@more))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro atomic<> "Create a new record instance, with all attributes inside an atom. e.g. (atomic<> ClazzA) (atomic<> ClazzA {:a 1}) (atomic<> ClazzA :a 1 :b 2)" {:arglists '([z] [z m] [z ab & more])} ([z] `(assoc (new ~z) :o (atom {}))) ([z m] `(assoc (new ~z) :o (atom (merge {} ~m)))) ([z a b & more] `(assoc (new ~z) :o (atom (assoc {} ~a ~b ~@more))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vargs "Coerce into java array of type z." {:arglists '([z arglist])} [z arglist] `(into-array ~z ~arglist)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro preduce<map> "Reduce with a transient map accumulator, returning a map." {:arglists '([f coll])} [f coll] `(persistent! (reduce ~f (transient {}) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro preduce<set> "Reduce with a transient set accumulator, returning a set." {:arglists '([f coll])} [f coll] `(persistent! (reduce ~f (transient #{}) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro preduce<vec> "Reduce with a transient vec accumulator, returning a vec." {:arglists '([f coll])} [f coll] `(persistent! (reduce ~f (transient []) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rset! "Reset a atom." {:arglists '([a] [a value])} ([a] `(rset! ~a nil)) ([a value] `(reset! ~a ~value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro exp! "Create an exception of type E." {:arglists '([E & args])} [E & args] `(new ~E ~@args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro trap! "Throw exception of type E." {:arglists '([E & args])} [E & args] `(throw (exp! ~E ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro raise! "Throw java Exception with message." {:arglists '([fmt & args])} [fmt & args] `(throw (new java.lang.Exception (str (format ~fmt ~@args))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-assert-exp "Generate a function which when called, will assert the condition and if false, throw the desired exception." {:arglists '([name E])} [name E] `(defn ~name [~'kond ~'arg & ~'xs] (if-not ~'kond (cond (string? ~'arg) (czlab.basal.core/trap! ~E (str (apply format ~'arg ~'xs))) (instance? Throwable ~'arg) (czlab.basal.core/trap! ~E ~(with-meta 'arg {:tag 'Throwable})))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-throw-exp "Generate a function which when called, will throw the desired exception." {:arglists '([name E])} [name E] `(defn ~name [~'arg & ~'xs] (cond (string? ~'arg) (czlab.basal.core/trap! ~E (str (apply format ~'arg ~'xs))) (instance? Throwable ~'arg) (czlab.basal.core/trap! ~E ~(with-meta 'arg {:tag 'Throwable}))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro assert-on! "Like assert, but throws a specific exception." {:arglists '([kond E & args])} [kond E & args] `(if-not ~kond (trap! ~E ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do-with "bindings => [symbol init-expr] Evals the body in a context in which the symbol is always the returned value." {:arglists '([bindings & forms])} [bindings & forms] (let [f (first bindings) sz (count bindings)] (assert (or (== sz 1) (== sz 2)) "(not 1 or 2) in bindings.") (assert (symbol? f)) (if (== sz 1) `(let [~f ~f] ~@forms ~f) `(let [~f ~(last bindings)] ~@forms ~f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do-with-str "bindings => [symbol init-expr] Eval the body in a context in which the symbol is always the returned value to-string'ed. e.g. (do-with-str [a (f)] ... (str a))." {:arglists '([bindings & forms])} [bindings & forms] `(str (czlab.basal.core/do-with ~bindings ~@forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do-with-atom "bindings => [symbol init-expr] Eval the body in a context in which the symbol is always the returned value deref'ed. e.g. (do-with-atom [a (atom 0)] ... (deref a))." {:arglists '([bindings & forms])} [bindings & forms] `(deref (czlab.basal.core/do-with ~bindings ~@forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro bool! "Same as boolean." {:arglists '([x])} [x] `(boolean ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro trye! "Eat exception and return a value." {:arglists '([value & forms])} [value & forms] `(try ~@forms (catch Throwable ~'_ ~value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro try! "Eat exception and return nil." {:arglists '([& forms])} [& forms] `(czlab.basal.core/trye! nil ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-some+ "bindings => [binding-form test]. When test is not empty, evaluates body with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-some+ ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? empty? ~bindings ~else ~then))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-some+ "bindings => [binding-form test]. When test is not empty, evaluates body with binding-form bound to the value of test." {:arglists '([bindings & body])} [bindings & body] `(czlab.basal.core/if-some+ ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-fn "bindings => [binding-form test]. When test is a fn?, evaluates body with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-fn ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? fn? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-fn "bindings => [binding-form test]. When test is a fn?, evaluates body with binding-form bound to the value of test." {:arglists '([bindings & body])} [bindings & body] `(czlab.basal.core/if-fn ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro doto->> "Combine doto and ->>." {:arglists '([x & forms])} [x & forms] (let [X (gensym)] `(let [~X ~x] ~@(map (fn [f] (if (seq? f) `(~@f ~X) `(~f ~X))) forms) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro doto-> "Combine doto and ->." {:arglists '([x & forms])} [x & forms] (let [X (gensym)] `(let [~X ~x] ~@(map (fn [f] (if (seq? f) (let [z (first f) r (rest f)] `(~z ~X ~@r)) `(~f ~X))) forms) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro eq? "Use java's .equals method." {:arglists '([a b])} [a b] `(.equals ~a ~b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !eq? "Use java's .equals method." {:arglists '([a b])} [a b] `(not (.equals ~a ~b))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !=? "Same as not-identical?" {:arglists '([& more])} [& more] `(not (identical? ~@more))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro =? "Same as identical?" {:arglists '([& more])} [& more] `(identical? ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !in? "Same as not-contains?" {:arglists '([& more])} [& more] `(not (contains? ~@more))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro in? "Same as contains?" {:arglists '([& more])} [& more] `(contains? ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;had to use this trick to prevent reflection warning (defmacro cast? "Cast object of this type else nil." {:arglists '([someType obj])} [someType obj] (let [X (gensym)] `(let [~X ~obj] (if (instance? ~someType ~X) ^{:tag ~someType} (identity (.cast ~someType ~X)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cexp? "Try casting to Throwable." {:arglists '([e])} [e] `(cast? Throwable ~e)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !nil? "Same as not-nil." {:arglists '([x])} [x] `(not (nil? ~x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rnil "Skip nil(s) in collection." {:arglists '([coll])} [coll] `(remove nil? ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rnilv "Same as rnil but returns a vec." {:arglists '([coll])} [coll] `(into [] (remove nil? ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro szero? "Safe zero?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E)(zero? ~E))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sneg? "Safe neg?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E)(neg? ~E))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro spos? "Safe pos?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E)(pos? ~E))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro snneg? "Safe not neg?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E) (or (zero? ~E)(pos? ~E)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !false? "Same as not-false." {:arglists '([x])} [x] `(not (false? ~x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !true? "Same as not true." {:arglists '([x])} [x] `(not (true? ~x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro assert-not "Assert a false condition." {:arglists '([cond])} [cond] `(assert (not ~cond))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro marray "n-size java array of type Z." {:arglists '([Z n])} [Z n] `(make-array ~Z ~n)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro zarray "0-size java array of type Z." {:arglists '([Z])} [Z] `(make-array ~Z 0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vtbl** "Make a virtual table: op1 f1 op2 f2, with parent vtbl." {:arglists '([parent & args])} [parent & args] (do (assert (even? (count args))) `(czlab.basal.core/object<> ~'czlab.basal.core.VTable :____proto ~parent ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vtbl* "Make a virtual table: op1 f1 op2 f2." {:arglists '([& args])} [& args] `(vtbl** nil ~@args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro wo* "Same as with-open." {:arglists '([bindings & forms])} [bindings & forms] `(with-open ~bindings ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro wm* "Same as with-meta." {:arglists '([obj m])} [obj m] `(with-meta ~obj ~m)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ->str "Same as java's .toString." {:arglists '([obj])} [obj] `(some-> ~obj .toString)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;monads ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro run-bind ;"Run the bind operator. *Internal*" {:arglists '([binder steps expr])} [binder steps expr] (let [more (drop 2 steps) [a1 mv] (take 2 steps)] `(~binder ~mv (fn [~a1] ~(if (not-empty more) `(run-bind ~binder ~more ~expr) `(do ~expr)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defmonad "Define a named monad by defining the monad operations. The definitions are written like bindings to the monad operations bind and unit (required) and zero and plus (optional)." {:arglists '([name ops] [name docs ops])} ([name ops] `(defmonad ~name "" ~ops)) ([name docs ops] (let [_ (assert (not-empty ops) "no monad ops!")] `(def ~(with-meta name {:doc docs}) (merge {:bind nil :unit nil :zero nil :plus nil} (into {} (map #(vec %) (partition 2 ~ops)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro domonad "Monad comprehension. Takes the name of a monad, a vector of steps given as binding-form, and a result value specified by body." {:arglists '([monad steps] [monad steps body])} ([monad steps] `(domonad ~monad ~steps nil)) ([monad steps body] (let [E (gensym) B (gensym) U (gensym) Z (gensym)] `(let [{~B :bind ~U :unit ~Z :zero} ~monad ;if no body try to run the zero func, ;else run the unit on it. ~E #(if (and (nil? %) (some? ~Z)) ~Z (~U %))] (czlab.basal.core/run-bind ~B ~steps (~E ~body)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;end-macros ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;monads ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-identity "Monad describing plain computations. This monad does nothing at all. It is useful for testing, for combination with monad transformers, and for code that is parameterized with a monad." [:bind (fn [mv mf] (mf mv)) :unit identity]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-maybe "Monad describing computations with possible failures. Failure is represented by nil, any other value is considered valid. As soon as a step returns nil, the whole computation will yield nil as well." [:unit identity :bind (fn [mv mf] (if-not (nil? mv) (mf mv)))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-list "Monad describing multi-valued computations, i.e. computations that can yield multiple values. Any object implementing the seq protocol can be used as a monadic value." [:bind (fn [mv mf] (flatten (map mf mv))) :unit (fn_1 (vector ____1)) :zero [] :plus (fn_* (flatten ____xs))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-state "Monad describing stateful computations. The monadic values have the structure (fn [old-state] [result new-state])." [:unit (fn [v] (fn [s] [v s])) :bind (fn [mv mf] (fn [s] (let [[v s'] (mv s)] ((mf v) s'))))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-continuation "Monad describing computations in continuation-passing style. The monadic values are functions that are called with a single argument representing the continuation of the computation, to which they pass their result." [:unit (fn [v] (fn [cont] (cont v))) :bind (fn [mv mf] (fn [cont] (mv (fn [v] ((mf v) cont)))))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn run-cont "Execute the computation in the cont monad and return its result." {:arglists '([cont])} [cont] (cont identity)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; end-monad ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn kvs->map "Turn a list of key values into map." {:arglists '([arglist])} [arglist] {:pre [(even? (count arglist))]} (apply array-map arglist)) ;(into {} (map #(vec %) (partition 2 arglist))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn repeat-str "Repeat string n times." {:tag String :arglists '([n s])} [n s] (cs/join "" (repeat n s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn num?? "If n is not a number, return other." {:arglists '([n other])} [n other] {:pre [(number? other)]} (if (number? n) n other)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn !== "Same as (not (== num1 num2))." {:arglists '([x] [x y] [x y & more])} ([x] false) ([x y] (not (== x y))) ([x y & more] (not (apply == x y more)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn flip "Invert number if not zero." {:arglists '([x])} [x] {:pre [(number? x)]} (if (zero? x) 0 (/ 1 x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn percent "Calculate the percentage." {:arglists '([numerator denominator])} [numerator denominator] (* 100.0 (/ numerator denominator))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn split-seq "Split a collection into 2 parts." {:arglists '([coll cnt])} [coll cnt] (if-not (< cnt (count coll)) (list (concat [] coll) ()) (list (take cnt coll) (drop cnt coll)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn compare-asc* "Returns a ascending compare function." {:arglists '([] [f])} ([] (compare-asc* identity)) ([f] (fn_2 (cond (< (f ____1) (f ____2)) -1 (> (f ____1) (f ____2)) 1 :else 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn compare-des* "Returns a descending compare function." {:arglists '([] [f])} ([] (compare-des* identity)) ([f] (fn_2 (cond (< (f ____1) (f ____2)) 1 (> (f ____1) (f ____2)) -1 :else 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- xxx-by "Used by min-by & max-by. *Internal*" {:arglists '([cb coll])} [cb coll] (if (not-empty coll) (reduce cb (_1 coll) (rest coll)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn min-by "Find item with minimum value as defined by the function." {:arglists '([f coll])} [f coll] (xxx-by #(if (< (f %1) (f %2)) %1 %2) coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn max-by "Find item with maximum value as defined by the function." {:arglists '([f coll])} [f coll] (xxx-by #(if (< (f %1) (f %2)) %2 %1) coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ensure-test "Assert a test condition, returning a message." {:arglists '([cond msg])} [cond msg] (str (try (if cond t-ok t-bad) (catch Throwable _ t-bad)) ": " msg)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ensure-thrown "Assert an exception is thrown during test." {:arglists '([msg] [expected error msg])} ([msg] (ensure-thrown nil nil msg)) ([expected error msg] (str (if (nil? error) t-bad (if (or (= expected :any) (is? expected error)) t-ok t-bad)) ": " msg))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rip-fn-name "Extract (mangled) name of the function." {:tag String :arglists '([func])} [func] (let [s (str func) h (cs/index-of s "$") s (if h (subs s (+ 1 h)) s) p (cs/last-index-of s "@")] (if p (subs s 0 p) s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-int "Operate like a mutable int, get and set." {:arglists '([] [arr] [arr v] [arr op nv])} ;setter ([^ints arr v] (aset arr 0 (int v)) (int v)) ;ctor ([] (int-array 1 0)) ;getter ([^ints arr] (int (aget arr 0))) ;apply (op old-val new-value) ([^ints arr op nv] (let [v (int (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-int* "Create & init mu-i." {:arglists '([i])} [i] {:pre [(number? i)]} (doto (mu-int) (mu-int i))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-long "Operate like a mutable long, get and set." {:arglists '([] [arr] [arr v] [arr op nv])} ;setter ([^longs arr v] (aset arr 0 (long v)) (long v)) ;ctor ([] (long-array 1 0)) ;getter ([^longs arr] (long (aget arr 0))) ;apply (op old-val new-val) ([^longs arr op nv] (let [v (long (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-long* "Create & init a mu-long." {:arglists '([n])} [n] {:pre [(number? n)]} (doto (mu-long) (mu-long n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nth?? "Get the nth element, 1-indexed." {:arglists '([coll pos])} [coll pos] {:pre [(> pos 0)]} (first (drop (- pos 1) coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn vargs* "Coerce into java array." {:arglists '([clazz & args])} [clazz & args] (vargs clazz args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (defn- interject "Run the function on the current field value, replacing the key with the returned value. function(pojo oldvalue) -> newvalue." [pojo field func] {:pre [(map? pojo) (fn? func)]} (assoc pojo field (func pojo field)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn scoped-keyword "Scope name as a fully-qualified keyword." {:arglists '([t])} [t] {:pre [(string? t) (nil? (cs/index-of t "/")) (nil? (cs/index-of t ":"))]} (keyword (str *ns*) t)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn is-scoped-keyword? "If a scoped keyword?" {:arglists '([kw])} [kw] (and (keyword? kw) (cs/includes? (str kw) "/"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rand-sign "Randomly choose a sign." {:arglists '([])} [] (if (even? (rand-int Integer/MAX_VALUE)) 1 -1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rand-bool "Randomly choose a boolean value." {:arglists '([])} [] (even? (rand-int Integer/MAX_VALUE))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn num-sign "Find the sign of a number." {:arglists '([n])} [n] {:pre [(number? n)]} (cond (> n 0) 1 (< n 0) -1 :else 0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->long "String as a long value." {:tag Long :arglists '([s] [s dv])} ([s] (s->long s nil)) ([s dv] (try (Long/parseLong ^String s) (catch Throwable _ (if (number? dv) (long dv) (throw _)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->int "String as an int value." {:tag Integer :arglists '([s] [s dv])} ([s] (s->int s nil)) ([s dv] (try (Integer/parseInt ^String s) (catch Throwable _ (if (number? dv) (int dv) (throw _)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->double "String as a double value." {:tag Double :arglists '([s][s dv])} ([s] (s->double s nil)) ([s dv] (try (Double/parseDouble ^String s) (catch Throwable _ (if (number? dv) (double dv) (throw _)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->bool "String as a boolean value." {:arglists '([s])} [s] (contains? BOOLS (cs/lower-case (str s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; test and assert funcs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-isa "Is child of parent?" {:arglists '([reason parent child])} [reason parent child] (do->true (-> (cond (and (class? parent) (class? child)) (isa? child parent) (or (nil? parent) (nil? child)) false (not (class? parent)) (test-isa reason (class parent) child) (not (class? child)) (test-isa reason parent (class child))) (assert (str reason child " not-isa " parent))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-some "Object is not null?" {:arglists '([reason obj])} [reason obj] (do->true (assert (some? obj) (str reason " is null.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-cond "A true condition?" {:arglists '([reason cond])} [reason cond] (do->true (assert cond (str reason)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-hgl "String is not empty?" {:arglists '([reason s])} [reason s] (do->true (assert (and (string? s) (not-empty s)) (str reason " is empty.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- test-xxx [a b] (condp instance? b Double :double Long :long Float :double Integer :long (raise! "Allow numbers only!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti test-pos0 "Check number is not negative?" test-xxx) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti test-pos "Check number is positive?" test-xxx) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos0 :double [reason v] (do->true (assert (snneg? v) (str reason " must be >= 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos0 :long [reason v] (do->true (assert (snneg? v) (str reason " must be >= 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos :double [reason v] (do->true (assert (spos? v) (str reason " must be > 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos :long [reason v] (do->true (assert (spos? v) (str reason " must be > 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-seq+ "Check sequence is not empty?" {:arglists '([reason v])} [reason v] (do->true (assert (pos? (count v)) (str reason " must be non empty.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sort-join "Sort and concatenate strings." {:tag String :arglists '([ss] [sep ss])} ([ss] (sort-join "" ss)) ([sep ss] (if (nil? ss) "" (cs/join sep (sort ss))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn strip-ns-path "Remove the leading colon." {:tag String :arglists '([path])} [path] (cs/replace (str path) #"^:" "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol VTableAPI "Act like a virtual table." (vt-set-proto [_ par] "Hook up parent prototype object.") (vt-has? [_ kee] "True if key exists in the hierarchy.") (vt-run?? [_ kee arglist] [_ kee arglist skip?] "Find key. If function run it else return value.") (vt-find?? [_ kee] [_ kee skip?] "Find this key, if skip? then search from parent.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord VTable [] VTableAPI (vt-set-proto [me par] (assoc me :____proto par)) (vt-find?? [me kee] (vt-find?? me kee false)) (vt-find?? [me kee skip?] (let [p (:____proto me)] (cond skip? (if p (vt-find?? p kee)) (in? me kee) (get me kee) :else (if p (vt-find?? p kee))))) (vt-has? [me kee] (or (in? me kee) (if-some [p (:____proto me)] (vt-has? p kee)))) (vt-run?? [me kee arglist] (vt-run?? me kee arglist false)) (vt-run?? [me kee arglist skip?] (let [f (vt-find?? me kee skip?)] (if (fn? f) (apply f me arglist) f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn identity-n "Like identity but returns positional param. e.g. (def get-2nd (identity-n 2)) (get-2nd a b c) => b." {:arglists '([n] [n index-zero?])} ([n] (identity-n n false)) ([n index-zero?] {:pre [(number? n)]} (fn_* (let [z (count ____xs) p (if index-zero? n (- n 1))] (assert (and (< p z) (>= p 0)) "Index out of bound.") (nth ____xs p))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- merge-2 [a b] (if (nil? a) b (if (nil? b) a (loop [[z & M] (seq b) tmp (tmap* a)] (let [[k vb] z va (get a k)] (if (nil? z) (persist! tmp) (recur M (assoc! tmp k (cond (not (in? a k)) vb (and (map? vb) (map? va)) (merge-2 va vb) (and (set? vb) (set? va)) (ct/union va vb) :else vb))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn merge+ "Merge (deep) of clojure data." {:arglists '([& more])} [& more] (cond (empty? more) nil (one? more) (_1 more) :else (loop [prev nil [a & xs] more] (if (empty? xs) (merge-2 prev a) (recur (merge-2 prev a) xs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;string stuff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sreduce<> "Reduce with a string-builder." {:arglists '([f coll])} [f coll] `(str (reduce ~f (StringBuilder.) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fmt "Same as string format." {:tag String :arglists '([f & args])} [f & args] (apply format f args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn char-array?? "Splits a string into string-char, e.g. \"abc\" = [\"a\" \"b\" \"c\"]." {:arglists '([s])} [s] {:pre [(or (nil? s) (string? s))]} (remove empty? (cs/split s #""))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbf+ "StringBuilder concat." {:tag StringBuilder :arglists '([buf & args])} [buf & args] (doseq [x args] (.append ^StringBuilder buf x)) buf) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbf<> "Same as StringBuilder.new" {:tag StringBuilder :arglists '([] [& args])} ([] (sbf<> "")) ([& args] (let [s (StringBuilder.)] (apply sbf+ s args) s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbf-join "Append to a string-builder, optionally inserting a delimiter if the buffer is not empty." {:tag StringBuilder :arglists '([buf sep item])} [buf sep item] (do-with [^StringBuilder buf] (when item (if (and (!nil? sep) (pos? (.length buf))) (.append buf sep)) (.append buf item)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbfz "Length of the string-buffer." {:arglists '([b])} [b] (.length ^StringBuilder b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nichts? "Is string empty?" {:arglists '([s])} [s] (or (nil? s) (not (string? s)) (.isEmpty ^String s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hgl? "If string has length?" {:arglists '([s])} [s] (and (string? s) (not (.isEmpty ^String s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn stror "If not s then s2" {:tag String :arglists '([s s2])} [s s2] (if (nichts? s) s2 s)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (defn stror* "If not s then s2...etc" ^String [& args] (loop [[a & more] args] (if (or (hgl? a) (empty? more)) a (recur more))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro stror* "If not s then s2...etc" {:arglists '([& args])} [& args] (let [[a & xs] args] (if (empty? xs) `(stror nil ~a) `(stror ~a (stror* ~@xs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn lcase "Lowercase string safely." {:tag String :arglists '([s])} [s] (str (some-> s clojure.string/lower-case))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ucase "Uppercase string safely." {:tag String :arglists '([s])} [s] (str (some-> s clojure.string/upper-case))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;#^"[Ljava.lang.Class;" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn triml "Get rid of unwanted chars from left." {:tag String :arglists '([src unwantedChars])} [^String src ^String unwantedChars] (if-not (and (hgl? src) (hgl? unwantedChars)) src (loop [len (.length src) pos 0] (if-not (and (< pos len) (cs/index-of unwantedChars (.charAt src pos))) (subs src pos) (recur len (+ 1 pos)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn trimr "Get rid of unwanted chars from right." {:tag String :arglists '([src unwantedChars])} [^String src ^String unwantedChars] (if-not (and (hgl? src) (hgl? unwantedChars)) src (loop [pos (.length src)] (if-not (and (pos? pos) (cs/index-of unwantedChars (.charAt src (- pos 1)))) (subs src 0 pos) (recur (- pos 1)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn includes? "If the char is inside the big str?" {:arglists '([bigs arg])} [^String bigs arg] (let [rc (cond (or (nil? arg) (nil? bigs)) false (integer? arg) (int arg) (string? arg) (number? (cs/index-of bigs arg)) (is? Character arg) (int (.charValue ^Character arg)))] (if-not (number? rc) rc (>= (.indexOf bigs (int rc)) 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro embeds? "If sub-str is inside the big str?" {:arglists '([bigs s])} [bigs s] `(czlab.basal.core/includes? ~bigs ~s)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro has-no-case? "If sub-str is inside the big str - ignore case?" {:arglists '([bigs s])} [bigs s] `(czlab.basal.core/includes? (czlab.basal.core/lcase ~bigs) (czlab.basal.core/lcase ~s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn index-any "If any one char is inside the big str, return the position." {:arglists '([bigs chStr])} [^String bigs ^String chStr] (if-not (and (hgl? bigs) (hgl? chStr)) -1 (let [rc (some #(cs/index-of bigs %) (.toCharArray chStr))] (if (nil? rc) -1 (int rc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn count-str "Count the times the sub-str appears in the big str." {:arglists '([bigs s])} [^String bigs ^String s] (if-not (and (hgl? s) (hgl? bigs)) 0 (loop [len (.length s) total 0 start 0] (let [pos (cs/index-of bigs s start)] (if (nil? pos) total (recur len (+ 1 total) (long (+ pos len)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn count-char "Count the times this char appears in the big str." {:arglists '([bigs ch])} [bigs ch] (reduce #(if (= ch %2) (+ 1 %1) %1) 0 (.toCharArray ^String bigs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sname "Safely get the name of this object." {:arglists '([n])} [n] `(str (some-> ~n name))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nsb "Empty string if obj is null, or obj.toString." {:tag String :arglists '([obj])} [obj] (if (keyword? obj) (name obj) (str obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn kw->str "Stringify a keyword - no leading colon." {:tag String :arglists '([k])} [k] (cs/replace (str k) #"^:" "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->kw "Concatenate all args and return it as a keyword." {:arglists '([& args])} [& args] (if-not (empty? args) (keyword (apply str args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nsn "(null) if obj is null, or obj.toString." {:tag String :arglists '([obj])} [obj] (if (nil? obj) "(null)" (str obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn match-char? "If this char is inside this set of chars?" {:arglists '([ch setOfChars])} [ch setOfChars] (and (set? setOfChars) (contains? setOfChars ch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro strim "Safely trim this string." {:arglists '([s])} [s] `(str (some-> ~s clojure.string/trim))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn strim-any "Strip source string of these unwanted chars." {:tag String :arglists '([src unwantedChars] [src unwantedChars whitespace?])} ([src unwantedChars] (strim-any src unwantedChars false)) ([^String src ^String unwantedChars whitespace?] (let [s (-> (if whitespace? (strim src) src) (triml unwantedChars) (trimr unwantedChars))] (if whitespace? (strim s) s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn splunk "Split a large string into chunks, each chunk having a specific length." {:arglists '([largeString chunkLength])} [^String largeString chunkLength] (if-not (and (hgl? largeString) (snneg? chunkLength)) [] (mapv #(cs/join "" %1) (partition-all chunkLength largeString)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hasic-any? "If bigs contains any one of these strs - ignore case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (empty? substrs) (nichts? bigs)) (let [lc (lcase bigs)] (true? (some #(number? (cs/index-of lc (lcase %))) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn has-any? "If bigs contains any one of these strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (true? (some #(number? (cs/index-of bigs %)) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hasic-all? "If bigs contains all of these strs - ignore case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (empty? substrs) (nichts? bigs)) (let [lc (lcase bigs)] (every? #(number? (cs/index-of lc (lcase %))) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn has-all? "If bigs contains all of these strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (every? #(number? (cs/index-of bigs %)) substrs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ewic-any? "If bigs endsWith any one of the strs, no-case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (let [lc (lcase bigs)] (true? (some #(cs/ends-with? lc (lcase %)) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ew-any? "If bigs endsWith any one of the strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (true? (some #(cs/ends-with? bigs %) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn swic-any? "If bigs startWith any one of the strs - no case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (let [lc (lcase bigs)] (true? (some #(cs/starts-with? lc (lcase %)) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sw-any? "If bigs startWith any one of the strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (true? (some #(cs/starts-with? bigs %) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro eqic? "Same as String.equalIgnoreCase()?" {:arglists '([src other])} [src other] (let [^String ss src ^String oo other] `(.equalsIgnoreCase ~ss ~oo))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn eqic-any? "String.equalIgnoreCase() on any one of the strs?" {:arglists '([src substrs])} [^String src substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? src) (empty? substrs)) (let [lc (lcase src)] (true? (some #(= lc (lcase %)) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn eq-any? "If String.equals() on any one of the strs?" {:arglists '([src substrs])} [^String src substrs] {:pre [(sequential? substrs)]} (if-not (empty? substrs) (true? (some #(.equals src %) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn wrapped? "If src string starts with head and ends with tail?" {:arglists '([src head tail])} [^String src ^String head ^String tail] (if (and (hgl? src) (hgl? head) (hgl? tail)) (and (cs/starts-with? src head) (cs/ends-with? src tail)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rights "Get the rightmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (if (or (<= len 0) (nichts? src)) "" (if (< (.length src) len) src (subs src (- (.length src) len))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn lefts "Get the leftmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (if (or (<= len 0) (nichts? src)) "" (if (< (.length src) len) src (subs src 0 len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn drop-head "Drop leftmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (cond (nichts? src) "" (<= len 0) src :else (if (< (.length src) len) "" (subs src len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn drop-tail "Drop rightmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (cond (nichts? src) "" (<= len 0) src :else (let [n (.length src)] (if (< n len) "" (subs src 0 (- n len)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn matches? "Same as String.matches." {:arglists '([src regex])} [src regex] {:pre [(string? regex)]} (if (hgl? src) (.matches ^String src ^String regex))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn split "Same as String.split." {:arglists '([src regex] [src regex limit])} ([src regex] (split src regex nil)) ([src regex limit] {:pre [(string? regex)]} (if (hgl? src) (remove empty? (if-not (number? limit) (.split ^String src ^String regex) (.split ^String src ^String regex (int limit))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn split-str "Same as String-tokenizer." {:arglists '([s sep] [s sep incSep?])} ([s sep] (split-str s sep false)) ([s sep incSep?] (let [t (new java.util.StringTokenizer ^String s ^String sep (boolean incSep?))] (loop [rc (tvec*)] (if-not (.hasMoreTokens t) (persist! rc) (recur (conj! rc (.nextToken t)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn esc-xml "Escape XML special chars." {:tag String :arglists '([s])} [s] (cs/escape s {\& "&amp;" \> "&gt;" \< "&lt;" \" "&quot;" \' "&apos;"})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- run-test [test] (let [res (test)] [res (every? #(cs/starts-with? % "p") res)])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pretty-millis "Pretty print milliseconds value." {:tag String :arglists '([millis])} [millis] {:pre [(number? millis)]} (let [secs (int (/ millis 1000.0)) millis (int (- millis (* secs 1000.0))) mins (int (/ secs 60.0)) secs (int (- secs (* mins 60.0))) hours (int (/ mins 60.0)) mins (int (- mins (* hours 60.0)))] (cond (pos? hours) (fmt "%d hours %2d minutes %2d.%03d secs" hours mins secs millis) (pos? mins) (fmt "%2d minutes %2d.%03d secs" mins secs millis) (pos? secs) (fmt "%2d.%03d seconds" secs millis) :else (fmt "0.%03d seconds" millis)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- prn-test [results title diff] (let [lsep (repeat-str 78 "+") esep (repeat-str 78 "=") sum (count results) f (filter #(cs/starts-with? % "F") results) p (filter #(cs/starts-with? % "p") results) ok (count p) perc (percent ok sum)] (-> lsep ansi/bold-white prn!!) (-> "test-case: " ansi/bold-white prn!) (-> (stror title (rip-fn-name test)) cs/upper-case ansi/bold-yellow prn!!) (-> (str (Date.)) ansi/bold-white prn!!) (-> lsep ansi/bold-white prn!!) (doseq [r p] (-> r ansi/bold-green prn!!)) (doseq [r f] (-> r ansi/bold-red prn!!)) (-> esep ansi/bold-white prn!!) (-> (str "Passed: " ok "/" sum " [" (int perc) "%%]") ansi/bold-white prn!!) (-> (str "Failed: " (- sum ok)) ansi/bold-white prn!!) (-> (str "cpu-time: " (pretty-millis diff)) ansi/bold-white prn!!) (-> "" ansi/white prn!!))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn clj-test?? "Run test as a clojure test case." {:arglists '([test] [test title print?])} ([test] (clj-test?? test nil true)) ([test title print?] {:pre [(fn? test)]} (let [mark (System/currentTimeMillis) [res ok?] (run-test test) diff (- (System/currentTimeMillis) mark)] (if print? (prn-test res title diff)) ok?))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;protocols ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol AtomicGS "" (getf [_ n] "Get field") (setf [_ n v] "Set field")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Activable "Something that can be activated." (deactivate [_] "") (activate [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Cancelable "Something that can be canceled." (cancel [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Testable "Something that can be tested for validity." (is-valid? [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Catchable "Something that can catch an Exception." (catche [_ e] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Configurable "Something that can be configured with key-values." (get-conf [_] [_ k] "") (set-conf [_ arg] [_ k v] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Debuggable "Something that can be debugged." (dbg-str [_] "") (dbg-show [_ ^PrintStream out] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Dispatchable "Something that can be dispatched, like an observer." (add-handler [_ handler] "") (remove-handler [_ handler] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Disposable "Something that can be disposed." (dispose [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Enqueable "Something that can be enqueued." (put [_ something] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Gettable "Something that gives access to key-values." (getv [_ key] "") (has? [_ key] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Hierarchical "Something that has a parent." (parent [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Idable "Something that can be identified." (id [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Initable "Something that can be initialized." (init [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Finzable "Something that can be finalized - opposite to initialize." (finz [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Interruptable "Something that can be interrupted." (interrupt [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Schedulable "Something that can be scheduled." (wakeup [_ arg] "") (schedule [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Morphable "Something that can be morphed." (morph [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Typeable "Something that can be identified as a type." (typeid [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Openable "Something that can be opened." (open [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Receivable "Something that can receive a message." (receive [_ msg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Resetable "Something that can be reset." (reset [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Restartable "Something that can be restarted." (restart [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Sendable "Something that can send a message." (send [_ msg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Settable "Something that supports settable key-values." (unsetv [_ key] "") (setv [_ key arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Startable "Something that can be started." (stop [_] "") (start [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Connectable "Something that can be connected." (disconnect [_] "") (connect [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Suspendable "Something that can be suspended." (resume [_] "") (suspend [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Triggerable "Something that can be triggered." (fire [_] [_ arg] "") (set-trigger [_ t] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Nextable "Something that has a next." (next [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Versioned "Something that has a version." (version [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn id?? "Get id of this object" [obj] (cond (satisfies? Idable obj) (czlab.basal.core/id obj) (map? obj) (:id obj) :t nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;EOF
643
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.basal.core "Useful additions to clojure core & string." (:refer-clojure :exclude [send next]) (:require [clojure.set :as ct] [clojure.string :as cs] [io.aviso.ansi :as ansi] [clojure.tools.logging :as l]) (:import [java.util Date] [java.lang System StringBuilder])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;; #^"[Ljava.lang.Object;" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:doc "Log flag(toggle) used internally."} LOG-FLAG (not (.equals "false" (System/getProperty "czlabloggerflag")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private t-bad "FAILED") (def ^:private t-ok "passed") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defmacro- "Same as defmacro but private." {:arglists '([name & more])} [name & more] (list* `defmacro (with-meta name (assoc (meta name) :private true)) more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defonce- "Same as defonce but private." {:arglists '([name & more])} [name & more] (list* `defonce (with-meta name (assoc (meta name) :private true)) more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro def- "Same as def but private." {:arglists '([name & more])} [name & more] (list* `def (with-meta name (assoc (meta name) :private true)) more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-long-var "Define a long array[1] for local operation" ([] `(decl-long-var 0)) ([n] `(long-array 1 ~n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-int-var "Define a int array[1] for local operation" ([] `(decl-int-var 0)) ([n] `(int-array 1 ~n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn int-var "" ([^ints arr v] (aset arr 0 (int v)) (int v)) ([^ints arr] (aget arr 0)) ([^ints arr op nv] (let [v (int (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn long-var "" ([^longs arr ^long v] (aset arr 0 v) v) ([^longs arr] (aget arr 0)) ([^longs arr op nv] (let [v (long (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-var-docstring "Add docstring to var" [v s] `(alter-meta! ~v assoc :doc ~s)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-var-private "Make var private" [v] `(alter-meta! ~v assoc :private true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-object<> "Define a simple type" [name & more] `(defrecord ~name [] ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol JEnumProto "Mimic Java Enum" (lookup-enum-str [_ s] "Get enum from string") (get-enum-str [_ e] "Get string value of enum") (lookup-enum-int [_ n] "Get enum from int")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;Loose equivalent of a Java Enum (decl-object<> JEnum JEnumProto (get-enum-str [me e] (if (contains? me e) (cs/replace (str e) #"^:" ""))) (lookup-enum-str [me s] (let [kee (keyword s)] (some #(if (= kee (first %)) (first %)) me))) (lookup-enum-int [me n] (some #(if (= n (last %)) (first %)) me))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-generic-enum "e.g. (decl-generic-enum weather hot cold)" [name base & more] (assert (and (not-empty more) (integer? base))) `(def ~name (czlab.basal.core/object<> czlab.basal.core.JEnum (-> {} ~@(reduce #(conj %1 `(assoc (keyword (str *ns*) ~(str %2)) ~(+ base (count %1)))) [] more))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;how to make it private ;;(alter-meta! #'weather assoc :private true) (defmacro decl-special-enum "e.g. (decl-special-enum weather hot 3 cold 7)" [name & more] (assert (even? (count more))) (let [ps (partition 2 more)] `(def ~name (czlab.basal.core/object<> czlab.basal.core.JEnum (-> {} ~@(mapv #(do `(assoc (keyword (str *ns*) ~(str (first %))) ~(last %))) ps)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro trace "Logging at TRACE level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :trace ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro debug "Logging at DEBUG level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :debug ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro info "Logging at INFO level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :info ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro warn "Logging at WARN level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :warn ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro error "Logging at ERROR level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :error ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fatal "Logging at FATAL level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :fatal ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn exception "Log an exception at ERROR level." {:arglists '([e])} [e] (when czlab.basal.core/LOG-FLAG (clojure.tools.logging/logf :error e "") (clojure.tools.logging/logf :error "%s" "exception thrown."))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def BOOLS #{"true" "yes" "on" "ok" "active" "1"}) (def ^String HEX-CHAR-STR "0123456789ABCDEF") (def ^String hex-char-str "0123456789abcdef") (def ^{:tag "[C"} HEX-CHARS (.toCharArray HEX-CHAR-STR)) (def ^{:tag "[C"} hex-chars (.toCharArray hex-char-str)) (def ^String USASCII "ISO-8859-1") (def ^String UTF16 "UTF-16") (def ^String UTF8 "UTF-8") (def OneK 1024) (def FourK (* 4 OneK)) (def KiloBytes OneK) (def BUF-SZ (* 4 KiloBytes)) (def MegaBytes (* KiloBytes KiloBytes)) (def GigaBytes (* KiloBytes KiloBytes KiloBytes)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro funcit?? "Maybe run a function with args." {:arglists '([f & args])} [f & args] `(let [f# ~f] (if (fn? f#) (f# ~@args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro pre "Like :pre, assert conditions." {:arglists '([& conds])} [& conds] `(assert (and ~@conds) "precond failed.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro atom? "If obj is an atom?" {:arglists '([x])} [x] `(instance? clojure.lang.Atom ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro n#-even? "Count of collection even?" {:arglists '([coll])} [coll] `(even? (count ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !sas? "Same as not-satisfies?" {:arglists '([proto obj])} [proto obj] `(not (satisfies? ~proto ~obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sas? "Same as satisfies?" {:arglists '([proto obj])} [proto obj] `(satisfies? ~proto ~obj)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !is? "Same as not-instance?" {:arglists '([clazz obj])} [clazz obj] `(not (instance? ~clazz ~obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro is? "Same as instance?" {:arglists '([clazz obj])} [clazz obj] `(instance? ~clazz ~obj)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro map-> "Same as into {}." {:arglists '([& more])} [& more] `(into {} ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vec-> "Same as into []." {:arglists '([& more])} [& more] `(into [] ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro set-> "Same as into #{}." {:arglists '([& more])} [& more] `(into #{} ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cc+1 "Prepend an item to collection(s)." {:arglists '([a & more])} [a & more] `(concat [~a] ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cc+ "Same as concat." {:arglists '([& more])} [& more] `(concat ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _2 "Same as second." {:arglists '([coll])} [coll] `(second ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _1 "Same as first." {:arglists '([coll])} [coll] `(first ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _3 "Get the 3rd item." {:arglists '([coll])} [coll] `(nth ~coll 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _E "Same as last." {:arglists '([coll])} [coll] `(last ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _NE "Get the last item via nth." {:arglists '([coll])} [coll] `(let [x# ~coll] (nth x# (- (count x#) 1)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !zero? "Same as not-zero?" {:arglists '([n])} [n] `(not (zero? ~n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro n# "Same as count." {:arglists '([coll])} [coll] `(count ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro car "Same as first." {:arglists '([coll])} [coll] `(first ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cdr "Same as rest." {:arglists '([coll])} [coll] `(rest ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro one? "If count() is 1?" {:arglists '([coll])} [coll] `(== 1 (count ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro two? "If count() is 2?" {:arglists '([coll])} [coll] `(== 2 (count ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro one+? "If count() is more than 1?" {:arglists '([coll])} [coll] `(> (count ~coll) 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro or?? "(or?? [= a] b c) => (or (= b a) (= c a))." {:arglists '([bindings & args])} [bindings & args] (let [op (gensym) arg (gensym) [p1 p2] bindings] `(let [~op ~p1 ~arg ~p2] (or ~@(map (fn [n] `(~op ~n ~arg)) args))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro dissoc!! "Mutable dissoc (atom)." {:arglists '([a & args])} [a & args] (let [X (gensym)] `(let [~X ~a] (swap! ~X dissoc ~@args) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro assoc!! "Mutable assoc (atom)." {:arglists '([a & args])} [a & args] (let [X (gensym)] `(let [~X ~a] (swap! ~X assoc ~@args) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_* "Wrap code into a fn(...)." {:arglists '([& forms])} [& forms] `(fn [& ~'____xs] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_3 "Wrap code into a fn(a1,a2,a3)." {:arglists '([& forms])} [& forms] `(fn [~'____1 ~'____2 ~'____3] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_2 "Wrap code into a fn(a1,a2)." {:arglists '([& forms])} [& forms] `(fn [~'____1 ~'____2] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_1 "Wrap code into a fn(a1)." {:arglists '([& forms])} [& forms] `(fn [~'____1] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_0 "Wrap code into a fn()." {:arglists '([& forms])} [& forms] `(fn [] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro tset* "A transient set." {:arglists '([] [x])} ([] `(tset* nil)) ([x] `(transient (or ~x #{})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro tvec* "A transient vector." {:arglists '([] [x])} ([] `(tvec* nil)) ([x] `(transient (or ~x [])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro tmap* "A transient map." {:arglists '([] [x])} ([] `(tmap* nil)) ([x] `(transient (or ~x {})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro persist! "Same as persistent!." {:arglists '([coll])} [coll] `(persistent! ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro atomic "Atomize fields as map." {:arglists '([& args])} [& args] `(atom (array-map ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro mapfv "Apply a binary-op to the value over the forms. e.g. (+ 3 1 (+ 2 2)) => [4 7]." {:arglists '([op value & forms])} [op value & forms] `(vector ~@(map (fn [f] `(~op ~f ~value)) forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro last-index "count less 1." {:arglists '([coll])} [coll] `(- (count ~coll) 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro nexth "The nth item after i." {:arglists '([coll i])} [coll i] `(nth ~coll (+ 1 ~i))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro chop "Same as partition." {:arglists '([& args])} [& args] `(partition ~@args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro inc* "One plus, x+1." {:arglists '([x])} [x] `(+ 1 ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro dec* "One less, x-1." {:arglists '([x])} [x] `(- ~x 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do->false "Do returns false." {:arglists '([& forms])} [& forms] `(do ~@forms false)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do->true "Do returns true." {:arglists '([& forms])} [& forms] `(do ~@forms true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do->nil "Do returns nil." {:arglists '([& forms])} [& forms] `(do ~@forms nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro let->false "Let returns false." {:arglists '([& forms])} [& forms] `(let ~@forms false)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro let->true "Let returns true." {:arglists '([& forms])} [& forms] `(let ~@forms true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro let->nil "Let returns nil." {:arglists '([& forms])} [& forms] `(let ~@forms nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defenum "Enum definition. e.g. (defenum ^:private xyz 1 a b c) will generate (def ^:private xyz-a 1) (def ^:private xyz-b 2) (def ^:private xyz-c 3)." {:arglists '([ename start & args])} [ename start & args] (let [mm (meta ename)] (assert (number? start) "Enum expecting a number.") `(do ~@(loop [v start [m & ms] args out []] (if (nil? m) out (let [m' (meta m) z (str (name ename) "-" (name m))] (recur (+ 1 v) ms (conj out `(def ~(with-meta (symbol z) (merge m' mm)) ~v))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro condp?? "condp without throwing exception." {:arglists '([pred expr & clauses])} [pred expr & clauses] (let [c (count clauses) z (count (filter #(and (keyword? %) (= :>> %)) clauses)) d (- c z) xs (if-not (even? d) clauses (concat clauses ['nil]))] `(condp ~pred ~expr ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro case?? "case without throwing exception." {:arglists '([expr & clauses])} [expr & clauses] (let [c (count clauses) xs (if-not (even? c) clauses (concat clauses ['nil]))] `(case ~expr ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-xxx?? {:arglists '([F bindings then] [F bindings then else])} ([F bindings then] `(if-xxx?? ~F ~bindings ~then nil)) ([F bindings then else & oldform] (let [_ (assert (== 2 (count bindings)) "Too many (> 2) in bindings.") X (gensym) f1 (first bindings)] (assert (symbol? f1)) `(let [~X ~(last bindings) ~f1 ~X] (if (~F ~X) ~then ~else))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-inst "If expr is instance of class, execute `then`, otherwise `else`." {:arglists '([clazz expr then] [clazz expr then else])} ([clazz expr then] `(if-inst ~clazz ~expr ~then nil)) ([clazz expr then else & oldform] `(if (instance? ~clazz ~expr) ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-inst "If expr is instance of class, execute `body`." {:arglists '([clazz expr & body])} [clazz expr & body] `(if (instance? ~clazz ~expr) (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-proto "If expr satisfies the protocol, execute `then`, otherwise `else`." {:arglists '([proto expr then] [proto expr then else])} ([proto expr then] `(if-proto ~proto ~expr ~then nil)) ([proto expr then else & oldform] `(if (satisfies? ~proto ~expr) ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-proto "If expr satisfies the protocol, execute `body`." {:arglists '([proto expr & body])} [proto expr & body] `(if (satisfies? ~proto ~expr) (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-nil "If expr evals to nil, execute `then`, otherwise `else`." {:arglists '([expr then] [expr then else])} ([expr then] `(if-nil ~expr ~then nil)) ([expr then else & oldform] `(if (nil? ~expr) ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-nil "If expr evals to nil, execute `body`." {:arglists '([expr & body])} [expr & body] `(if (nil? ~expr) (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn is-throwable? "If object is a Throwable?" {:arglists '([x])} [x] (instance? Throwable x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-throw "bindings => binding-form test If test is a Throwable, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-throw ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? czlab.basal.core/is-throwable? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-throw "bindings => binding-form test If test is a Throwable, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-throw ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-var "bindings => binding-form test If test is a var, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-var ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? var? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-var "bindings => binding-form test If test is a var, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-var ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-number "bindings => binding-form test If test is a number, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-number ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? number? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-number "bindings => binding-form test If test is a number, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-number ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-string "bindings => binding-form test If test is a string, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-string ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? string? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-string "bindings => binding-form test If test is a string, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-string ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro nloop "Loop over code n times." {:arglists '([n & forms])} [n & forms] (let [x (gensym)] `(dotimes [~x ~n] ~@forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro each* "Evals function for each element, indexed." {:arglists '([func coll])} [func coll] (let [C (gensym) I (gensym) T (gensym)] `(let [~C ~coll ~T (count ~C)] (dotimes [~I ~T] (~func (nth ~C ~I) ~I))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro each "Evals function for each element." {:arglists '([func coll])} [func coll] (let [I (gensym)] `(doseq [~I ~coll] (~func ~I)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro mget "Java map.get()." {:arglists '([m k])} [m k] `(.get ~(with-meta m {:tag 'java.util.Map}) ~k)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mdel! "Java map.remove()." {:arglists '([m k])} [m k] (.remove ^java.util.Map m k)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro mput! "Java map.put()." {:arglists '([m k v])} [m k v] `(.put ~(with-meta m {:tag 'java.util.Map}) ~k ~v)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;testing stuff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro deftest "A bunch of test-cases grouped together." {:arglists '([name & body])} [name & body] `(def ~name (fn [] (filter #(not (nil? %)) [~@body])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ensure?? "Assert test was ok." {:arglists '([msg form])} [msg form] `(czlab.basal.core/ensure-test ~form ~msg)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ensure-thrown?? "Assert an error was thrown." {:arglists '([msg expected form])} [msg expected form] `(try ~form (czlab.basal.core/ensure-thrown ~msg) (catch Throwable e# (czlab.basal.core/ensure-thrown ~expected e# ~msg)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro prn!! "Println with format." {:arglists '([fmt & args])} [fmt & args] `(println (format ~fmt ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro prn! "Print with format." {:arglists '([fmt & args])} [fmt & args] `(print (format ~fmt ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (defmacro- make-fn "Hack to wrap a macro as fn so one can use *apply* on it." [m] `(fn [& xs#] (eval (cons '~m xs#))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro object<> "Create a new record instance. e.g. (object<> ClazzA) (object<> ClazzA {:a 1}) (object<> ClazzA :a 1 :b 2)" {:arglists '([z] [z m] [z ab & more])} ([z] `(new ~z)) ([z m] `(merge (new ~z) ~m)) ([z a b & more] `(assoc (new ~z) ~a ~b ~@more))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro atomic<> "Create a new record instance, with all attributes inside an atom. e.g. (atomic<> ClazzA) (atomic<> ClazzA {:a 1}) (atomic<> ClazzA :a 1 :b 2)" {:arglists '([z] [z m] [z ab & more])} ([z] `(assoc (new ~z) :o (atom {}))) ([z m] `(assoc (new ~z) :o (atom (merge {} ~m)))) ([z a b & more] `(assoc (new ~z) :o (atom (assoc {} ~a ~b ~@more))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vargs "Coerce into java array of type z." {:arglists '([z arglist])} [z arglist] `(into-array ~z ~arglist)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro preduce<map> "Reduce with a transient map accumulator, returning a map." {:arglists '([f coll])} [f coll] `(persistent! (reduce ~f (transient {}) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro preduce<set> "Reduce with a transient set accumulator, returning a set." {:arglists '([f coll])} [f coll] `(persistent! (reduce ~f (transient #{}) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro preduce<vec> "Reduce with a transient vec accumulator, returning a vec." {:arglists '([f coll])} [f coll] `(persistent! (reduce ~f (transient []) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rset! "Reset a atom." {:arglists '([a] [a value])} ([a] `(rset! ~a nil)) ([a value] `(reset! ~a ~value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro exp! "Create an exception of type E." {:arglists '([E & args])} [E & args] `(new ~E ~@args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro trap! "Throw exception of type E." {:arglists '([E & args])} [E & args] `(throw (exp! ~E ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro raise! "Throw java Exception with message." {:arglists '([fmt & args])} [fmt & args] `(throw (new java.lang.Exception (str (format ~fmt ~@args))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-assert-exp "Generate a function which when called, will assert the condition and if false, throw the desired exception." {:arglists '([name E])} [name E] `(defn ~name [~'kond ~'arg & ~'xs] (if-not ~'kond (cond (string? ~'arg) (czlab.basal.core/trap! ~E (str (apply format ~'arg ~'xs))) (instance? Throwable ~'arg) (czlab.basal.core/trap! ~E ~(with-meta 'arg {:tag 'Throwable})))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-throw-exp "Generate a function which when called, will throw the desired exception." {:arglists '([name E])} [name E] `(defn ~name [~'arg & ~'xs] (cond (string? ~'arg) (czlab.basal.core/trap! ~E (str (apply format ~'arg ~'xs))) (instance? Throwable ~'arg) (czlab.basal.core/trap! ~E ~(with-meta 'arg {:tag 'Throwable}))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro assert-on! "Like assert, but throws a specific exception." {:arglists '([kond E & args])} [kond E & args] `(if-not ~kond (trap! ~E ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do-with "bindings => [symbol init-expr] Evals the body in a context in which the symbol is always the returned value." {:arglists '([bindings & forms])} [bindings & forms] (let [f (first bindings) sz (count bindings)] (assert (or (== sz 1) (== sz 2)) "(not 1 or 2) in bindings.") (assert (symbol? f)) (if (== sz 1) `(let [~f ~f] ~@forms ~f) `(let [~f ~(last bindings)] ~@forms ~f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do-with-str "bindings => [symbol init-expr] Eval the body in a context in which the symbol is always the returned value to-string'ed. e.g. (do-with-str [a (f)] ... (str a))." {:arglists '([bindings & forms])} [bindings & forms] `(str (czlab.basal.core/do-with ~bindings ~@forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do-with-atom "bindings => [symbol init-expr] Eval the body in a context in which the symbol is always the returned value deref'ed. e.g. (do-with-atom [a (atom 0)] ... (deref a))." {:arglists '([bindings & forms])} [bindings & forms] `(deref (czlab.basal.core/do-with ~bindings ~@forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro bool! "Same as boolean." {:arglists '([x])} [x] `(boolean ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro trye! "Eat exception and return a value." {:arglists '([value & forms])} [value & forms] `(try ~@forms (catch Throwable ~'_ ~value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro try! "Eat exception and return nil." {:arglists '([& forms])} [& forms] `(czlab.basal.core/trye! nil ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-some+ "bindings => [binding-form test]. When test is not empty, evaluates body with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-some+ ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? empty? ~bindings ~else ~then))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-some+ "bindings => [binding-form test]. When test is not empty, evaluates body with binding-form bound to the value of test." {:arglists '([bindings & body])} [bindings & body] `(czlab.basal.core/if-some+ ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-fn "bindings => [binding-form test]. When test is a fn?, evaluates body with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-fn ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? fn? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-fn "bindings => [binding-form test]. When test is a fn?, evaluates body with binding-form bound to the value of test." {:arglists '([bindings & body])} [bindings & body] `(czlab.basal.core/if-fn ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro doto->> "Combine doto and ->>." {:arglists '([x & forms])} [x & forms] (let [X (gensym)] `(let [~X ~x] ~@(map (fn [f] (if (seq? f) `(~@f ~X) `(~f ~X))) forms) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro doto-> "Combine doto and ->." {:arglists '([x & forms])} [x & forms] (let [X (gensym)] `(let [~X ~x] ~@(map (fn [f] (if (seq? f) (let [z (first f) r (rest f)] `(~z ~X ~@r)) `(~f ~X))) forms) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro eq? "Use java's .equals method." {:arglists '([a b])} [a b] `(.equals ~a ~b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !eq? "Use java's .equals method." {:arglists '([a b])} [a b] `(not (.equals ~a ~b))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !=? "Same as not-identical?" {:arglists '([& more])} [& more] `(not (identical? ~@more))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro =? "Same as identical?" {:arglists '([& more])} [& more] `(identical? ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !in? "Same as not-contains?" {:arglists '([& more])} [& more] `(not (contains? ~@more))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro in? "Same as contains?" {:arglists '([& more])} [& more] `(contains? ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;had to use this trick to prevent reflection warning (defmacro cast? "Cast object of this type else nil." {:arglists '([someType obj])} [someType obj] (let [X (gensym)] `(let [~X ~obj] (if (instance? ~someType ~X) ^{:tag ~someType} (identity (.cast ~someType ~X)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cexp? "Try casting to Throwable." {:arglists '([e])} [e] `(cast? Throwable ~e)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !nil? "Same as not-nil." {:arglists '([x])} [x] `(not (nil? ~x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rnil "Skip nil(s) in collection." {:arglists '([coll])} [coll] `(remove nil? ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rnilv "Same as rnil but returns a vec." {:arglists '([coll])} [coll] `(into [] (remove nil? ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro szero? "Safe zero?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E)(zero? ~E))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sneg? "Safe neg?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E)(neg? ~E))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro spos? "Safe pos?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E)(pos? ~E))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro snneg? "Safe not neg?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E) (or (zero? ~E)(pos? ~E)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !false? "Same as not-false." {:arglists '([x])} [x] `(not (false? ~x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !true? "Same as not true." {:arglists '([x])} [x] `(not (true? ~x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro assert-not "Assert a false condition." {:arglists '([cond])} [cond] `(assert (not ~cond))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro marray "n-size java array of type Z." {:arglists '([Z n])} [Z n] `(make-array ~Z ~n)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro zarray "0-size java array of type Z." {:arglists '([Z])} [Z] `(make-array ~Z 0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vtbl** "Make a virtual table: op1 f1 op2 f2, with parent vtbl." {:arglists '([parent & args])} [parent & args] (do (assert (even? (count args))) `(czlab.basal.core/object<> ~'czlab.basal.core.VTable :____proto ~parent ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vtbl* "Make a virtual table: op1 f1 op2 f2." {:arglists '([& args])} [& args] `(vtbl** nil ~@args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro wo* "Same as with-open." {:arglists '([bindings & forms])} [bindings & forms] `(with-open ~bindings ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro wm* "Same as with-meta." {:arglists '([obj m])} [obj m] `(with-meta ~obj ~m)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ->str "Same as java's .toString." {:arglists '([obj])} [obj] `(some-> ~obj .toString)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;monads ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro run-bind ;"Run the bind operator. *Internal*" {:arglists '([binder steps expr])} [binder steps expr] (let [more (drop 2 steps) [a1 mv] (take 2 steps)] `(~binder ~mv (fn [~a1] ~(if (not-empty more) `(run-bind ~binder ~more ~expr) `(do ~expr)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defmonad "Define a named monad by defining the monad operations. The definitions are written like bindings to the monad operations bind and unit (required) and zero and plus (optional)." {:arglists '([name ops] [name docs ops])} ([name ops] `(defmonad ~name "" ~ops)) ([name docs ops] (let [_ (assert (not-empty ops) "no monad ops!")] `(def ~(with-meta name {:doc docs}) (merge {:bind nil :unit nil :zero nil :plus nil} (into {} (map #(vec %) (partition 2 ~ops)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro domonad "Monad comprehension. Takes the name of a monad, a vector of steps given as binding-form, and a result value specified by body." {:arglists '([monad steps] [monad steps body])} ([monad steps] `(domonad ~monad ~steps nil)) ([monad steps body] (let [E (gensym) B (gensym) U (gensym) Z (gensym)] `(let [{~B :bind ~U :unit ~Z :zero} ~monad ;if no body try to run the zero func, ;else run the unit on it. ~E #(if (and (nil? %) (some? ~Z)) ~Z (~U %))] (czlab.basal.core/run-bind ~B ~steps (~E ~body)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;end-macros ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;monads ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-identity "Monad describing plain computations. This monad does nothing at all. It is useful for testing, for combination with monad transformers, and for code that is parameterized with a monad." [:bind (fn [mv mf] (mf mv)) :unit identity]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-maybe "Monad describing computations with possible failures. Failure is represented by nil, any other value is considered valid. As soon as a step returns nil, the whole computation will yield nil as well." [:unit identity :bind (fn [mv mf] (if-not (nil? mv) (mf mv)))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-list "Monad describing multi-valued computations, i.e. computations that can yield multiple values. Any object implementing the seq protocol can be used as a monadic value." [:bind (fn [mv mf] (flatten (map mf mv))) :unit (fn_1 (vector ____1)) :zero [] :plus (fn_* (flatten ____xs))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-state "Monad describing stateful computations. The monadic values have the structure (fn [old-state] [result new-state])." [:unit (fn [v] (fn [s] [v s])) :bind (fn [mv mf] (fn [s] (let [[v s'] (mv s)] ((mf v) s'))))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-continuation "Monad describing computations in continuation-passing style. The monadic values are functions that are called with a single argument representing the continuation of the computation, to which they pass their result." [:unit (fn [v] (fn [cont] (cont v))) :bind (fn [mv mf] (fn [cont] (mv (fn [v] ((mf v) cont)))))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn run-cont "Execute the computation in the cont monad and return its result." {:arglists '([cont])} [cont] (cont identity)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; end-monad ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn kvs->map "Turn a list of key values into map." {:arglists '([arglist])} [arglist] {:pre [(even? (count arglist))]} (apply array-map arglist)) ;(into {} (map #(vec %) (partition 2 arglist))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn repeat-str "Repeat string n times." {:tag String :arglists '([n s])} [n s] (cs/join "" (repeat n s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn num?? "If n is not a number, return other." {:arglists '([n other])} [n other] {:pre [(number? other)]} (if (number? n) n other)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn !== "Same as (not (== num1 num2))." {:arglists '([x] [x y] [x y & more])} ([x] false) ([x y] (not (== x y))) ([x y & more] (not (apply == x y more)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn flip "Invert number if not zero." {:arglists '([x])} [x] {:pre [(number? x)]} (if (zero? x) 0 (/ 1 x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn percent "Calculate the percentage." {:arglists '([numerator denominator])} [numerator denominator] (* 100.0 (/ numerator denominator))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn split-seq "Split a collection into 2 parts." {:arglists '([coll cnt])} [coll cnt] (if-not (< cnt (count coll)) (list (concat [] coll) ()) (list (take cnt coll) (drop cnt coll)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn compare-asc* "Returns a ascending compare function." {:arglists '([] [f])} ([] (compare-asc* identity)) ([f] (fn_2 (cond (< (f ____1) (f ____2)) -1 (> (f ____1) (f ____2)) 1 :else 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn compare-des* "Returns a descending compare function." {:arglists '([] [f])} ([] (compare-des* identity)) ([f] (fn_2 (cond (< (f ____1) (f ____2)) 1 (> (f ____1) (f ____2)) -1 :else 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- xxx-by "Used by min-by & max-by. *Internal*" {:arglists '([cb coll])} [cb coll] (if (not-empty coll) (reduce cb (_1 coll) (rest coll)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn min-by "Find item with minimum value as defined by the function." {:arglists '([f coll])} [f coll] (xxx-by #(if (< (f %1) (f %2)) %1 %2) coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn max-by "Find item with maximum value as defined by the function." {:arglists '([f coll])} [f coll] (xxx-by #(if (< (f %1) (f %2)) %2 %1) coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ensure-test "Assert a test condition, returning a message." {:arglists '([cond msg])} [cond msg] (str (try (if cond t-ok t-bad) (catch Throwable _ t-bad)) ": " msg)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ensure-thrown "Assert an exception is thrown during test." {:arglists '([msg] [expected error msg])} ([msg] (ensure-thrown nil nil msg)) ([expected error msg] (str (if (nil? error) t-bad (if (or (= expected :any) (is? expected error)) t-ok t-bad)) ": " msg))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rip-fn-name "Extract (mangled) name of the function." {:tag String :arglists '([func])} [func] (let [s (str func) h (cs/index-of s "$") s (if h (subs s (+ 1 h)) s) p (cs/last-index-of s "@")] (if p (subs s 0 p) s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-int "Operate like a mutable int, get and set." {:arglists '([] [arr] [arr v] [arr op nv])} ;setter ([^ints arr v] (aset arr 0 (int v)) (int v)) ;ctor ([] (int-array 1 0)) ;getter ([^ints arr] (int (aget arr 0))) ;apply (op old-val new-value) ([^ints arr op nv] (let [v (int (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-int* "Create & init mu-i." {:arglists '([i])} [i] {:pre [(number? i)]} (doto (mu-int) (mu-int i))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-long "Operate like a mutable long, get and set." {:arglists '([] [arr] [arr v] [arr op nv])} ;setter ([^longs arr v] (aset arr 0 (long v)) (long v)) ;ctor ([] (long-array 1 0)) ;getter ([^longs arr] (long (aget arr 0))) ;apply (op old-val new-val) ([^longs arr op nv] (let [v (long (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-long* "Create & init a mu-long." {:arglists '([n])} [n] {:pre [(number? n)]} (doto (mu-long) (mu-long n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nth?? "Get the nth element, 1-indexed." {:arglists '([coll pos])} [coll pos] {:pre [(> pos 0)]} (first (drop (- pos 1) coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn vargs* "Coerce into java array." {:arglists '([clazz & args])} [clazz & args] (vargs clazz args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (defn- interject "Run the function on the current field value, replacing the key with the returned value. function(pojo oldvalue) -> newvalue." [pojo field func] {:pre [(map? pojo) (fn? func)]} (assoc pojo field (func pojo field)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn scoped-keyword "Scope name as a fully-qualified keyword." {:arglists '([t])} [t] {:pre [(string? t) (nil? (cs/index-of t "/")) (nil? (cs/index-of t ":"))]} (keyword (str *ns*) t)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn is-scoped-keyword? "If a scoped keyword?" {:arglists '([kw])} [kw] (and (keyword? kw) (cs/includes? (str kw) "/"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rand-sign "Randomly choose a sign." {:arglists '([])} [] (if (even? (rand-int Integer/MAX_VALUE)) 1 -1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rand-bool "Randomly choose a boolean value." {:arglists '([])} [] (even? (rand-int Integer/MAX_VALUE))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn num-sign "Find the sign of a number." {:arglists '([n])} [n] {:pre [(number? n)]} (cond (> n 0) 1 (< n 0) -1 :else 0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->long "String as a long value." {:tag Long :arglists '([s] [s dv])} ([s] (s->long s nil)) ([s dv] (try (Long/parseLong ^String s) (catch Throwable _ (if (number? dv) (long dv) (throw _)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->int "String as an int value." {:tag Integer :arglists '([s] [s dv])} ([s] (s->int s nil)) ([s dv] (try (Integer/parseInt ^String s) (catch Throwable _ (if (number? dv) (int dv) (throw _)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->double "String as a double value." {:tag Double :arglists '([s][s dv])} ([s] (s->double s nil)) ([s dv] (try (Double/parseDouble ^String s) (catch Throwable _ (if (number? dv) (double dv) (throw _)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->bool "String as a boolean value." {:arglists '([s])} [s] (contains? BOOLS (cs/lower-case (str s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; test and assert funcs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-isa "Is child of parent?" {:arglists '([reason parent child])} [reason parent child] (do->true (-> (cond (and (class? parent) (class? child)) (isa? child parent) (or (nil? parent) (nil? child)) false (not (class? parent)) (test-isa reason (class parent) child) (not (class? child)) (test-isa reason parent (class child))) (assert (str reason child " not-isa " parent))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-some "Object is not null?" {:arglists '([reason obj])} [reason obj] (do->true (assert (some? obj) (str reason " is null.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-cond "A true condition?" {:arglists '([reason cond])} [reason cond] (do->true (assert cond (str reason)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-hgl "String is not empty?" {:arglists '([reason s])} [reason s] (do->true (assert (and (string? s) (not-empty s)) (str reason " is empty.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- test-xxx [a b] (condp instance? b Double :double Long :long Float :double Integer :long (raise! "Allow numbers only!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti test-pos0 "Check number is not negative?" test-xxx) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti test-pos "Check number is positive?" test-xxx) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos0 :double [reason v] (do->true (assert (snneg? v) (str reason " must be >= 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos0 :long [reason v] (do->true (assert (snneg? v) (str reason " must be >= 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos :double [reason v] (do->true (assert (spos? v) (str reason " must be > 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos :long [reason v] (do->true (assert (spos? v) (str reason " must be > 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-seq+ "Check sequence is not empty?" {:arglists '([reason v])} [reason v] (do->true (assert (pos? (count v)) (str reason " must be non empty.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sort-join "Sort and concatenate strings." {:tag String :arglists '([ss] [sep ss])} ([ss] (sort-join "" ss)) ([sep ss] (if (nil? ss) "" (cs/join sep (sort ss))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn strip-ns-path "Remove the leading colon." {:tag String :arglists '([path])} [path] (cs/replace (str path) #"^:" "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol VTableAPI "Act like a virtual table." (vt-set-proto [_ par] "Hook up parent prototype object.") (vt-has? [_ kee] "True if key exists in the hierarchy.") (vt-run?? [_ kee arglist] [_ kee arglist skip?] "Find key. If function run it else return value.") (vt-find?? [_ kee] [_ kee skip?] "Find this key, if skip? then search from parent.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord VTable [] VTableAPI (vt-set-proto [me par] (assoc me :____proto par)) (vt-find?? [me kee] (vt-find?? me kee false)) (vt-find?? [me kee skip?] (let [p (:____proto me)] (cond skip? (if p (vt-find?? p kee)) (in? me kee) (get me kee) :else (if p (vt-find?? p kee))))) (vt-has? [me kee] (or (in? me kee) (if-some [p (:____proto me)] (vt-has? p kee)))) (vt-run?? [me kee arglist] (vt-run?? me kee arglist false)) (vt-run?? [me kee arglist skip?] (let [f (vt-find?? me kee skip?)] (if (fn? f) (apply f me arglist) f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn identity-n "Like identity but returns positional param. e.g. (def get-2nd (identity-n 2)) (get-2nd a b c) => b." {:arglists '([n] [n index-zero?])} ([n] (identity-n n false)) ([n index-zero?] {:pre [(number? n)]} (fn_* (let [z (count ____xs) p (if index-zero? n (- n 1))] (assert (and (< p z) (>= p 0)) "Index out of bound.") (nth ____xs p))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- merge-2 [a b] (if (nil? a) b (if (nil? b) a (loop [[z & M] (seq b) tmp (tmap* a)] (let [[k vb] z va (get a k)] (if (nil? z) (persist! tmp) (recur M (assoc! tmp k (cond (not (in? a k)) vb (and (map? vb) (map? va)) (merge-2 va vb) (and (set? vb) (set? va)) (ct/union va vb) :else vb))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn merge+ "Merge (deep) of clojure data." {:arglists '([& more])} [& more] (cond (empty? more) nil (one? more) (_1 more) :else (loop [prev nil [a & xs] more] (if (empty? xs) (merge-2 prev a) (recur (merge-2 prev a) xs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;string stuff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sreduce<> "Reduce with a string-builder." {:arglists '([f coll])} [f coll] `(str (reduce ~f (StringBuilder.) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fmt "Same as string format." {:tag String :arglists '([f & args])} [f & args] (apply format f args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn char-array?? "Splits a string into string-char, e.g. \"abc\" = [\"a\" \"b\" \"c\"]." {:arglists '([s])} [s] {:pre [(or (nil? s) (string? s))]} (remove empty? (cs/split s #""))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbf+ "StringBuilder concat." {:tag StringBuilder :arglists '([buf & args])} [buf & args] (doseq [x args] (.append ^StringBuilder buf x)) buf) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbf<> "Same as StringBuilder.new" {:tag StringBuilder :arglists '([] [& args])} ([] (sbf<> "")) ([& args] (let [s (StringBuilder.)] (apply sbf+ s args) s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbf-join "Append to a string-builder, optionally inserting a delimiter if the buffer is not empty." {:tag StringBuilder :arglists '([buf sep item])} [buf sep item] (do-with [^StringBuilder buf] (when item (if (and (!nil? sep) (pos? (.length buf))) (.append buf sep)) (.append buf item)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbfz "Length of the string-buffer." {:arglists '([b])} [b] (.length ^StringBuilder b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nichts? "Is string empty?" {:arglists '([s])} [s] (or (nil? s) (not (string? s)) (.isEmpty ^String s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hgl? "If string has length?" {:arglists '([s])} [s] (and (string? s) (not (.isEmpty ^String s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn stror "If not s then s2" {:tag String :arglists '([s s2])} [s s2] (if (nichts? s) s2 s)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (defn stror* "If not s then s2...etc" ^String [& args] (loop [[a & more] args] (if (or (hgl? a) (empty? more)) a (recur more))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro stror* "If not s then s2...etc" {:arglists '([& args])} [& args] (let [[a & xs] args] (if (empty? xs) `(stror nil ~a) `(stror ~a (stror* ~@xs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn lcase "Lowercase string safely." {:tag String :arglists '([s])} [s] (str (some-> s clojure.string/lower-case))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ucase "Uppercase string safely." {:tag String :arglists '([s])} [s] (str (some-> s clojure.string/upper-case))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;#^"[Ljava.lang.Class;" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn triml "Get rid of unwanted chars from left." {:tag String :arglists '([src unwantedChars])} [^String src ^String unwantedChars] (if-not (and (hgl? src) (hgl? unwantedChars)) src (loop [len (.length src) pos 0] (if-not (and (< pos len) (cs/index-of unwantedChars (.charAt src pos))) (subs src pos) (recur len (+ 1 pos)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn trimr "Get rid of unwanted chars from right." {:tag String :arglists '([src unwantedChars])} [^String src ^String unwantedChars] (if-not (and (hgl? src) (hgl? unwantedChars)) src (loop [pos (.length src)] (if-not (and (pos? pos) (cs/index-of unwantedChars (.charAt src (- pos 1)))) (subs src 0 pos) (recur (- pos 1)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn includes? "If the char is inside the big str?" {:arglists '([bigs arg])} [^String bigs arg] (let [rc (cond (or (nil? arg) (nil? bigs)) false (integer? arg) (int arg) (string? arg) (number? (cs/index-of bigs arg)) (is? Character arg) (int (.charValue ^Character arg)))] (if-not (number? rc) rc (>= (.indexOf bigs (int rc)) 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro embeds? "If sub-str is inside the big str?" {:arglists '([bigs s])} [bigs s] `(czlab.basal.core/includes? ~bigs ~s)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro has-no-case? "If sub-str is inside the big str - ignore case?" {:arglists '([bigs s])} [bigs s] `(czlab.basal.core/includes? (czlab.basal.core/lcase ~bigs) (czlab.basal.core/lcase ~s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn index-any "If any one char is inside the big str, return the position." {:arglists '([bigs chStr])} [^String bigs ^String chStr] (if-not (and (hgl? bigs) (hgl? chStr)) -1 (let [rc (some #(cs/index-of bigs %) (.toCharArray chStr))] (if (nil? rc) -1 (int rc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn count-str "Count the times the sub-str appears in the big str." {:arglists '([bigs s])} [^String bigs ^String s] (if-not (and (hgl? s) (hgl? bigs)) 0 (loop [len (.length s) total 0 start 0] (let [pos (cs/index-of bigs s start)] (if (nil? pos) total (recur len (+ 1 total) (long (+ pos len)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn count-char "Count the times this char appears in the big str." {:arglists '([bigs ch])} [bigs ch] (reduce #(if (= ch %2) (+ 1 %1) %1) 0 (.toCharArray ^String bigs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sname "Safely get the name of this object." {:arglists '([n])} [n] `(str (some-> ~n name))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nsb "Empty string if obj is null, or obj.toString." {:tag String :arglists '([obj])} [obj] (if (keyword? obj) (name obj) (str obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn kw->str "Stringify a keyword - no leading colon." {:tag String :arglists '([k])} [k] (cs/replace (str k) #"^:" "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->kw "Concatenate all args and return it as a keyword." {:arglists '([& args])} [& args] (if-not (empty? args) (keyword (apply str args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nsn "(null) if obj is null, or obj.toString." {:tag String :arglists '([obj])} [obj] (if (nil? obj) "(null)" (str obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn match-char? "If this char is inside this set of chars?" {:arglists '([ch setOfChars])} [ch setOfChars] (and (set? setOfChars) (contains? setOfChars ch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro strim "Safely trim this string." {:arglists '([s])} [s] `(str (some-> ~s clojure.string/trim))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn strim-any "Strip source string of these unwanted chars." {:tag String :arglists '([src unwantedChars] [src unwantedChars whitespace?])} ([src unwantedChars] (strim-any src unwantedChars false)) ([^String src ^String unwantedChars whitespace?] (let [s (-> (if whitespace? (strim src) src) (triml unwantedChars) (trimr unwantedChars))] (if whitespace? (strim s) s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn splunk "Split a large string into chunks, each chunk having a specific length." {:arglists '([largeString chunkLength])} [^String largeString chunkLength] (if-not (and (hgl? largeString) (snneg? chunkLength)) [] (mapv #(cs/join "" %1) (partition-all chunkLength largeString)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hasic-any? "If bigs contains any one of these strs - ignore case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (empty? substrs) (nichts? bigs)) (let [lc (lcase bigs)] (true? (some #(number? (cs/index-of lc (lcase %))) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn has-any? "If bigs contains any one of these strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (true? (some #(number? (cs/index-of bigs %)) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hasic-all? "If bigs contains all of these strs - ignore case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (empty? substrs) (nichts? bigs)) (let [lc (lcase bigs)] (every? #(number? (cs/index-of lc (lcase %))) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn has-all? "If bigs contains all of these strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (every? #(number? (cs/index-of bigs %)) substrs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ewic-any? "If bigs endsWith any one of the strs, no-case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (let [lc (lcase bigs)] (true? (some #(cs/ends-with? lc (lcase %)) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ew-any? "If bigs endsWith any one of the strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (true? (some #(cs/ends-with? bigs %) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn swic-any? "If bigs startWith any one of the strs - no case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (let [lc (lcase bigs)] (true? (some #(cs/starts-with? lc (lcase %)) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sw-any? "If bigs startWith any one of the strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (true? (some #(cs/starts-with? bigs %) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro eqic? "Same as String.equalIgnoreCase()?" {:arglists '([src other])} [src other] (let [^String ss src ^String oo other] `(.equalsIgnoreCase ~ss ~oo))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn eqic-any? "String.equalIgnoreCase() on any one of the strs?" {:arglists '([src substrs])} [^String src substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? src) (empty? substrs)) (let [lc (lcase src)] (true? (some #(= lc (lcase %)) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn eq-any? "If String.equals() on any one of the strs?" {:arglists '([src substrs])} [^String src substrs] {:pre [(sequential? substrs)]} (if-not (empty? substrs) (true? (some #(.equals src %) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn wrapped? "If src string starts with head and ends with tail?" {:arglists '([src head tail])} [^String src ^String head ^String tail] (if (and (hgl? src) (hgl? head) (hgl? tail)) (and (cs/starts-with? src head) (cs/ends-with? src tail)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rights "Get the rightmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (if (or (<= len 0) (nichts? src)) "" (if (< (.length src) len) src (subs src (- (.length src) len))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn lefts "Get the leftmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (if (or (<= len 0) (nichts? src)) "" (if (< (.length src) len) src (subs src 0 len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn drop-head "Drop leftmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (cond (nichts? src) "" (<= len 0) src :else (if (< (.length src) len) "" (subs src len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn drop-tail "Drop rightmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (cond (nichts? src) "" (<= len 0) src :else (let [n (.length src)] (if (< n len) "" (subs src 0 (- n len)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn matches? "Same as String.matches." {:arglists '([src regex])} [src regex] {:pre [(string? regex)]} (if (hgl? src) (.matches ^String src ^String regex))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn split "Same as String.split." {:arglists '([src regex] [src regex limit])} ([src regex] (split src regex nil)) ([src regex limit] {:pre [(string? regex)]} (if (hgl? src) (remove empty? (if-not (number? limit) (.split ^String src ^String regex) (.split ^String src ^String regex (int limit))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn split-str "Same as String-tokenizer." {:arglists '([s sep] [s sep incSep?])} ([s sep] (split-str s sep false)) ([s sep incSep?] (let [t (new java.util.StringTokenizer ^String s ^String sep (boolean incSep?))] (loop [rc (tvec*)] (if-not (.hasMoreTokens t) (persist! rc) (recur (conj! rc (.nextToken t)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn esc-xml "Escape XML special chars." {:tag String :arglists '([s])} [s] (cs/escape s {\& "&amp;" \> "&gt;" \< "&lt;" \" "&quot;" \' "&apos;"})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- run-test [test] (let [res (test)] [res (every? #(cs/starts-with? % "p") res)])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pretty-millis "Pretty print milliseconds value." {:tag String :arglists '([millis])} [millis] {:pre [(number? millis)]} (let [secs (int (/ millis 1000.0)) millis (int (- millis (* secs 1000.0))) mins (int (/ secs 60.0)) secs (int (- secs (* mins 60.0))) hours (int (/ mins 60.0)) mins (int (- mins (* hours 60.0)))] (cond (pos? hours) (fmt "%d hours %2d minutes %2d.%03d secs" hours mins secs millis) (pos? mins) (fmt "%2d minutes %2d.%03d secs" mins secs millis) (pos? secs) (fmt "%2d.%03d seconds" secs millis) :else (fmt "0.%03d seconds" millis)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- prn-test [results title diff] (let [lsep (repeat-str 78 "+") esep (repeat-str 78 "=") sum (count results) f (filter #(cs/starts-with? % "F") results) p (filter #(cs/starts-with? % "p") results) ok (count p) perc (percent ok sum)] (-> lsep ansi/bold-white prn!!) (-> "test-case: " ansi/bold-white prn!) (-> (stror title (rip-fn-name test)) cs/upper-case ansi/bold-yellow prn!!) (-> (str (Date.)) ansi/bold-white prn!!) (-> lsep ansi/bold-white prn!!) (doseq [r p] (-> r ansi/bold-green prn!!)) (doseq [r f] (-> r ansi/bold-red prn!!)) (-> esep ansi/bold-white prn!!) (-> (str "Passed: " ok "/" sum " [" (int perc) "%%]") ansi/bold-white prn!!) (-> (str "Failed: " (- sum ok)) ansi/bold-white prn!!) (-> (str "cpu-time: " (pretty-millis diff)) ansi/bold-white prn!!) (-> "" ansi/white prn!!))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn clj-test?? "Run test as a clojure test case." {:arglists '([test] [test title print?])} ([test] (clj-test?? test nil true)) ([test title print?] {:pre [(fn? test)]} (let [mark (System/currentTimeMillis) [res ok?] (run-test test) diff (- (System/currentTimeMillis) mark)] (if print? (prn-test res title diff)) ok?))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;protocols ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol AtomicGS "" (getf [_ n] "Get field") (setf [_ n v] "Set field")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Activable "Something that can be activated." (deactivate [_] "") (activate [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Cancelable "Something that can be canceled." (cancel [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Testable "Something that can be tested for validity." (is-valid? [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Catchable "Something that can catch an Exception." (catche [_ e] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Configurable "Something that can be configured with key-values." (get-conf [_] [_ k] "") (set-conf [_ arg] [_ k v] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Debuggable "Something that can be debugged." (dbg-str [_] "") (dbg-show [_ ^PrintStream out] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Dispatchable "Something that can be dispatched, like an observer." (add-handler [_ handler] "") (remove-handler [_ handler] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Disposable "Something that can be disposed." (dispose [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Enqueable "Something that can be enqueued." (put [_ something] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Gettable "Something that gives access to key-values." (getv [_ key] "") (has? [_ key] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Hierarchical "Something that has a parent." (parent [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Idable "Something that can be identified." (id [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Initable "Something that can be initialized." (init [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Finzable "Something that can be finalized - opposite to initialize." (finz [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Interruptable "Something that can be interrupted." (interrupt [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Schedulable "Something that can be scheduled." (wakeup [_ arg] "") (schedule [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Morphable "Something that can be morphed." (morph [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Typeable "Something that can be identified as a type." (typeid [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Openable "Something that can be opened." (open [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Receivable "Something that can receive a message." (receive [_ msg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Resetable "Something that can be reset." (reset [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Restartable "Something that can be restarted." (restart [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Sendable "Something that can send a message." (send [_ msg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Settable "Something that supports settable key-values." (unsetv [_ key] "") (setv [_ key arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Startable "Something that can be started." (stop [_] "") (start [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Connectable "Something that can be connected." (disconnect [_] "") (connect [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Suspendable "Something that can be suspended." (resume [_] "") (suspend [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Triggerable "Something that can be triggered." (fire [_] [_ arg] "") (set-trigger [_ t] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Nextable "Something that has a next." (next [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Versioned "Something that has a version." (version [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn id?? "Get id of this object" [obj] (cond (satisfies? Idable obj) (czlab.basal.core/id obj) (map? obj) (:id obj) :t nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;EOF
true
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.basal.core "Useful additions to clojure core & string." (:refer-clojure :exclude [send next]) (:require [clojure.set :as ct] [clojure.string :as cs] [io.aviso.ansi :as ansi] [clojure.tools.logging :as l]) (:import [java.util Date] [java.lang System StringBuilder])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;; #^"[Ljava.lang.Object;" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:doc "Log flag(toggle) used internally."} LOG-FLAG (not (.equals "false" (System/getProperty "czlabloggerflag")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private t-bad "FAILED") (def ^:private t-ok "passed") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defmacro- "Same as defmacro but private." {:arglists '([name & more])} [name & more] (list* `defmacro (with-meta name (assoc (meta name) :private true)) more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defonce- "Same as defonce but private." {:arglists '([name & more])} [name & more] (list* `defonce (with-meta name (assoc (meta name) :private true)) more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro def- "Same as def but private." {:arglists '([name & more])} [name & more] (list* `def (with-meta name (assoc (meta name) :private true)) more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-long-var "Define a long array[1] for local operation" ([] `(decl-long-var 0)) ([n] `(long-array 1 ~n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-int-var "Define a int array[1] for local operation" ([] `(decl-int-var 0)) ([n] `(int-array 1 ~n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn int-var "" ([^ints arr v] (aset arr 0 (int v)) (int v)) ([^ints arr] (aget arr 0)) ([^ints arr op nv] (let [v (int (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn long-var "" ([^longs arr ^long v] (aset arr 0 v) v) ([^longs arr] (aget arr 0)) ([^longs arr op nv] (let [v (long (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-var-docstring "Add docstring to var" [v s] `(alter-meta! ~v assoc :doc ~s)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-var-private "Make var private" [v] `(alter-meta! ~v assoc :private true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-object<> "Define a simple type" [name & more] `(defrecord ~name [] ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol JEnumProto "Mimic Java Enum" (lookup-enum-str [_ s] "Get enum from string") (get-enum-str [_ e] "Get string value of enum") (lookup-enum-int [_ n] "Get enum from int")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;Loose equivalent of a Java Enum (decl-object<> JEnum JEnumProto (get-enum-str [me e] (if (contains? me e) (cs/replace (str e) #"^:" ""))) (lookup-enum-str [me s] (let [kee (keyword s)] (some #(if (= kee (first %)) (first %)) me))) (lookup-enum-int [me n] (some #(if (= n (last %)) (first %)) me))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-generic-enum "e.g. (decl-generic-enum weather hot cold)" [name base & more] (assert (and (not-empty more) (integer? base))) `(def ~name (czlab.basal.core/object<> czlab.basal.core.JEnum (-> {} ~@(reduce #(conj %1 `(assoc (keyword (str *ns*) ~(str %2)) ~(+ base (count %1)))) [] more))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;how to make it private ;;(alter-meta! #'weather assoc :private true) (defmacro decl-special-enum "e.g. (decl-special-enum weather hot 3 cold 7)" [name & more] (assert (even? (count more))) (let [ps (partition 2 more)] `(def ~name (czlab.basal.core/object<> czlab.basal.core.JEnum (-> {} ~@(mapv #(do `(assoc (keyword (str *ns*) ~(str (first %))) ~(last %))) ps)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro trace "Logging at TRACE level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :trace ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro debug "Logging at DEBUG level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :debug ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro info "Logging at INFO level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :info ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro warn "Logging at WARN level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :warn ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro error "Logging at ERROR level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :error ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fatal "Logging at FATAL level." {:arglists '([& xs])} [& xs] (and czlab.basal.core/LOG-FLAG `(clojure.tools.logging/logf :fatal ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn exception "Log an exception at ERROR level." {:arglists '([e])} [e] (when czlab.basal.core/LOG-FLAG (clojure.tools.logging/logf :error e "") (clojure.tools.logging/logf :error "%s" "exception thrown."))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def BOOLS #{"true" "yes" "on" "ok" "active" "1"}) (def ^String HEX-CHAR-STR "0123456789ABCDEF") (def ^String hex-char-str "0123456789abcdef") (def ^{:tag "[C"} HEX-CHARS (.toCharArray HEX-CHAR-STR)) (def ^{:tag "[C"} hex-chars (.toCharArray hex-char-str)) (def ^String USASCII "ISO-8859-1") (def ^String UTF16 "UTF-16") (def ^String UTF8 "UTF-8") (def OneK 1024) (def FourK (* 4 OneK)) (def KiloBytes OneK) (def BUF-SZ (* 4 KiloBytes)) (def MegaBytes (* KiloBytes KiloBytes)) (def GigaBytes (* KiloBytes KiloBytes KiloBytes)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro funcit?? "Maybe run a function with args." {:arglists '([f & args])} [f & args] `(let [f# ~f] (if (fn? f#) (f# ~@args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro pre "Like :pre, assert conditions." {:arglists '([& conds])} [& conds] `(assert (and ~@conds) "precond failed.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro atom? "If obj is an atom?" {:arglists '([x])} [x] `(instance? clojure.lang.Atom ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro n#-even? "Count of collection even?" {:arglists '([coll])} [coll] `(even? (count ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !sas? "Same as not-satisfies?" {:arglists '([proto obj])} [proto obj] `(not (satisfies? ~proto ~obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sas? "Same as satisfies?" {:arglists '([proto obj])} [proto obj] `(satisfies? ~proto ~obj)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !is? "Same as not-instance?" {:arglists '([clazz obj])} [clazz obj] `(not (instance? ~clazz ~obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro is? "Same as instance?" {:arglists '([clazz obj])} [clazz obj] `(instance? ~clazz ~obj)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro map-> "Same as into {}." {:arglists '([& more])} [& more] `(into {} ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vec-> "Same as into []." {:arglists '([& more])} [& more] `(into [] ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro set-> "Same as into #{}." {:arglists '([& more])} [& more] `(into #{} ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cc+1 "Prepend an item to collection(s)." {:arglists '([a & more])} [a & more] `(concat [~a] ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cc+ "Same as concat." {:arglists '([& more])} [& more] `(concat ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _2 "Same as second." {:arglists '([coll])} [coll] `(second ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _1 "Same as first." {:arglists '([coll])} [coll] `(first ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _3 "Get the 3rd item." {:arglists '([coll])} [coll] `(nth ~coll 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _E "Same as last." {:arglists '([coll])} [coll] `(last ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro _NE "Get the last item via nth." {:arglists '([coll])} [coll] `(let [x# ~coll] (nth x# (- (count x#) 1)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !zero? "Same as not-zero?" {:arglists '([n])} [n] `(not (zero? ~n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro n# "Same as count." {:arglists '([coll])} [coll] `(count ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro car "Same as first." {:arglists '([coll])} [coll] `(first ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cdr "Same as rest." {:arglists '([coll])} [coll] `(rest ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro one? "If count() is 1?" {:arglists '([coll])} [coll] `(== 1 (count ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro two? "If count() is 2?" {:arglists '([coll])} [coll] `(== 2 (count ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro one+? "If count() is more than 1?" {:arglists '([coll])} [coll] `(> (count ~coll) 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro or?? "(or?? [= a] b c) => (or (= b a) (= c a))." {:arglists '([bindings & args])} [bindings & args] (let [op (gensym) arg (gensym) [p1 p2] bindings] `(let [~op ~p1 ~arg ~p2] (or ~@(map (fn [n] `(~op ~n ~arg)) args))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro dissoc!! "Mutable dissoc (atom)." {:arglists '([a & args])} [a & args] (let [X (gensym)] `(let [~X ~a] (swap! ~X dissoc ~@args) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro assoc!! "Mutable assoc (atom)." {:arglists '([a & args])} [a & args] (let [X (gensym)] `(let [~X ~a] (swap! ~X assoc ~@args) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_* "Wrap code into a fn(...)." {:arglists '([& forms])} [& forms] `(fn [& ~'____xs] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_3 "Wrap code into a fn(a1,a2,a3)." {:arglists '([& forms])} [& forms] `(fn [~'____1 ~'____2 ~'____3] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_2 "Wrap code into a fn(a1,a2)." {:arglists '([& forms])} [& forms] `(fn [~'____1 ~'____2] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_1 "Wrap code into a fn(a1)." {:arglists '([& forms])} [& forms] `(fn [~'____1] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro fn_0 "Wrap code into a fn()." {:arglists '([& forms])} [& forms] `(fn [] ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro tset* "A transient set." {:arglists '([] [x])} ([] `(tset* nil)) ([x] `(transient (or ~x #{})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro tvec* "A transient vector." {:arglists '([] [x])} ([] `(tvec* nil)) ([x] `(transient (or ~x [])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro tmap* "A transient map." {:arglists '([] [x])} ([] `(tmap* nil)) ([x] `(transient (or ~x {})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro persist! "Same as persistent!." {:arglists '([coll])} [coll] `(persistent! ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro atomic "Atomize fields as map." {:arglists '([& args])} [& args] `(atom (array-map ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro mapfv "Apply a binary-op to the value over the forms. e.g. (+ 3 1 (+ 2 2)) => [4 7]." {:arglists '([op value & forms])} [op value & forms] `(vector ~@(map (fn [f] `(~op ~f ~value)) forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro last-index "count less 1." {:arglists '([coll])} [coll] `(- (count ~coll) 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro nexth "The nth item after i." {:arglists '([coll i])} [coll i] `(nth ~coll (+ 1 ~i))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro chop "Same as partition." {:arglists '([& args])} [& args] `(partition ~@args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro inc* "One plus, x+1." {:arglists '([x])} [x] `(+ 1 ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro dec* "One less, x-1." {:arglists '([x])} [x] `(- ~x 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do->false "Do returns false." {:arglists '([& forms])} [& forms] `(do ~@forms false)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do->true "Do returns true." {:arglists '([& forms])} [& forms] `(do ~@forms true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do->nil "Do returns nil." {:arglists '([& forms])} [& forms] `(do ~@forms nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro let->false "Let returns false." {:arglists '([& forms])} [& forms] `(let ~@forms false)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro let->true "Let returns true." {:arglists '([& forms])} [& forms] `(let ~@forms true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro let->nil "Let returns nil." {:arglists '([& forms])} [& forms] `(let ~@forms nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defenum "Enum definition. e.g. (defenum ^:private xyz 1 a b c) will generate (def ^:private xyz-a 1) (def ^:private xyz-b 2) (def ^:private xyz-c 3)." {:arglists '([ename start & args])} [ename start & args] (let [mm (meta ename)] (assert (number? start) "Enum expecting a number.") `(do ~@(loop [v start [m & ms] args out []] (if (nil? m) out (let [m' (meta m) z (str (name ename) "-" (name m))] (recur (+ 1 v) ms (conj out `(def ~(with-meta (symbol z) (merge m' mm)) ~v))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro condp?? "condp without throwing exception." {:arglists '([pred expr & clauses])} [pred expr & clauses] (let [c (count clauses) z (count (filter #(and (keyword? %) (= :>> %)) clauses)) d (- c z) xs (if-not (even? d) clauses (concat clauses ['nil]))] `(condp ~pred ~expr ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro case?? "case without throwing exception." {:arglists '([expr & clauses])} [expr & clauses] (let [c (count clauses) xs (if-not (even? c) clauses (concat clauses ['nil]))] `(case ~expr ~@xs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-xxx?? {:arglists '([F bindings then] [F bindings then else])} ([F bindings then] `(if-xxx?? ~F ~bindings ~then nil)) ([F bindings then else & oldform] (let [_ (assert (== 2 (count bindings)) "Too many (> 2) in bindings.") X (gensym) f1 (first bindings)] (assert (symbol? f1)) `(let [~X ~(last bindings) ~f1 ~X] (if (~F ~X) ~then ~else))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-inst "If expr is instance of class, execute `then`, otherwise `else`." {:arglists '([clazz expr then] [clazz expr then else])} ([clazz expr then] `(if-inst ~clazz ~expr ~then nil)) ([clazz expr then else & oldform] `(if (instance? ~clazz ~expr) ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-inst "If expr is instance of class, execute `body`." {:arglists '([clazz expr & body])} [clazz expr & body] `(if (instance? ~clazz ~expr) (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-proto "If expr satisfies the protocol, execute `then`, otherwise `else`." {:arglists '([proto expr then] [proto expr then else])} ([proto expr then] `(if-proto ~proto ~expr ~then nil)) ([proto expr then else & oldform] `(if (satisfies? ~proto ~expr) ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-proto "If expr satisfies the protocol, execute `body`." {:arglists '([proto expr & body])} [proto expr & body] `(if (satisfies? ~proto ~expr) (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-nil "If expr evals to nil, execute `then`, otherwise `else`." {:arglists '([expr then] [expr then else])} ([expr then] `(if-nil ~expr ~then nil)) ([expr then else & oldform] `(if (nil? ~expr) ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-nil "If expr evals to nil, execute `body`." {:arglists '([expr & body])} [expr & body] `(if (nil? ~expr) (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn is-throwable? "If object is a Throwable?" {:arglists '([x])} [x] (instance? Throwable x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-throw "bindings => binding-form test If test is a Throwable, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-throw ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? czlab.basal.core/is-throwable? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-throw "bindings => binding-form test If test is a Throwable, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-throw ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-var "bindings => binding-form test If test is a var, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-var ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? var? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-var "bindings => binding-form test If test is a var, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-var ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-number "bindings => binding-form test If test is a number, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-number ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? number? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-number "bindings => binding-form test If test is a number, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-number ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-string "bindings => binding-form test If test is a string, evaluates 'then' with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-string ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? string? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-string "bindings => binding-form test If test is a string, evaluates the body." {:arglists '([bindings & body])} [bindings & body] `(if-string ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro nloop "Loop over code n times." {:arglists '([n & forms])} [n & forms] (let [x (gensym)] `(dotimes [~x ~n] ~@forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro each* "Evals function for each element, indexed." {:arglists '([func coll])} [func coll] (let [C (gensym) I (gensym) T (gensym)] `(let [~C ~coll ~T (count ~C)] (dotimes [~I ~T] (~func (nth ~C ~I) ~I))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro each "Evals function for each element." {:arglists '([func coll])} [func coll] (let [I (gensym)] `(doseq [~I ~coll] (~func ~I)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro mget "Java map.get()." {:arglists '([m k])} [m k] `(.get ~(with-meta m {:tag 'java.util.Map}) ~k)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mdel! "Java map.remove()." {:arglists '([m k])} [m k] (.remove ^java.util.Map m k)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro mput! "Java map.put()." {:arglists '([m k v])} [m k v] `(.put ~(with-meta m {:tag 'java.util.Map}) ~k ~v)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;testing stuff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro deftest "A bunch of test-cases grouped together." {:arglists '([name & body])} [name & body] `(def ~name (fn [] (filter #(not (nil? %)) [~@body])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ensure?? "Assert test was ok." {:arglists '([msg form])} [msg form] `(czlab.basal.core/ensure-test ~form ~msg)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ensure-thrown?? "Assert an error was thrown." {:arglists '([msg expected form])} [msg expected form] `(try ~form (czlab.basal.core/ensure-thrown ~msg) (catch Throwable e# (czlab.basal.core/ensure-thrown ~expected e# ~msg)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro prn!! "Println with format." {:arglists '([fmt & args])} [fmt & args] `(println (format ~fmt ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro prn! "Print with format." {:arglists '([fmt & args])} [fmt & args] `(print (format ~fmt ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (defmacro- make-fn "Hack to wrap a macro as fn so one can use *apply* on it." [m] `(fn [& xs#] (eval (cons '~m xs#))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro object<> "Create a new record instance. e.g. (object<> ClazzA) (object<> ClazzA {:a 1}) (object<> ClazzA :a 1 :b 2)" {:arglists '([z] [z m] [z ab & more])} ([z] `(new ~z)) ([z m] `(merge (new ~z) ~m)) ([z a b & more] `(assoc (new ~z) ~a ~b ~@more))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro atomic<> "Create a new record instance, with all attributes inside an atom. e.g. (atomic<> ClazzA) (atomic<> ClazzA {:a 1}) (atomic<> ClazzA :a 1 :b 2)" {:arglists '([z] [z m] [z ab & more])} ([z] `(assoc (new ~z) :o (atom {}))) ([z m] `(assoc (new ~z) :o (atom (merge {} ~m)))) ([z a b & more] `(assoc (new ~z) :o (atom (assoc {} ~a ~b ~@more))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vargs "Coerce into java array of type z." {:arglists '([z arglist])} [z arglist] `(into-array ~z ~arglist)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro preduce<map> "Reduce with a transient map accumulator, returning a map." {:arglists '([f coll])} [f coll] `(persistent! (reduce ~f (transient {}) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro preduce<set> "Reduce with a transient set accumulator, returning a set." {:arglists '([f coll])} [f coll] `(persistent! (reduce ~f (transient #{}) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro preduce<vec> "Reduce with a transient vec accumulator, returning a vec." {:arglists '([f coll])} [f coll] `(persistent! (reduce ~f (transient []) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rset! "Reset a atom." {:arglists '([a] [a value])} ([a] `(rset! ~a nil)) ([a value] `(reset! ~a ~value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro exp! "Create an exception of type E." {:arglists '([E & args])} [E & args] `(new ~E ~@args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro trap! "Throw exception of type E." {:arglists '([E & args])} [E & args] `(throw (exp! ~E ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro raise! "Throw java Exception with message." {:arglists '([fmt & args])} [fmt & args] `(throw (new java.lang.Exception (str (format ~fmt ~@args))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-assert-exp "Generate a function which when called, will assert the condition and if false, throw the desired exception." {:arglists '([name E])} [name E] `(defn ~name [~'kond ~'arg & ~'xs] (if-not ~'kond (cond (string? ~'arg) (czlab.basal.core/trap! ~E (str (apply format ~'arg ~'xs))) (instance? Throwable ~'arg) (czlab.basal.core/trap! ~E ~(with-meta 'arg {:tag 'Throwable})))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decl-throw-exp "Generate a function which when called, will throw the desired exception." {:arglists '([name E])} [name E] `(defn ~name [~'arg & ~'xs] (cond (string? ~'arg) (czlab.basal.core/trap! ~E (str (apply format ~'arg ~'xs))) (instance? Throwable ~'arg) (czlab.basal.core/trap! ~E ~(with-meta 'arg {:tag 'Throwable}))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro assert-on! "Like assert, but throws a specific exception." {:arglists '([kond E & args])} [kond E & args] `(if-not ~kond (trap! ~E ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do-with "bindings => [symbol init-expr] Evals the body in a context in which the symbol is always the returned value." {:arglists '([bindings & forms])} [bindings & forms] (let [f (first bindings) sz (count bindings)] (assert (or (== sz 1) (== sz 2)) "(not 1 or 2) in bindings.") (assert (symbol? f)) (if (== sz 1) `(let [~f ~f] ~@forms ~f) `(let [~f ~(last bindings)] ~@forms ~f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do-with-str "bindings => [symbol init-expr] Eval the body in a context in which the symbol is always the returned value to-string'ed. e.g. (do-with-str [a (f)] ... (str a))." {:arglists '([bindings & forms])} [bindings & forms] `(str (czlab.basal.core/do-with ~bindings ~@forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro do-with-atom "bindings => [symbol init-expr] Eval the body in a context in which the symbol is always the returned value deref'ed. e.g. (do-with-atom [a (atom 0)] ... (deref a))." {:arglists '([bindings & forms])} [bindings & forms] `(deref (czlab.basal.core/do-with ~bindings ~@forms))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro bool! "Same as boolean." {:arglists '([x])} [x] `(boolean ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro trye! "Eat exception and return a value." {:arglists '([value & forms])} [value & forms] `(try ~@forms (catch Throwable ~'_ ~value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro try! "Eat exception and return nil." {:arglists '([& forms])} [& forms] `(czlab.basal.core/trye! nil ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-some+ "bindings => [binding-form test]. When test is not empty, evaluates body with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-some+ ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? empty? ~bindings ~else ~then))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-some+ "bindings => [binding-form test]. When test is not empty, evaluates body with binding-form bound to the value of test." {:arglists '([bindings & body])} [bindings & body] `(czlab.basal.core/if-some+ ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro if-fn "bindings => [binding-form test]. When test is a fn?, evaluates body with binding-form bound to the value of test." {:arglists '([bindings then] [bindings then else])} ([bindings then] `(if-fn ~bindings ~then nil)) ([bindings then else & oldform] `(czlab.basal.core/if-xxx?? fn? ~bindings ~then ~else))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro when-fn "bindings => [binding-form test]. When test is a fn?, evaluates body with binding-form bound to the value of test." {:arglists '([bindings & body])} [bindings & body] `(czlab.basal.core/if-fn ~bindings (do ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro doto->> "Combine doto and ->>." {:arglists '([x & forms])} [x & forms] (let [X (gensym)] `(let [~X ~x] ~@(map (fn [f] (if (seq? f) `(~@f ~X) `(~f ~X))) forms) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro doto-> "Combine doto and ->." {:arglists '([x & forms])} [x & forms] (let [X (gensym)] `(let [~X ~x] ~@(map (fn [f] (if (seq? f) (let [z (first f) r (rest f)] `(~z ~X ~@r)) `(~f ~X))) forms) ~X))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro eq? "Use java's .equals method." {:arglists '([a b])} [a b] `(.equals ~a ~b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !eq? "Use java's .equals method." {:arglists '([a b])} [a b] `(not (.equals ~a ~b))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !=? "Same as not-identical?" {:arglists '([& more])} [& more] `(not (identical? ~@more))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro =? "Same as identical?" {:arglists '([& more])} [& more] `(identical? ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !in? "Same as not-contains?" {:arglists '([& more])} [& more] `(not (contains? ~@more))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro in? "Same as contains?" {:arglists '([& more])} [& more] `(contains? ~@more)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;had to use this trick to prevent reflection warning (defmacro cast? "Cast object of this type else nil." {:arglists '([someType obj])} [someType obj] (let [X (gensym)] `(let [~X ~obj] (if (instance? ~someType ~X) ^{:tag ~someType} (identity (.cast ~someType ~X)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro cexp? "Try casting to Throwable." {:arglists '([e])} [e] `(cast? Throwable ~e)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !nil? "Same as not-nil." {:arglists '([x])} [x] `(not (nil? ~x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rnil "Skip nil(s) in collection." {:arglists '([coll])} [coll] `(remove nil? ~coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rnilv "Same as rnil but returns a vec." {:arglists '([coll])} [coll] `(into [] (remove nil? ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro szero? "Safe zero?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E)(zero? ~E))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sneg? "Safe neg?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E)(neg? ~E))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro spos? "Safe pos?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E)(pos? ~E))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro snneg? "Safe not neg?" {:arglists '([e])} [e] (let [E (gensym)] `(let [~E ~e] (and (number? ~E) (or (zero? ~E)(pos? ~E)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !false? "Same as not-false." {:arglists '([x])} [x] `(not (false? ~x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro !true? "Same as not true." {:arglists '([x])} [x] `(not (true? ~x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro assert-not "Assert a false condition." {:arglists '([cond])} [cond] `(assert (not ~cond))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro marray "n-size java array of type Z." {:arglists '([Z n])} [Z n] `(make-array ~Z ~n)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro zarray "0-size java array of type Z." {:arglists '([Z])} [Z] `(make-array ~Z 0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vtbl** "Make a virtual table: op1 f1 op2 f2, with parent vtbl." {:arglists '([parent & args])} [parent & args] (do (assert (even? (count args))) `(czlab.basal.core/object<> ~'czlab.basal.core.VTable :____proto ~parent ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro vtbl* "Make a virtual table: op1 f1 op2 f2." {:arglists '([& args])} [& args] `(vtbl** nil ~@args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro wo* "Same as with-open." {:arglists '([bindings & forms])} [bindings & forms] `(with-open ~bindings ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro wm* "Same as with-meta." {:arglists '([obj m])} [obj m] `(with-meta ~obj ~m)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ->str "Same as java's .toString." {:arglists '([obj])} [obj] `(some-> ~obj .toString)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;monads ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro run-bind ;"Run the bind operator. *Internal*" {:arglists '([binder steps expr])} [binder steps expr] (let [more (drop 2 steps) [a1 mv] (take 2 steps)] `(~binder ~mv (fn [~a1] ~(if (not-empty more) `(run-bind ~binder ~more ~expr) `(do ~expr)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defmonad "Define a named monad by defining the monad operations. The definitions are written like bindings to the monad operations bind and unit (required) and zero and plus (optional)." {:arglists '([name ops] [name docs ops])} ([name ops] `(defmonad ~name "" ~ops)) ([name docs ops] (let [_ (assert (not-empty ops) "no monad ops!")] `(def ~(with-meta name {:doc docs}) (merge {:bind nil :unit nil :zero nil :plus nil} (into {} (map #(vec %) (partition 2 ~ops)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro domonad "Monad comprehension. Takes the name of a monad, a vector of steps given as binding-form, and a result value specified by body." {:arglists '([monad steps] [monad steps body])} ([monad steps] `(domonad ~monad ~steps nil)) ([monad steps body] (let [E (gensym) B (gensym) U (gensym) Z (gensym)] `(let [{~B :bind ~U :unit ~Z :zero} ~monad ;if no body try to run the zero func, ;else run the unit on it. ~E #(if (and (nil? %) (some? ~Z)) ~Z (~U %))] (czlab.basal.core/run-bind ~B ~steps (~E ~body)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;end-macros ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;monads ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-identity "Monad describing plain computations. This monad does nothing at all. It is useful for testing, for combination with monad transformers, and for code that is parameterized with a monad." [:bind (fn [mv mf] (mf mv)) :unit identity]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-maybe "Monad describing computations with possible failures. Failure is represented by nil, any other value is considered valid. As soon as a step returns nil, the whole computation will yield nil as well." [:unit identity :bind (fn [mv mf] (if-not (nil? mv) (mf mv)))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-list "Monad describing multi-valued computations, i.e. computations that can yield multiple values. Any object implementing the seq protocol can be used as a monadic value." [:bind (fn [mv mf] (flatten (map mf mv))) :unit (fn_1 (vector ____1)) :zero [] :plus (fn_* (flatten ____xs))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-state "Monad describing stateful computations. The monadic values have the structure (fn [old-state] [result new-state])." [:unit (fn [v] (fn [s] [v s])) :bind (fn [mv mf] (fn [s] (let [[v s'] (mv s)] ((mf v) s'))))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmonad m-continuation "Monad describing computations in continuation-passing style. The monadic values are functions that are called with a single argument representing the continuation of the computation, to which they pass their result." [:unit (fn [v] (fn [cont] (cont v))) :bind (fn [mv mf] (fn [cont] (mv (fn [v] ((mf v) cont)))))]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn run-cont "Execute the computation in the cont monad and return its result." {:arglists '([cont])} [cont] (cont identity)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; end-monad ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn kvs->map "Turn a list of key values into map." {:arglists '([arglist])} [arglist] {:pre [(even? (count arglist))]} (apply array-map arglist)) ;(into {} (map #(vec %) (partition 2 arglist))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn repeat-str "Repeat string n times." {:tag String :arglists '([n s])} [n s] (cs/join "" (repeat n s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn num?? "If n is not a number, return other." {:arglists '([n other])} [n other] {:pre [(number? other)]} (if (number? n) n other)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn !== "Same as (not (== num1 num2))." {:arglists '([x] [x y] [x y & more])} ([x] false) ([x y] (not (== x y))) ([x y & more] (not (apply == x y more)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn flip "Invert number if not zero." {:arglists '([x])} [x] {:pre [(number? x)]} (if (zero? x) 0 (/ 1 x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn percent "Calculate the percentage." {:arglists '([numerator denominator])} [numerator denominator] (* 100.0 (/ numerator denominator))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn split-seq "Split a collection into 2 parts." {:arglists '([coll cnt])} [coll cnt] (if-not (< cnt (count coll)) (list (concat [] coll) ()) (list (take cnt coll) (drop cnt coll)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn compare-asc* "Returns a ascending compare function." {:arglists '([] [f])} ([] (compare-asc* identity)) ([f] (fn_2 (cond (< (f ____1) (f ____2)) -1 (> (f ____1) (f ____2)) 1 :else 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn compare-des* "Returns a descending compare function." {:arglists '([] [f])} ([] (compare-des* identity)) ([f] (fn_2 (cond (< (f ____1) (f ____2)) 1 (> (f ____1) (f ____2)) -1 :else 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- xxx-by "Used by min-by & max-by. *Internal*" {:arglists '([cb coll])} [cb coll] (if (not-empty coll) (reduce cb (_1 coll) (rest coll)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn min-by "Find item with minimum value as defined by the function." {:arglists '([f coll])} [f coll] (xxx-by #(if (< (f %1) (f %2)) %1 %2) coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn max-by "Find item with maximum value as defined by the function." {:arglists '([f coll])} [f coll] (xxx-by #(if (< (f %1) (f %2)) %2 %1) coll)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ensure-test "Assert a test condition, returning a message." {:arglists '([cond msg])} [cond msg] (str (try (if cond t-ok t-bad) (catch Throwable _ t-bad)) ": " msg)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ensure-thrown "Assert an exception is thrown during test." {:arglists '([msg] [expected error msg])} ([msg] (ensure-thrown nil nil msg)) ([expected error msg] (str (if (nil? error) t-bad (if (or (= expected :any) (is? expected error)) t-ok t-bad)) ": " msg))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rip-fn-name "Extract (mangled) name of the function." {:tag String :arglists '([func])} [func] (let [s (str func) h (cs/index-of s "$") s (if h (subs s (+ 1 h)) s) p (cs/last-index-of s "@")] (if p (subs s 0 p) s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-int "Operate like a mutable int, get and set." {:arglists '([] [arr] [arr v] [arr op nv])} ;setter ([^ints arr v] (aset arr 0 (int v)) (int v)) ;ctor ([] (int-array 1 0)) ;getter ([^ints arr] (int (aget arr 0))) ;apply (op old-val new-value) ([^ints arr op nv] (let [v (int (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-int* "Create & init mu-i." {:arglists '([i])} [i] {:pre [(number? i)]} (doto (mu-int) (mu-int i))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-long "Operate like a mutable long, get and set." {:arglists '([] [arr] [arr v] [arr op nv])} ;setter ([^longs arr v] (aset arr 0 (long v)) (long v)) ;ctor ([] (long-array 1 0)) ;getter ([^longs arr] (long (aget arr 0))) ;apply (op old-val new-val) ([^longs arr op nv] (let [v (long (op (aget arr 0) nv))] (aset arr 0 v) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mu-long* "Create & init a mu-long." {:arglists '([n])} [n] {:pre [(number? n)]} (doto (mu-long) (mu-long n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nth?? "Get the nth element, 1-indexed." {:arglists '([coll pos])} [coll pos] {:pre [(> pos 0)]} (first (drop (- pos 1) coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn vargs* "Coerce into java array." {:arglists '([clazz & args])} [clazz & args] (vargs clazz args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (defn- interject "Run the function on the current field value, replacing the key with the returned value. function(pojo oldvalue) -> newvalue." [pojo field func] {:pre [(map? pojo) (fn? func)]} (assoc pojo field (func pojo field)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn scoped-keyword "Scope name as a fully-qualified keyword." {:arglists '([t])} [t] {:pre [(string? t) (nil? (cs/index-of t "/")) (nil? (cs/index-of t ":"))]} (keyword (str *ns*) t)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn is-scoped-keyword? "If a scoped keyword?" {:arglists '([kw])} [kw] (and (keyword? kw) (cs/includes? (str kw) "/"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rand-sign "Randomly choose a sign." {:arglists '([])} [] (if (even? (rand-int Integer/MAX_VALUE)) 1 -1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rand-bool "Randomly choose a boolean value." {:arglists '([])} [] (even? (rand-int Integer/MAX_VALUE))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn num-sign "Find the sign of a number." {:arglists '([n])} [n] {:pre [(number? n)]} (cond (> n 0) 1 (< n 0) -1 :else 0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->long "String as a long value." {:tag Long :arglists '([s] [s dv])} ([s] (s->long s nil)) ([s dv] (try (Long/parseLong ^String s) (catch Throwable _ (if (number? dv) (long dv) (throw _)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->int "String as an int value." {:tag Integer :arglists '([s] [s dv])} ([s] (s->int s nil)) ([s dv] (try (Integer/parseInt ^String s) (catch Throwable _ (if (number? dv) (int dv) (throw _)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->double "String as a double value." {:tag Double :arglists '([s][s dv])} ([s] (s->double s nil)) ([s dv] (try (Double/parseDouble ^String s) (catch Throwable _ (if (number? dv) (double dv) (throw _)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn s->bool "String as a boolean value." {:arglists '([s])} [s] (contains? BOOLS (cs/lower-case (str s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; test and assert funcs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-isa "Is child of parent?" {:arglists '([reason parent child])} [reason parent child] (do->true (-> (cond (and (class? parent) (class? child)) (isa? child parent) (or (nil? parent) (nil? child)) false (not (class? parent)) (test-isa reason (class parent) child) (not (class? child)) (test-isa reason parent (class child))) (assert (str reason child " not-isa " parent))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-some "Object is not null?" {:arglists '([reason obj])} [reason obj] (do->true (assert (some? obj) (str reason " is null.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-cond "A true condition?" {:arglists '([reason cond])} [reason cond] (do->true (assert cond (str reason)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-hgl "String is not empty?" {:arglists '([reason s])} [reason s] (do->true (assert (and (string? s) (not-empty s)) (str reason " is empty.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- test-xxx [a b] (condp instance? b Double :double Long :long Float :double Integer :long (raise! "Allow numbers only!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti test-pos0 "Check number is not negative?" test-xxx) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti test-pos "Check number is positive?" test-xxx) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos0 :double [reason v] (do->true (assert (snneg? v) (str reason " must be >= 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos0 :long [reason v] (do->true (assert (snneg? v) (str reason " must be >= 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos :double [reason v] (do->true (assert (spos? v) (str reason " must be > 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-pos :long [reason v] (do->true (assert (spos? v) (str reason " must be > 0.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn test-seq+ "Check sequence is not empty?" {:arglists '([reason v])} [reason v] (do->true (assert (pos? (count v)) (str reason " must be non empty.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sort-join "Sort and concatenate strings." {:tag String :arglists '([ss] [sep ss])} ([ss] (sort-join "" ss)) ([sep ss] (if (nil? ss) "" (cs/join sep (sort ss))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn strip-ns-path "Remove the leading colon." {:tag String :arglists '([path])} [path] (cs/replace (str path) #"^:" "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol VTableAPI "Act like a virtual table." (vt-set-proto [_ par] "Hook up parent prototype object.") (vt-has? [_ kee] "True if key exists in the hierarchy.") (vt-run?? [_ kee arglist] [_ kee arglist skip?] "Find key. If function run it else return value.") (vt-find?? [_ kee] [_ kee skip?] "Find this key, if skip? then search from parent.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord VTable [] VTableAPI (vt-set-proto [me par] (assoc me :____proto par)) (vt-find?? [me kee] (vt-find?? me kee false)) (vt-find?? [me kee skip?] (let [p (:____proto me)] (cond skip? (if p (vt-find?? p kee)) (in? me kee) (get me kee) :else (if p (vt-find?? p kee))))) (vt-has? [me kee] (or (in? me kee) (if-some [p (:____proto me)] (vt-has? p kee)))) (vt-run?? [me kee arglist] (vt-run?? me kee arglist false)) (vt-run?? [me kee arglist skip?] (let [f (vt-find?? me kee skip?)] (if (fn? f) (apply f me arglist) f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn identity-n "Like identity but returns positional param. e.g. (def get-2nd (identity-n 2)) (get-2nd a b c) => b." {:arglists '([n] [n index-zero?])} ([n] (identity-n n false)) ([n index-zero?] {:pre [(number? n)]} (fn_* (let [z (count ____xs) p (if index-zero? n (- n 1))] (assert (and (< p z) (>= p 0)) "Index out of bound.") (nth ____xs p))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- merge-2 [a b] (if (nil? a) b (if (nil? b) a (loop [[z & M] (seq b) tmp (tmap* a)] (let [[k vb] z va (get a k)] (if (nil? z) (persist! tmp) (recur M (assoc! tmp k (cond (not (in? a k)) vb (and (map? vb) (map? va)) (merge-2 va vb) (and (set? vb) (set? va)) (ct/union va vb) :else vb))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn merge+ "Merge (deep) of clojure data." {:arglists '([& more])} [& more] (cond (empty? more) nil (one? more) (_1 more) :else (loop [prev nil [a & xs] more] (if (empty? xs) (merge-2 prev a) (recur (merge-2 prev a) xs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;string stuff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sreduce<> "Reduce with a string-builder." {:arglists '([f coll])} [f coll] `(str (reduce ~f (StringBuilder.) ~coll))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fmt "Same as string format." {:tag String :arglists '([f & args])} [f & args] (apply format f args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn char-array?? "Splits a string into string-char, e.g. \"abc\" = [\"a\" \"b\" \"c\"]." {:arglists '([s])} [s] {:pre [(or (nil? s) (string? s))]} (remove empty? (cs/split s #""))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbf+ "StringBuilder concat." {:tag StringBuilder :arglists '([buf & args])} [buf & args] (doseq [x args] (.append ^StringBuilder buf x)) buf) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbf<> "Same as StringBuilder.new" {:tag StringBuilder :arglists '([] [& args])} ([] (sbf<> "")) ([& args] (let [s (StringBuilder.)] (apply sbf+ s args) s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbf-join "Append to a string-builder, optionally inserting a delimiter if the buffer is not empty." {:tag StringBuilder :arglists '([buf sep item])} [buf sep item] (do-with [^StringBuilder buf] (when item (if (and (!nil? sep) (pos? (.length buf))) (.append buf sep)) (.append buf item)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sbfz "Length of the string-buffer." {:arglists '([b])} [b] (.length ^StringBuilder b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nichts? "Is string empty?" {:arglists '([s])} [s] (or (nil? s) (not (string? s)) (.isEmpty ^String s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hgl? "If string has length?" {:arglists '([s])} [s] (and (string? s) (not (.isEmpty ^String s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn stror "If not s then s2" {:tag String :arglists '([s s2])} [s s2] (if (nichts? s) s2 s)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (defn stror* "If not s then s2...etc" ^String [& args] (loop [[a & more] args] (if (or (hgl? a) (empty? more)) a (recur more))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro stror* "If not s then s2...etc" {:arglists '([& args])} [& args] (let [[a & xs] args] (if (empty? xs) `(stror nil ~a) `(stror ~a (stror* ~@xs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn lcase "Lowercase string safely." {:tag String :arglists '([s])} [s] (str (some-> s clojure.string/lower-case))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ucase "Uppercase string safely." {:tag String :arglists '([s])} [s] (str (some-> s clojure.string/upper-case))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;#^"[Ljava.lang.Class;" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn triml "Get rid of unwanted chars from left." {:tag String :arglists '([src unwantedChars])} [^String src ^String unwantedChars] (if-not (and (hgl? src) (hgl? unwantedChars)) src (loop [len (.length src) pos 0] (if-not (and (< pos len) (cs/index-of unwantedChars (.charAt src pos))) (subs src pos) (recur len (+ 1 pos)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn trimr "Get rid of unwanted chars from right." {:tag String :arglists '([src unwantedChars])} [^String src ^String unwantedChars] (if-not (and (hgl? src) (hgl? unwantedChars)) src (loop [pos (.length src)] (if-not (and (pos? pos) (cs/index-of unwantedChars (.charAt src (- pos 1)))) (subs src 0 pos) (recur (- pos 1)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn includes? "If the char is inside the big str?" {:arglists '([bigs arg])} [^String bigs arg] (let [rc (cond (or (nil? arg) (nil? bigs)) false (integer? arg) (int arg) (string? arg) (number? (cs/index-of bigs arg)) (is? Character arg) (int (.charValue ^Character arg)))] (if-not (number? rc) rc (>= (.indexOf bigs (int rc)) 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro embeds? "If sub-str is inside the big str?" {:arglists '([bigs s])} [bigs s] `(czlab.basal.core/includes? ~bigs ~s)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro has-no-case? "If sub-str is inside the big str - ignore case?" {:arglists '([bigs s])} [bigs s] `(czlab.basal.core/includes? (czlab.basal.core/lcase ~bigs) (czlab.basal.core/lcase ~s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn index-any "If any one char is inside the big str, return the position." {:arglists '([bigs chStr])} [^String bigs ^String chStr] (if-not (and (hgl? bigs) (hgl? chStr)) -1 (let [rc (some #(cs/index-of bigs %) (.toCharArray chStr))] (if (nil? rc) -1 (int rc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn count-str "Count the times the sub-str appears in the big str." {:arglists '([bigs s])} [^String bigs ^String s] (if-not (and (hgl? s) (hgl? bigs)) 0 (loop [len (.length s) total 0 start 0] (let [pos (cs/index-of bigs s start)] (if (nil? pos) total (recur len (+ 1 total) (long (+ pos len)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn count-char "Count the times this char appears in the big str." {:arglists '([bigs ch])} [bigs ch] (reduce #(if (= ch %2) (+ 1 %1) %1) 0 (.toCharArray ^String bigs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro sname "Safely get the name of this object." {:arglists '([n])} [n] `(str (some-> ~n name))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nsb "Empty string if obj is null, or obj.toString." {:tag String :arglists '([obj])} [obj] (if (keyword? obj) (name obj) (str obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn kw->str "Stringify a keyword - no leading colon." {:tag String :arglists '([k])} [k] (cs/replace (str k) #"^:" "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->kw "Concatenate all args and return it as a keyword." {:arglists '([& args])} [& args] (if-not (empty? args) (keyword (apply str args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn nsn "(null) if obj is null, or obj.toString." {:tag String :arglists '([obj])} [obj] (if (nil? obj) "(null)" (str obj))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn match-char? "If this char is inside this set of chars?" {:arglists '([ch setOfChars])} [ch setOfChars] (and (set? setOfChars) (contains? setOfChars ch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro strim "Safely trim this string." {:arglists '([s])} [s] `(str (some-> ~s clojure.string/trim))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn strim-any "Strip source string of these unwanted chars." {:tag String :arglists '([src unwantedChars] [src unwantedChars whitespace?])} ([src unwantedChars] (strim-any src unwantedChars false)) ([^String src ^String unwantedChars whitespace?] (let [s (-> (if whitespace? (strim src) src) (triml unwantedChars) (trimr unwantedChars))] (if whitespace? (strim s) s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn splunk "Split a large string into chunks, each chunk having a specific length." {:arglists '([largeString chunkLength])} [^String largeString chunkLength] (if-not (and (hgl? largeString) (snneg? chunkLength)) [] (mapv #(cs/join "" %1) (partition-all chunkLength largeString)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hasic-any? "If bigs contains any one of these strs - ignore case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (empty? substrs) (nichts? bigs)) (let [lc (lcase bigs)] (true? (some #(number? (cs/index-of lc (lcase %))) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn has-any? "If bigs contains any one of these strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (true? (some #(number? (cs/index-of bigs %)) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hasic-all? "If bigs contains all of these strs - ignore case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (empty? substrs) (nichts? bigs)) (let [lc (lcase bigs)] (every? #(number? (cs/index-of lc (lcase %))) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn has-all? "If bigs contains all of these strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (every? #(number? (cs/index-of bigs %)) substrs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ewic-any? "If bigs endsWith any one of the strs, no-case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (let [lc (lcase bigs)] (true? (some #(cs/ends-with? lc (lcase %)) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn ew-any? "If bigs endsWith any one of the strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (true? (some #(cs/ends-with? bigs %) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn swic-any? "If bigs startWith any one of the strs - no case?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (let [lc (lcase bigs)] (true? (some #(cs/starts-with? lc (lcase %)) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sw-any? "If bigs startWith any one of the strs?" {:arglists '([bigs substrs])} [^String bigs substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? bigs) (empty? substrs)) (true? (some #(cs/starts-with? bigs %) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro eqic? "Same as String.equalIgnoreCase()?" {:arglists '([src other])} [src other] (let [^String ss src ^String oo other] `(.equalsIgnoreCase ~ss ~oo))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn eqic-any? "String.equalIgnoreCase() on any one of the strs?" {:arglists '([src substrs])} [^String src substrs] {:pre [(sequential? substrs)]} (if-not (or (nichts? src) (empty? substrs)) (let [lc (lcase src)] (true? (some #(= lc (lcase %)) substrs))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn eq-any? "If String.equals() on any one of the strs?" {:arglists '([src substrs])} [^String src substrs] {:pre [(sequential? substrs)]} (if-not (empty? substrs) (true? (some #(.equals src %) substrs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn wrapped? "If src string starts with head and ends with tail?" {:arglists '([src head tail])} [^String src ^String head ^String tail] (if (and (hgl? src) (hgl? head) (hgl? tail)) (and (cs/starts-with? src head) (cs/ends-with? src tail)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rights "Get the rightmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (if (or (<= len 0) (nichts? src)) "" (if (< (.length src) len) src (subs src (- (.length src) len))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn lefts "Get the leftmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (if (or (<= len 0) (nichts? src)) "" (if (< (.length src) len) src (subs src 0 len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn drop-head "Drop leftmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (cond (nichts? src) "" (<= len 0) src :else (if (< (.length src) len) "" (subs src len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn drop-tail "Drop rightmost len characters of a String." {:tag String :arglists '([src len])} [^String src len] {:pre [(number? len)]} (cond (nichts? src) "" (<= len 0) src :else (let [n (.length src)] (if (< n len) "" (subs src 0 (- n len)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn matches? "Same as String.matches." {:arglists '([src regex])} [src regex] {:pre [(string? regex)]} (if (hgl? src) (.matches ^String src ^String regex))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn split "Same as String.split." {:arglists '([src regex] [src regex limit])} ([src regex] (split src regex nil)) ([src regex limit] {:pre [(string? regex)]} (if (hgl? src) (remove empty? (if-not (number? limit) (.split ^String src ^String regex) (.split ^String src ^String regex (int limit))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn split-str "Same as String-tokenizer." {:arglists '([s sep] [s sep incSep?])} ([s sep] (split-str s sep false)) ([s sep incSep?] (let [t (new java.util.StringTokenizer ^String s ^String sep (boolean incSep?))] (loop [rc (tvec*)] (if-not (.hasMoreTokens t) (persist! rc) (recur (conj! rc (.nextToken t)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn esc-xml "Escape XML special chars." {:tag String :arglists '([s])} [s] (cs/escape s {\& "&amp;" \> "&gt;" \< "&lt;" \" "&quot;" \' "&apos;"})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- run-test [test] (let [res (test)] [res (every? #(cs/starts-with? % "p") res)])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pretty-millis "Pretty print milliseconds value." {:tag String :arglists '([millis])} [millis] {:pre [(number? millis)]} (let [secs (int (/ millis 1000.0)) millis (int (- millis (* secs 1000.0))) mins (int (/ secs 60.0)) secs (int (- secs (* mins 60.0))) hours (int (/ mins 60.0)) mins (int (- mins (* hours 60.0)))] (cond (pos? hours) (fmt "%d hours %2d minutes %2d.%03d secs" hours mins secs millis) (pos? mins) (fmt "%2d minutes %2d.%03d secs" mins secs millis) (pos? secs) (fmt "%2d.%03d seconds" secs millis) :else (fmt "0.%03d seconds" millis)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- prn-test [results title diff] (let [lsep (repeat-str 78 "+") esep (repeat-str 78 "=") sum (count results) f (filter #(cs/starts-with? % "F") results) p (filter #(cs/starts-with? % "p") results) ok (count p) perc (percent ok sum)] (-> lsep ansi/bold-white prn!!) (-> "test-case: " ansi/bold-white prn!) (-> (stror title (rip-fn-name test)) cs/upper-case ansi/bold-yellow prn!!) (-> (str (Date.)) ansi/bold-white prn!!) (-> lsep ansi/bold-white prn!!) (doseq [r p] (-> r ansi/bold-green prn!!)) (doseq [r f] (-> r ansi/bold-red prn!!)) (-> esep ansi/bold-white prn!!) (-> (str "Passed: " ok "/" sum " [" (int perc) "%%]") ansi/bold-white prn!!) (-> (str "Failed: " (- sum ok)) ansi/bold-white prn!!) (-> (str "cpu-time: " (pretty-millis diff)) ansi/bold-white prn!!) (-> "" ansi/white prn!!))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn clj-test?? "Run test as a clojure test case." {:arglists '([test] [test title print?])} ([test] (clj-test?? test nil true)) ([test title print?] {:pre [(fn? test)]} (let [mark (System/currentTimeMillis) [res ok?] (run-test test) diff (- (System/currentTimeMillis) mark)] (if print? (prn-test res title diff)) ok?))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;protocols ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol AtomicGS "" (getf [_ n] "Get field") (setf [_ n v] "Set field")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Activable "Something that can be activated." (deactivate [_] "") (activate [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Cancelable "Something that can be canceled." (cancel [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Testable "Something that can be tested for validity." (is-valid? [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Catchable "Something that can catch an Exception." (catche [_ e] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Configurable "Something that can be configured with key-values." (get-conf [_] [_ k] "") (set-conf [_ arg] [_ k v] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Debuggable "Something that can be debugged." (dbg-str [_] "") (dbg-show [_ ^PrintStream out] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Dispatchable "Something that can be dispatched, like an observer." (add-handler [_ handler] "") (remove-handler [_ handler] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Disposable "Something that can be disposed." (dispose [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Enqueable "Something that can be enqueued." (put [_ something] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Gettable "Something that gives access to key-values." (getv [_ key] "") (has? [_ key] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Hierarchical "Something that has a parent." (parent [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Idable "Something that can be identified." (id [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Initable "Something that can be initialized." (init [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Finzable "Something that can be finalized - opposite to initialize." (finz [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Interruptable "Something that can be interrupted." (interrupt [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Schedulable "Something that can be scheduled." (wakeup [_ arg] "") (schedule [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Morphable "Something that can be morphed." (morph [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Typeable "Something that can be identified as a type." (typeid [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Openable "Something that can be opened." (open [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Receivable "Something that can receive a message." (receive [_ msg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Resetable "Something that can be reset." (reset [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Restartable "Something that can be restarted." (restart [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Sendable "Something that can send a message." (send [_ msg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Settable "Something that supports settable key-values." (unsetv [_ key] "") (setv [_ key arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Startable "Something that can be started." (stop [_] "") (start [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Connectable "Something that can be connected." (disconnect [_] "") (connect [_] [_ arg] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Suspendable "Something that can be suspended." (resume [_] "") (suspend [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Triggerable "Something that can be triggered." (fire [_] [_ arg] "") (set-trigger [_ t] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Nextable "Something that has a next." (next [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Versioned "Something that has a version." (version [_] "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn id?? "Get id of this object" [obj] (cond (satisfies? Idable obj) (czlab.basal.core/id obj) (map? obj) (:id obj) :t nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;EOF
[ { "context": ";; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2016 Alejand", "end": 40, "score": 0.9998930096626282, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2016 Alejandro Gómez <alej", "end": 54, "score": 0.9999284744262695, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" }, { "context": "y Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2016 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved.\n;", "end": 98, "score": 0.9998891949653625, "start": 83, "tag": "NAME", "value": "Alejandro Gómez" }, { "context": "i.nz>\n;; Copyright (c) 2014-2016 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 121, "score": 0.9999344348907471, "start": 100, "tag": "EMAIL", "value": "alejandro@dialelo.com" } ]
src/cats/labs/channel.cljc
klausharbo/cats
896
;; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz> ;; Copyright (c) 2014-2016 Alejandro Gómez <alejandro@dialelo.com> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.labs.channel #?(:cljs (:require-macros [cljs.core.async.macros :refer [go go-loop]])) #?(:cljs (:require [cljs.core.async :as a] [cljs.core.async.impl.protocols :as impl] [cats.context :as ctx] [cats.core :as m] [cats.protocols :as p] [cats.util :as util]) :clj (:require [clojure.core.async :refer [go go-loop] :as a] [clojure.core.async.impl.protocols :as impl] [cats.context :as ctx] [cats.core :as m] [cats.protocols :as p] [cats.util :as util]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn with-value "Simple helper that creates a channel and attach an value to it." ([value] (with-value value (a/chan))) ([value ch] (a/put! ch value) ch)) (defn channel? "Return true if a `c` is a channel." [c] (instance? #?(:clj clojure.core.async.impl.channels.ManyToManyChannel :cljs cljs.core.async.impl.channels.ManyToManyChannel) c)) (def ^{:no-doc true} context (reify p/Context p/Functor (-fmap [_ f mv] (a/pipe mv (a/chan 1 (map f)))) p/Semigroup (-mappend [_ sv sv'] (a/merge [sv sv'])) p/Monoid (-mempty [_] (a/to-chan [])) p/Applicative (-pure [_ v] (a/to-chan [(if (nil? v) ::nil v)])) (-fapply [mn af av] (a/map #(%1 %2) [af av])) p/Monad (-mreturn [_ v] (a/to-chan [(if (nil? v) ::nil v)])) (-mbind [it mv f] (let [ctx ctx/*context* out (a/chan) bindf #(binding [ctx/*context* ctx] (f %))] (a/pipeline-async 1 out #(a/pipe (bindf %1) %2) mv) out)) p/MonadZero (-mzero [it] (a/to-chan [])) p/MonadPlus (-mplus [it mv mv'] (a/merge [mv mv'])) p/Printable (-repr [_] "#<Channel>"))) (util/make-printable (type context)) (extend-type #?(:clj clojure.core.async.impl.channels.ManyToManyChannel :cljs cljs.core.async.impl.channels.ManyToManyChannel) p/Contextual (-get-context [_] context))
9878
;; Copyright (c) 2014-2016 <NAME> <<EMAIL>> ;; Copyright (c) 2014-2016 <NAME> <<EMAIL>> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.labs.channel #?(:cljs (:require-macros [cljs.core.async.macros :refer [go go-loop]])) #?(:cljs (:require [cljs.core.async :as a] [cljs.core.async.impl.protocols :as impl] [cats.context :as ctx] [cats.core :as m] [cats.protocols :as p] [cats.util :as util]) :clj (:require [clojure.core.async :refer [go go-loop] :as a] [clojure.core.async.impl.protocols :as impl] [cats.context :as ctx] [cats.core :as m] [cats.protocols :as p] [cats.util :as util]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn with-value "Simple helper that creates a channel and attach an value to it." ([value] (with-value value (a/chan))) ([value ch] (a/put! ch value) ch)) (defn channel? "Return true if a `c` is a channel." [c] (instance? #?(:clj clojure.core.async.impl.channels.ManyToManyChannel :cljs cljs.core.async.impl.channels.ManyToManyChannel) c)) (def ^{:no-doc true} context (reify p/Context p/Functor (-fmap [_ f mv] (a/pipe mv (a/chan 1 (map f)))) p/Semigroup (-mappend [_ sv sv'] (a/merge [sv sv'])) p/Monoid (-mempty [_] (a/to-chan [])) p/Applicative (-pure [_ v] (a/to-chan [(if (nil? v) ::nil v)])) (-fapply [mn af av] (a/map #(%1 %2) [af av])) p/Monad (-mreturn [_ v] (a/to-chan [(if (nil? v) ::nil v)])) (-mbind [it mv f] (let [ctx ctx/*context* out (a/chan) bindf #(binding [ctx/*context* ctx] (f %))] (a/pipeline-async 1 out #(a/pipe (bindf %1) %2) mv) out)) p/MonadZero (-mzero [it] (a/to-chan [])) p/MonadPlus (-mplus [it mv mv'] (a/merge [mv mv'])) p/Printable (-repr [_] "#<Channel>"))) (util/make-printable (type context)) (extend-type #?(:clj clojure.core.async.impl.channels.ManyToManyChannel :cljs cljs.core.async.impl.channels.ManyToManyChannel) p/Contextual (-get-context [_] context))
true
;; Copyright (c) 2014-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; Copyright (c) 2014-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.labs.channel #?(:cljs (:require-macros [cljs.core.async.macros :refer [go go-loop]])) #?(:cljs (:require [cljs.core.async :as a] [cljs.core.async.impl.protocols :as impl] [cats.context :as ctx] [cats.core :as m] [cats.protocols :as p] [cats.util :as util]) :clj (:require [clojure.core.async :refer [go go-loop] :as a] [clojure.core.async.impl.protocols :as impl] [cats.context :as ctx] [cats.core :as m] [cats.protocols :as p] [cats.util :as util]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn with-value "Simple helper that creates a channel and attach an value to it." ([value] (with-value value (a/chan))) ([value ch] (a/put! ch value) ch)) (defn channel? "Return true if a `c` is a channel." [c] (instance? #?(:clj clojure.core.async.impl.channels.ManyToManyChannel :cljs cljs.core.async.impl.channels.ManyToManyChannel) c)) (def ^{:no-doc true} context (reify p/Context p/Functor (-fmap [_ f mv] (a/pipe mv (a/chan 1 (map f)))) p/Semigroup (-mappend [_ sv sv'] (a/merge [sv sv'])) p/Monoid (-mempty [_] (a/to-chan [])) p/Applicative (-pure [_ v] (a/to-chan [(if (nil? v) ::nil v)])) (-fapply [mn af av] (a/map #(%1 %2) [af av])) p/Monad (-mreturn [_ v] (a/to-chan [(if (nil? v) ::nil v)])) (-mbind [it mv f] (let [ctx ctx/*context* out (a/chan) bindf #(binding [ctx/*context* ctx] (f %))] (a/pipeline-async 1 out #(a/pipe (bindf %1) %2) mv) out)) p/MonadZero (-mzero [it] (a/to-chan [])) p/MonadPlus (-mplus [it mv mv'] (a/merge [mv mv'])) p/Printable (-repr [_] "#<Channel>"))) (util/make-printable (type context)) (extend-type #?(:clj clojure.core.async.impl.channels.ManyToManyChannel :cljs cljs.core.async.impl.channels.ManyToManyChannel) p/Contextual (-get-context [_] context))
[ { "context": "d\n {:access-key \"aws-access-key\"\n :secret-key \"aws-secret-key\"\n :endpoint \"http://localhost:8000", "end": 1114, "score": 0.6475479006767273, "start": 1111, "tag": "KEY", "value": "aws" }, { "context": " (try\n (send-command :user/register {:name \"Bob\" :age 33})\n (assert @feedback)\n (assert", "end": 2730, "score": 0.9956986904144287, "start": 2727, "tag": "NAME", "value": "Bob" }, { "context": " 33})\n (assert @feedback)\n (assert (= {\"Bob\" {:name \"Bob\" :age 33}} @users))\n (assert (=", "end": 2789, "score": 0.9925162196159363, "start": 2786, "tag": "NAME", "value": "Bob" }, { "context": "assert @feedback)\n (assert (= {\"Bob\" {:name \"Bob\" :age 33}} @users))\n (assert (= 1 (count (fa", "end": 2802, "score": 0.9976521730422974, "start": 2799, "tag": "NAME", "value": "Bob" }, { "context": " :eventstore))))\n (assert (= {:age 33 :name \"Bob\"} (nippy/thaw (:data (first (far/scan local-cred ", "end": 2922, "score": 0.9990647435188293, "start": 2919, "tag": "NAME", "value": "Bob" } ]
test/cqrs_server/simple_dynamo_test.clj
Yuppiechef/cqrs-server
227
(ns cqrs-server.simple-dynamo-test (:require [schema.core :as s] [clojure.core.async :as a] [clojure.test :refer :all] [clojure.tools.logging :as log] [taoensso.faraday :as far] [taoensso.nippy :as nippy] [cqrs-server.cqrs :as cqrs] [cqrs-server.simple :as simple] [cqrs-server.async :as async] [cqrs-server.dynamo :as dynamo])) ;; Simple testing module (def users (atom {})) ;; Our super lightweight 'database' (defn setup-aggregate-chan [chan] (a/go-loop [] (when-let [msg (a/<! chan)] (doseq [u msg] (swap! users assoc (:name u) u)) (recur)))) (cqrs/install-commands {:user/register {:name s/Str :age s/Int}}) ;; :user/create (defmethod cqrs/process-command :user/register [{:keys [data] :as c}] (if (get @users (:name data)) (cqrs/events c 0 [[:user/register-failed data]]) (cqrs/events c 1 [[:user/registered data]]))) (defmethod cqrs/aggregate-event :user/registered [{:keys [data] :as e}] [{:name (:name data) :age (:age data)}]) ;; Implementation (def local-cred {:access-key "aws-access-key" :secret-key "aws-secret-key" :endpoint "http://localhost:8000" :tablename :eventstore}) (def config {:command-stream (atom nil) :event-stream (atom nil) :aggregator (atom nil) :feedback-stream (atom nil) :channels [:command-stream :event-stream :aggregator :feedback-stream]}) (def catalog-map {:command/in-queue (async/stream :input (:command-stream config)) :event/out-queue (async/stream :output (:event-stream config)) :event/in-queue (async/stream :input (:event-stream config)) :event/store (dynamo/catalog local-cred) :event/aggregator (async/stream :fn (:aggregator config)) :command/feedback (async/stream :output (:feedback-stream config))}) (defn setup-env [] (try (far/delete-table local-cred (:tablename local-cred)) (catch Exception e nil)) (dynamo/table-setup local-cred) (reset! users {}) (doseq [c (:channels config)] (reset! (get config c) (a/chan 10))) (setup-aggregate-chan @(:aggregator config)) (let [setup (cqrs/setup (java.util.UUID/randomUUID) catalog-map)] {:simple (simple/start setup)})) (defn stop-env [env] (doseq [c (:channels config)] (swap! (get config c) (fn [chan] (a/close! chan) nil))) (try (far/delete-table local-cred (:tablename local-cred)) (catch Exception e nil)) true) (defn send-command [type data] (a/>!! @(:command-stream config) (cqrs/command "123" 1 type data))) ;; Requires dynamo local (defn run-test [] (let [env (setup-env) feedback (delay (first (a/alts!! [@(:feedback-stream config) (a/timeout 2000)])))] (try (send-command :user/register {:name "Bob" :age 33}) (assert @feedback) (assert (= {"Bob" {:name "Bob" :age 33}} @users)) (assert (= 1 (count (far/scan local-cred :eventstore)))) (assert (= {:age 33 :name "Bob"} (nippy/thaw (:data (first (far/scan local-cred :eventstore)))))) (finally (stop-env env)))))
17624
(ns cqrs-server.simple-dynamo-test (:require [schema.core :as s] [clojure.core.async :as a] [clojure.test :refer :all] [clojure.tools.logging :as log] [taoensso.faraday :as far] [taoensso.nippy :as nippy] [cqrs-server.cqrs :as cqrs] [cqrs-server.simple :as simple] [cqrs-server.async :as async] [cqrs-server.dynamo :as dynamo])) ;; Simple testing module (def users (atom {})) ;; Our super lightweight 'database' (defn setup-aggregate-chan [chan] (a/go-loop [] (when-let [msg (a/<! chan)] (doseq [u msg] (swap! users assoc (:name u) u)) (recur)))) (cqrs/install-commands {:user/register {:name s/Str :age s/Int}}) ;; :user/create (defmethod cqrs/process-command :user/register [{:keys [data] :as c}] (if (get @users (:name data)) (cqrs/events c 0 [[:user/register-failed data]]) (cqrs/events c 1 [[:user/registered data]]))) (defmethod cqrs/aggregate-event :user/registered [{:keys [data] :as e}] [{:name (:name data) :age (:age data)}]) ;; Implementation (def local-cred {:access-key "aws-access-key" :secret-key "<KEY>-secret-key" :endpoint "http://localhost:8000" :tablename :eventstore}) (def config {:command-stream (atom nil) :event-stream (atom nil) :aggregator (atom nil) :feedback-stream (atom nil) :channels [:command-stream :event-stream :aggregator :feedback-stream]}) (def catalog-map {:command/in-queue (async/stream :input (:command-stream config)) :event/out-queue (async/stream :output (:event-stream config)) :event/in-queue (async/stream :input (:event-stream config)) :event/store (dynamo/catalog local-cred) :event/aggregator (async/stream :fn (:aggregator config)) :command/feedback (async/stream :output (:feedback-stream config))}) (defn setup-env [] (try (far/delete-table local-cred (:tablename local-cred)) (catch Exception e nil)) (dynamo/table-setup local-cred) (reset! users {}) (doseq [c (:channels config)] (reset! (get config c) (a/chan 10))) (setup-aggregate-chan @(:aggregator config)) (let [setup (cqrs/setup (java.util.UUID/randomUUID) catalog-map)] {:simple (simple/start setup)})) (defn stop-env [env] (doseq [c (:channels config)] (swap! (get config c) (fn [chan] (a/close! chan) nil))) (try (far/delete-table local-cred (:tablename local-cred)) (catch Exception e nil)) true) (defn send-command [type data] (a/>!! @(:command-stream config) (cqrs/command "123" 1 type data))) ;; Requires dynamo local (defn run-test [] (let [env (setup-env) feedback (delay (first (a/alts!! [@(:feedback-stream config) (a/timeout 2000)])))] (try (send-command :user/register {:name "<NAME>" :age 33}) (assert @feedback) (assert (= {"<NAME>" {:name "<NAME>" :age 33}} @users)) (assert (= 1 (count (far/scan local-cred :eventstore)))) (assert (= {:age 33 :name "<NAME>"} (nippy/thaw (:data (first (far/scan local-cred :eventstore)))))) (finally (stop-env env)))))
true
(ns cqrs-server.simple-dynamo-test (:require [schema.core :as s] [clojure.core.async :as a] [clojure.test :refer :all] [clojure.tools.logging :as log] [taoensso.faraday :as far] [taoensso.nippy :as nippy] [cqrs-server.cqrs :as cqrs] [cqrs-server.simple :as simple] [cqrs-server.async :as async] [cqrs-server.dynamo :as dynamo])) ;; Simple testing module (def users (atom {})) ;; Our super lightweight 'database' (defn setup-aggregate-chan [chan] (a/go-loop [] (when-let [msg (a/<! chan)] (doseq [u msg] (swap! users assoc (:name u) u)) (recur)))) (cqrs/install-commands {:user/register {:name s/Str :age s/Int}}) ;; :user/create (defmethod cqrs/process-command :user/register [{:keys [data] :as c}] (if (get @users (:name data)) (cqrs/events c 0 [[:user/register-failed data]]) (cqrs/events c 1 [[:user/registered data]]))) (defmethod cqrs/aggregate-event :user/registered [{:keys [data] :as e}] [{:name (:name data) :age (:age data)}]) ;; Implementation (def local-cred {:access-key "aws-access-key" :secret-key "PI:KEY:<KEY>END_PI-secret-key" :endpoint "http://localhost:8000" :tablename :eventstore}) (def config {:command-stream (atom nil) :event-stream (atom nil) :aggregator (atom nil) :feedback-stream (atom nil) :channels [:command-stream :event-stream :aggregator :feedback-stream]}) (def catalog-map {:command/in-queue (async/stream :input (:command-stream config)) :event/out-queue (async/stream :output (:event-stream config)) :event/in-queue (async/stream :input (:event-stream config)) :event/store (dynamo/catalog local-cred) :event/aggregator (async/stream :fn (:aggregator config)) :command/feedback (async/stream :output (:feedback-stream config))}) (defn setup-env [] (try (far/delete-table local-cred (:tablename local-cred)) (catch Exception e nil)) (dynamo/table-setup local-cred) (reset! users {}) (doseq [c (:channels config)] (reset! (get config c) (a/chan 10))) (setup-aggregate-chan @(:aggregator config)) (let [setup (cqrs/setup (java.util.UUID/randomUUID) catalog-map)] {:simple (simple/start setup)})) (defn stop-env [env] (doseq [c (:channels config)] (swap! (get config c) (fn [chan] (a/close! chan) nil))) (try (far/delete-table local-cred (:tablename local-cred)) (catch Exception e nil)) true) (defn send-command [type data] (a/>!! @(:command-stream config) (cqrs/command "123" 1 type data))) ;; Requires dynamo local (defn run-test [] (let [env (setup-env) feedback (delay (first (a/alts!! [@(:feedback-stream config) (a/timeout 2000)])))] (try (send-command :user/register {:name "PI:NAME:<NAME>END_PI" :age 33}) (assert @feedback) (assert (= {"PI:NAME:<NAME>END_PI" {:name "PI:NAME:<NAME>END_PI" :age 33}} @users)) (assert (= 1 (count (far/scan local-cred :eventstore)))) (assert (= {:age 33 :name "PI:NAME:<NAME>END_PI"} (nippy/thaw (:data (first (far/scan local-cred :eventstore)))))) (finally (stop-env env)))))
[ { "context": "os ix flipped pending])\r\n\r\n(def chicken {:name \"Chickn\" :anim-key \"chicken-idle\" :path [[-1 0] [0 1] [1", "end": 103, "score": 0.56037437915802, "start": 100, "tag": "NAME", "value": "ick" } ]
src/main/app/game.cljs
MattRoelle/LD49
0
(ns app.game) (defrecord FarmAnimal [id atype pos ix flipped pending]) (def chicken {:name "Chickn" :anim-key "chicken-idle" :path [[-1 0] [0 1] [1 0] [0 -1]]}) (def chicken2 {:name "Brown Chickn" :anim-key "chicken2-idle" :path [[1 0] [1 0] [-1 0] [-1 0]]}) (def cow {:name "Cow" :anim-key "cow-idle" :path [[0 -1] [0 -1] [1 0] [1 0] [0 1] [0 1] [-1 0] [-1 0]]}) (def pig {:name "Pig" :anim-key "pig-idle" :path [[0 -1] [0 -1] [0 -1] [0 1] [0 1] [0 1]]}) (def animal-types {:chicken chicken :chicken2 chicken2 :cow cow :pig pig}) (defn new-animal [atype] (FarmAnimal. (random-uuid) atype :inv 0 false true)) (defn add-animal-to-inventory [state atype] (assoc state :animals (conj (:animals state) (new-animal atype)))) (defn rotate-vector [v n] (loop [out v c 0] (if (< c n) (recur (concat (rest out) [(first out)]) (inc c)) out))) (defn walk-path ([animal] (walk-path (:path (:atype animal)) (:pos animal) (:ix animal))) ([path origin ix] (let [path (rotate-vector path ix)] (loop [[x y] origin out [[x y] (first path)] ix 0] (let [node (nth path ix) x (+ x (first node)) y (+ y (second node))] (if (< ix (- (count path) 1)) (recur [x y] (apply concat [out [[x y] node]]) (inc ix)) (mapv vec (partition 2 out)))))))) (defn can-place-animal-here [state animal pos] (let [existing-animal (first (filter #(= (:pos %) pos) (:animals state))) walked-path (walk-path (:path (:atype animal)) pos 0) max (- (:sz state) 1) out-of-bounds-tiles (filter (fn [[[x y]]] (or (< x 0) (< y 0) (> x max) (> y max))) walked-path)] (js/console.log "walked-path" (clj->js walked-path)) (and (not existing-animal) (= (count out-of-bounds-tiles) 0)))) (defn get-moving-animal [state] (when-let [moving-animal-id (:moving-animal state)] (when-let [out (first (filter #(= (:id %) moving-animal-id) (:animals state)))] out))) (defn get-animal-by-id-indexed [state id] (first (keep-indexed #(when (= (:id %2) id) [%1 %2]) (:animals state)))) (defn place-animal [state pos] (let [id (:moving-animal state) [ix animal] (get-animal-by-id-indexed state id) is-in-inventory (= (:pos animal) :inv) is-valid-placement (can-place-animal-here state animal pos) can-place (and animal is-in-inventory is-valid-placement)] (if can-place (let [new-state (-> state (assoc :moving-animal nil) (assoc-in [:animals ix] (assoc animal :pos pos))) new-moveable-animals (filter #(= (:pos %) :inv) (:animals new-state))] (if (> (count new-moveable-animals) 0) (assoc new-state :moving-animal (:id (first new-moveable-animals))) new-state)) state))) (defn next-day [state] (let [day (inc (:day state)) level (:level state) rounds (:rounds level) round (get rounds day)] (js/console.log "round" (clj->js round)) (if round (-> state (assoc :day day) (assoc :animals (vec (concat (:animals state) (mapv new-animal (map animal-types round)))))) (assoc state :win true)))) (defn active-animals [state] (filter #(not= :inv (:pos %)) (:animals state))) (defn inv-animals [state] (filter #(= :inv (:pos %)) (:animals state))) (defn animal-get-turn-path [animal] (let [pos (:pos animal) path (:path (:atype animal)) path-ix (:ix animal) x (first pos) y (second pos) delta (nth path path-ix) dx (first delta) dy (second delta) new-pos [(+ x dx) (+ y dy)]] [pos new-pos])) (defn animal-move-along-path [animal path] (let [[sx sy] (first path) [ex ey] (last path)] (FarmAnimal. (:id animal) (:atype animal) [ex ey] (mod (inc (:ix animal)) (count (:path (:atype animal)))) (if (< ex sx) true false) false))) (defn drop-nth [n coll] (keep-indexed #(when (not= %1 n) %2) coll)) (defn get-colliding-animals [animals paths] (let [final-positions (map last paths) reversed-paths (map reverse paths)] (keep-indexed (fn [ix a] (let [p (nth paths ix) final-pos (last p) not-me-final-positions (set (drop-nth ix final-positions)) not-me-rev-paths (set (drop-nth ix reversed-paths))] (when (or ; Two animals have the same final position (some #(= % final-pos) not-me-final-positions) ; Two animals are "swapping" positions (some #(= % p) not-me-rev-paths)) (list a final-pos)))) animals))) (defn simulate [state] (let [animals (active-animals state) paths (map animal-get-turn-path animals) collisions (get-colliding-animals animals paths) new-animals (vec (map-indexed #(animal-move-along-path %2 (nth paths %1)) animals))] (if (> (count collisions) 0) (-> state (assoc :game-over true) (assoc :collisions collisions) (assoc :animals new-animals) (assoc :crazy-animal (first (first collisions)))) (-> state (assoc :animals new-animals)))))
76540
(ns app.game) (defrecord FarmAnimal [id atype pos ix flipped pending]) (def chicken {:name "Ch<NAME>n" :anim-key "chicken-idle" :path [[-1 0] [0 1] [1 0] [0 -1]]}) (def chicken2 {:name "Brown Chickn" :anim-key "chicken2-idle" :path [[1 0] [1 0] [-1 0] [-1 0]]}) (def cow {:name "Cow" :anim-key "cow-idle" :path [[0 -1] [0 -1] [1 0] [1 0] [0 1] [0 1] [-1 0] [-1 0]]}) (def pig {:name "Pig" :anim-key "pig-idle" :path [[0 -1] [0 -1] [0 -1] [0 1] [0 1] [0 1]]}) (def animal-types {:chicken chicken :chicken2 chicken2 :cow cow :pig pig}) (defn new-animal [atype] (FarmAnimal. (random-uuid) atype :inv 0 false true)) (defn add-animal-to-inventory [state atype] (assoc state :animals (conj (:animals state) (new-animal atype)))) (defn rotate-vector [v n] (loop [out v c 0] (if (< c n) (recur (concat (rest out) [(first out)]) (inc c)) out))) (defn walk-path ([animal] (walk-path (:path (:atype animal)) (:pos animal) (:ix animal))) ([path origin ix] (let [path (rotate-vector path ix)] (loop [[x y] origin out [[x y] (first path)] ix 0] (let [node (nth path ix) x (+ x (first node)) y (+ y (second node))] (if (< ix (- (count path) 1)) (recur [x y] (apply concat [out [[x y] node]]) (inc ix)) (mapv vec (partition 2 out)))))))) (defn can-place-animal-here [state animal pos] (let [existing-animal (first (filter #(= (:pos %) pos) (:animals state))) walked-path (walk-path (:path (:atype animal)) pos 0) max (- (:sz state) 1) out-of-bounds-tiles (filter (fn [[[x y]]] (or (< x 0) (< y 0) (> x max) (> y max))) walked-path)] (js/console.log "walked-path" (clj->js walked-path)) (and (not existing-animal) (= (count out-of-bounds-tiles) 0)))) (defn get-moving-animal [state] (when-let [moving-animal-id (:moving-animal state)] (when-let [out (first (filter #(= (:id %) moving-animal-id) (:animals state)))] out))) (defn get-animal-by-id-indexed [state id] (first (keep-indexed #(when (= (:id %2) id) [%1 %2]) (:animals state)))) (defn place-animal [state pos] (let [id (:moving-animal state) [ix animal] (get-animal-by-id-indexed state id) is-in-inventory (= (:pos animal) :inv) is-valid-placement (can-place-animal-here state animal pos) can-place (and animal is-in-inventory is-valid-placement)] (if can-place (let [new-state (-> state (assoc :moving-animal nil) (assoc-in [:animals ix] (assoc animal :pos pos))) new-moveable-animals (filter #(= (:pos %) :inv) (:animals new-state))] (if (> (count new-moveable-animals) 0) (assoc new-state :moving-animal (:id (first new-moveable-animals))) new-state)) state))) (defn next-day [state] (let [day (inc (:day state)) level (:level state) rounds (:rounds level) round (get rounds day)] (js/console.log "round" (clj->js round)) (if round (-> state (assoc :day day) (assoc :animals (vec (concat (:animals state) (mapv new-animal (map animal-types round)))))) (assoc state :win true)))) (defn active-animals [state] (filter #(not= :inv (:pos %)) (:animals state))) (defn inv-animals [state] (filter #(= :inv (:pos %)) (:animals state))) (defn animal-get-turn-path [animal] (let [pos (:pos animal) path (:path (:atype animal)) path-ix (:ix animal) x (first pos) y (second pos) delta (nth path path-ix) dx (first delta) dy (second delta) new-pos [(+ x dx) (+ y dy)]] [pos new-pos])) (defn animal-move-along-path [animal path] (let [[sx sy] (first path) [ex ey] (last path)] (FarmAnimal. (:id animal) (:atype animal) [ex ey] (mod (inc (:ix animal)) (count (:path (:atype animal)))) (if (< ex sx) true false) false))) (defn drop-nth [n coll] (keep-indexed #(when (not= %1 n) %2) coll)) (defn get-colliding-animals [animals paths] (let [final-positions (map last paths) reversed-paths (map reverse paths)] (keep-indexed (fn [ix a] (let [p (nth paths ix) final-pos (last p) not-me-final-positions (set (drop-nth ix final-positions)) not-me-rev-paths (set (drop-nth ix reversed-paths))] (when (or ; Two animals have the same final position (some #(= % final-pos) not-me-final-positions) ; Two animals are "swapping" positions (some #(= % p) not-me-rev-paths)) (list a final-pos)))) animals))) (defn simulate [state] (let [animals (active-animals state) paths (map animal-get-turn-path animals) collisions (get-colliding-animals animals paths) new-animals (vec (map-indexed #(animal-move-along-path %2 (nth paths %1)) animals))] (if (> (count collisions) 0) (-> state (assoc :game-over true) (assoc :collisions collisions) (assoc :animals new-animals) (assoc :crazy-animal (first (first collisions)))) (-> state (assoc :animals new-animals)))))
true
(ns app.game) (defrecord FarmAnimal [id atype pos ix flipped pending]) (def chicken {:name "ChPI:NAME:<NAME>END_PIn" :anim-key "chicken-idle" :path [[-1 0] [0 1] [1 0] [0 -1]]}) (def chicken2 {:name "Brown Chickn" :anim-key "chicken2-idle" :path [[1 0] [1 0] [-1 0] [-1 0]]}) (def cow {:name "Cow" :anim-key "cow-idle" :path [[0 -1] [0 -1] [1 0] [1 0] [0 1] [0 1] [-1 0] [-1 0]]}) (def pig {:name "Pig" :anim-key "pig-idle" :path [[0 -1] [0 -1] [0 -1] [0 1] [0 1] [0 1]]}) (def animal-types {:chicken chicken :chicken2 chicken2 :cow cow :pig pig}) (defn new-animal [atype] (FarmAnimal. (random-uuid) atype :inv 0 false true)) (defn add-animal-to-inventory [state atype] (assoc state :animals (conj (:animals state) (new-animal atype)))) (defn rotate-vector [v n] (loop [out v c 0] (if (< c n) (recur (concat (rest out) [(first out)]) (inc c)) out))) (defn walk-path ([animal] (walk-path (:path (:atype animal)) (:pos animal) (:ix animal))) ([path origin ix] (let [path (rotate-vector path ix)] (loop [[x y] origin out [[x y] (first path)] ix 0] (let [node (nth path ix) x (+ x (first node)) y (+ y (second node))] (if (< ix (- (count path) 1)) (recur [x y] (apply concat [out [[x y] node]]) (inc ix)) (mapv vec (partition 2 out)))))))) (defn can-place-animal-here [state animal pos] (let [existing-animal (first (filter #(= (:pos %) pos) (:animals state))) walked-path (walk-path (:path (:atype animal)) pos 0) max (- (:sz state) 1) out-of-bounds-tiles (filter (fn [[[x y]]] (or (< x 0) (< y 0) (> x max) (> y max))) walked-path)] (js/console.log "walked-path" (clj->js walked-path)) (and (not existing-animal) (= (count out-of-bounds-tiles) 0)))) (defn get-moving-animal [state] (when-let [moving-animal-id (:moving-animal state)] (when-let [out (first (filter #(= (:id %) moving-animal-id) (:animals state)))] out))) (defn get-animal-by-id-indexed [state id] (first (keep-indexed #(when (= (:id %2) id) [%1 %2]) (:animals state)))) (defn place-animal [state pos] (let [id (:moving-animal state) [ix animal] (get-animal-by-id-indexed state id) is-in-inventory (= (:pos animal) :inv) is-valid-placement (can-place-animal-here state animal pos) can-place (and animal is-in-inventory is-valid-placement)] (if can-place (let [new-state (-> state (assoc :moving-animal nil) (assoc-in [:animals ix] (assoc animal :pos pos))) new-moveable-animals (filter #(= (:pos %) :inv) (:animals new-state))] (if (> (count new-moveable-animals) 0) (assoc new-state :moving-animal (:id (first new-moveable-animals))) new-state)) state))) (defn next-day [state] (let [day (inc (:day state)) level (:level state) rounds (:rounds level) round (get rounds day)] (js/console.log "round" (clj->js round)) (if round (-> state (assoc :day day) (assoc :animals (vec (concat (:animals state) (mapv new-animal (map animal-types round)))))) (assoc state :win true)))) (defn active-animals [state] (filter #(not= :inv (:pos %)) (:animals state))) (defn inv-animals [state] (filter #(= :inv (:pos %)) (:animals state))) (defn animal-get-turn-path [animal] (let [pos (:pos animal) path (:path (:atype animal)) path-ix (:ix animal) x (first pos) y (second pos) delta (nth path path-ix) dx (first delta) dy (second delta) new-pos [(+ x dx) (+ y dy)]] [pos new-pos])) (defn animal-move-along-path [animal path] (let [[sx sy] (first path) [ex ey] (last path)] (FarmAnimal. (:id animal) (:atype animal) [ex ey] (mod (inc (:ix animal)) (count (:path (:atype animal)))) (if (< ex sx) true false) false))) (defn drop-nth [n coll] (keep-indexed #(when (not= %1 n) %2) coll)) (defn get-colliding-animals [animals paths] (let [final-positions (map last paths) reversed-paths (map reverse paths)] (keep-indexed (fn [ix a] (let [p (nth paths ix) final-pos (last p) not-me-final-positions (set (drop-nth ix final-positions)) not-me-rev-paths (set (drop-nth ix reversed-paths))] (when (or ; Two animals have the same final position (some #(= % final-pos) not-me-final-positions) ; Two animals are "swapping" positions (some #(= % p) not-me-rev-paths)) (list a final-pos)))) animals))) (defn simulate [state] (let [animals (active-animals state) paths (map animal-get-turn-path animals) collisions (get-colliding-animals animals paths) new-animals (vec (map-indexed #(animal-move-along-path %2 (nth paths %1)) animals))] (if (> (count collisions) 0) (-> state (assoc :game-over true) (assoc :collisions collisions) (assoc :animals new-animals) (assoc :crazy-animal (first (first collisions)))) (-> state (assoc :animals new-animals)))))
[ { "context": " :account-id (:id (find-account ctx \"Medicare\"))\n ", "end": 9239, "score": 0.8626505732536316, "start": 9231, "tag": "NAME", "value": "Medicare" } ]
test/clj_money/models/scheduled_transactions_test.clj
dgknght/clj-money
5
(ns clj-money.models.scheduled-transactions-test (:require [clojure.test :refer [deftest is use-fixtures]] [clj-time.core :as t] [stowaway.core :refer [tag]] [dgknght.app-lib.test] [clj-money.models :as models] [clj-money.test-helpers :refer [reset-db]] [clj-money.test-context :refer [realize find-entity find-account find-accounts find-scheduled-transaction basic-context]] [clj-money.models.scheduled-transactions :as sched-trans] [clj-money.models.transactions :as trans])) (use-fixtures :each reset-db) (def ^:dynamic *attr* ) (defn- create-scheduled-transaction [] (let [result (sched-trans/create *attr*)] [result (sched-trans/search {})])) (defn- comparable [model] (-> model (select-keys (keys *attr*)) (update-in [:items] (fn [items] (mapv #(select-keys % [:action :account-id :quantity]) items))))) (defn- successful-creation [[result retrieved]] (is (map? result) "A map is returned") (is (valid? result)) (is (= ::models/scheduled-transaction (tag result))) (is (:id result) "The returned value has an :id") (is (= *attr* (comparable (first retrieved))) "The record can be retrieved")) (defn- failed-validation ([path artifacts] (failed-validation path nil artifacts)) ([path error [result retrieved]] {:pre [(vector? path)]} (is (map? result) "A map is returned") (is (invalid? result path error)) (is (empty? retrieved) "The record is not created"))) (defn- init-attr [] (let [ctx (realize basic-context) entity (find-entity ctx "Personal") [checking salary] (find-accounts ctx "Checking" "Salary")] {:entity-id (:id entity) :start-date (t/local-date 2021 3 31) :end-date (t/local-date 2022 12 31) :enabled true :date-spec {:day :last} :interval-type :month :interval-count 1 :description "Paycheck" :memo "scheduled" :items [{:action :debit :account-id (:id checking) :quantity 1000M} {:action :credit :account-id (:id salary) :quantity 1000M}]})) (deftest create-a-scheduled-transaction (binding [*attr* (init-attr)] (successful-creation (create-scheduled-transaction)))) (deftest entity-id-is-required (binding [*attr* (dissoc (init-attr) :entity-id)] (failed-validation [:entity-id] "Entity is required" (create-scheduled-transaction)))) (deftest description-is-required (binding [*attr* (dissoc (init-attr) :description)] (failed-validation [:description] "Description is required" (create-scheduled-transaction)))) (deftest interval-type-is-required (binding [*attr* (dissoc (init-attr) :interval-type)] (failed-validation [:interval-type] "Interval type is required" (create-scheduled-transaction)))) (deftest interval-type-can-be-week (binding [*attr* (assoc (init-attr) :interval-type :week)] (successful-creation (create-scheduled-transaction)))) (deftest interval-type-can-be-month (binding [*attr* (assoc (init-attr) :interval-type :month)] (successful-creation (create-scheduled-transaction)))) (deftest interval-type-can-be-year (binding [*attr* (assoc (init-attr) :interval-type :year)] (successful-creation (create-scheduled-transaction)))) (deftest interval-type-cannot-be-off-list (binding [*attr* (assoc (init-attr) :interval-type :not-valid)] (failed-validation [:interval-type] "Interval type must be day, week, month, or year" (create-scheduled-transaction)))) (deftest start-date-is-required (binding [*attr* (dissoc (init-attr) :start-date)] (failed-validation [:start-date] "Start date is required" (create-scheduled-transaction)))) (deftest date-spec-is-required (binding [*attr* (dissoc (init-attr) :date-spec)] (failed-validation [:date-spec] "Date spec is required" (create-scheduled-transaction)))) (deftest interval-count-is-required (binding [*attr* (dissoc (init-attr) :interval-count)] (failed-validation [:interval-count] "Interval count is required" (create-scheduled-transaction)))) (deftest interval-must-be-greater-than-zero (binding [*attr* (assoc (init-attr) :interval-count 0)] (failed-validation [:interval-count] "Interval count must be greater than zero" (create-scheduled-transaction)))) (deftest at-least-two-items-are-required (binding [*attr* (update-in (init-attr) [:items] #(take 1 %))] (failed-validation [:items] "There must be at least two items" (create-scheduled-transaction)))) (deftest sum-of-credits-must-equal-sum-of-debits (binding [*attr* (assoc-in (init-attr) [:items 0 :quantity] 1001M)] (failed-validation [:items] "The sum of debits must equal the sum of credits" (create-scheduled-transaction)))) (deftest item-account-id-is-required (binding [*attr* (update-in (init-attr) [:items 0] dissoc :account-id)] (failed-validation [:items 0 :account-id] "Account is required" (create-scheduled-transaction)))) (deftest item-action-is-required (binding [*attr* (update-in (init-attr) [:items 0] dissoc :action)] (failed-validation [:items 0 :action] "Action is required" (create-scheduled-transaction)))) (deftest item-action-must-be-credit-or-debit (binding [*attr* (assoc-in (init-attr) [:items 0 :action] :not-valid)] (failed-validation [:items 0 :action] "Action must be debit or credit" (create-scheduled-transaction)))) (deftest item-quantity-is-required (binding [*attr* (update-in (init-attr) [:items 0] dissoc :quantity)] (failed-validation [:items 0 :quantity] "Quantity is required" (create-scheduled-transaction)))) (deftest item-quantity-must-be-greater-than-zero (binding [*attr* (assoc-in (init-attr) [:items 0 :quantity] 0M)] (failed-validation [:items 0 :quantity] "Quantity must be greater than zero" (create-scheduled-transaction)))) (def ^:private update-context (assoc basic-context :scheduled-transactions [{:entity-id "Personal" :description "Paycheck" :start-date (t/local-date 2016 1 1) :date-spec {:day 1} :interval-type :month :interval-count 1 :items [{:action :debit :account-id "Checking" :quantity 900M} {:action :debit :account-id "FIT" :quantity 100M} {:action :credit :account-id "Salary" :quantity 1000M}]}])) (defn- update-sched-tran [update-fn] (let [ctx (realize update-context) sched-tran (find-scheduled-transaction ctx "Paycheck") result (-> sched-tran (update-fn ctx) sched-trans/update) retrieved (sched-trans/find sched-tran)] [result retrieved])) (deftest update-a-scheduled-transaction (let [changes {:interval-type :week :interval-count 2} [result retrieved] (update-sched-tran (fn [sched-tran _] (-> sched-tran (merge changes) (assoc-in [:items 0 :quantity] 901M) (assoc-in [:items 2 :quantity] 1001M))))] (is (valid? result)) (is (map? result) "A map is returned") (is (comparable? changes result) "The updated scheduled-transaction is returned") (is (comparable? changes retrieved) "The record is updated in the database") (is (= #{1001M 901M 100M} (->> (:items retrieved) (map :quantity) (into #{}))) "The items are updated in the database."))) (deftest add-an-item (let [[result retrieved] (update-sched-tran (fn [sched-tran ctx] (-> sched-tran (assoc-in [:items 0 :quantity] 850M) (update-in [:items] conj {:action :debit :account-id (:id (find-account ctx "Medicare")) :quantity 50M}))))] (is (valid? result)) (is (= (->> (:items retrieved) (map #(select-keys % [:action :quantity])) set) #{{:action :credit :quantity 1000M} {:action :debit :quantity 850M} {:action :debit :quantity 100M} {:action :debit :quantity 50M}}) "The new item can be retrieved after update"))) (deftest delete-a-scheduled-transaction (let [ctx (realize update-context) sched-tran (find-scheduled-transaction ctx "Paycheck") _ (sched-trans/delete sched-tran) retrieved (sched-trans/find sched-tran)] (is (nil? retrieved) "The record cannot be retrieved after delete"))) (defn- realize-tran [date] (let [ctx (realize update-context) sched-tran (find-scheduled-transaction ctx "Paycheck")] [(t/do-at date (sched-trans/realize sched-tran)) (trans/search {:description "Paycheck" :transaction-date "2016" :entity-id (:entity-id sched-tran)}) (sched-trans/find sched-tran)])) (defn- assert-successful-realization [[result transactions sched-tran]] (is (every? :id result) "The returned values contain an :id") (is (valid? result)) (is (= (:transaction-date (last transactions)) (:last-occurrence sched-tran)) "The scheduled transaction last occurrence is updated") (is (= (:id sched-tran) (-> result first :scheduled-transaction-id)) "The new transaction has the :scheduled-transaction-id") (let [expected {:transaction-date (t/local-date 2016 2 1) :description "Paycheck"}] (= expected (select-keys result (keys expected)) "The created transaction is returned") (= expected (select-keys (first transactions) (keys expected)) "The transaction can be retrieved"))) (deftest realize-a-scheduled-transaction-after-the-date (assert-successful-realization (realize-tran (t/date-time 2016 2 2))))
85845
(ns clj-money.models.scheduled-transactions-test (:require [clojure.test :refer [deftest is use-fixtures]] [clj-time.core :as t] [stowaway.core :refer [tag]] [dgknght.app-lib.test] [clj-money.models :as models] [clj-money.test-helpers :refer [reset-db]] [clj-money.test-context :refer [realize find-entity find-account find-accounts find-scheduled-transaction basic-context]] [clj-money.models.scheduled-transactions :as sched-trans] [clj-money.models.transactions :as trans])) (use-fixtures :each reset-db) (def ^:dynamic *attr* ) (defn- create-scheduled-transaction [] (let [result (sched-trans/create *attr*)] [result (sched-trans/search {})])) (defn- comparable [model] (-> model (select-keys (keys *attr*)) (update-in [:items] (fn [items] (mapv #(select-keys % [:action :account-id :quantity]) items))))) (defn- successful-creation [[result retrieved]] (is (map? result) "A map is returned") (is (valid? result)) (is (= ::models/scheduled-transaction (tag result))) (is (:id result) "The returned value has an :id") (is (= *attr* (comparable (first retrieved))) "The record can be retrieved")) (defn- failed-validation ([path artifacts] (failed-validation path nil artifacts)) ([path error [result retrieved]] {:pre [(vector? path)]} (is (map? result) "A map is returned") (is (invalid? result path error)) (is (empty? retrieved) "The record is not created"))) (defn- init-attr [] (let [ctx (realize basic-context) entity (find-entity ctx "Personal") [checking salary] (find-accounts ctx "Checking" "Salary")] {:entity-id (:id entity) :start-date (t/local-date 2021 3 31) :end-date (t/local-date 2022 12 31) :enabled true :date-spec {:day :last} :interval-type :month :interval-count 1 :description "Paycheck" :memo "scheduled" :items [{:action :debit :account-id (:id checking) :quantity 1000M} {:action :credit :account-id (:id salary) :quantity 1000M}]})) (deftest create-a-scheduled-transaction (binding [*attr* (init-attr)] (successful-creation (create-scheduled-transaction)))) (deftest entity-id-is-required (binding [*attr* (dissoc (init-attr) :entity-id)] (failed-validation [:entity-id] "Entity is required" (create-scheduled-transaction)))) (deftest description-is-required (binding [*attr* (dissoc (init-attr) :description)] (failed-validation [:description] "Description is required" (create-scheduled-transaction)))) (deftest interval-type-is-required (binding [*attr* (dissoc (init-attr) :interval-type)] (failed-validation [:interval-type] "Interval type is required" (create-scheduled-transaction)))) (deftest interval-type-can-be-week (binding [*attr* (assoc (init-attr) :interval-type :week)] (successful-creation (create-scheduled-transaction)))) (deftest interval-type-can-be-month (binding [*attr* (assoc (init-attr) :interval-type :month)] (successful-creation (create-scheduled-transaction)))) (deftest interval-type-can-be-year (binding [*attr* (assoc (init-attr) :interval-type :year)] (successful-creation (create-scheduled-transaction)))) (deftest interval-type-cannot-be-off-list (binding [*attr* (assoc (init-attr) :interval-type :not-valid)] (failed-validation [:interval-type] "Interval type must be day, week, month, or year" (create-scheduled-transaction)))) (deftest start-date-is-required (binding [*attr* (dissoc (init-attr) :start-date)] (failed-validation [:start-date] "Start date is required" (create-scheduled-transaction)))) (deftest date-spec-is-required (binding [*attr* (dissoc (init-attr) :date-spec)] (failed-validation [:date-spec] "Date spec is required" (create-scheduled-transaction)))) (deftest interval-count-is-required (binding [*attr* (dissoc (init-attr) :interval-count)] (failed-validation [:interval-count] "Interval count is required" (create-scheduled-transaction)))) (deftest interval-must-be-greater-than-zero (binding [*attr* (assoc (init-attr) :interval-count 0)] (failed-validation [:interval-count] "Interval count must be greater than zero" (create-scheduled-transaction)))) (deftest at-least-two-items-are-required (binding [*attr* (update-in (init-attr) [:items] #(take 1 %))] (failed-validation [:items] "There must be at least two items" (create-scheduled-transaction)))) (deftest sum-of-credits-must-equal-sum-of-debits (binding [*attr* (assoc-in (init-attr) [:items 0 :quantity] 1001M)] (failed-validation [:items] "The sum of debits must equal the sum of credits" (create-scheduled-transaction)))) (deftest item-account-id-is-required (binding [*attr* (update-in (init-attr) [:items 0] dissoc :account-id)] (failed-validation [:items 0 :account-id] "Account is required" (create-scheduled-transaction)))) (deftest item-action-is-required (binding [*attr* (update-in (init-attr) [:items 0] dissoc :action)] (failed-validation [:items 0 :action] "Action is required" (create-scheduled-transaction)))) (deftest item-action-must-be-credit-or-debit (binding [*attr* (assoc-in (init-attr) [:items 0 :action] :not-valid)] (failed-validation [:items 0 :action] "Action must be debit or credit" (create-scheduled-transaction)))) (deftest item-quantity-is-required (binding [*attr* (update-in (init-attr) [:items 0] dissoc :quantity)] (failed-validation [:items 0 :quantity] "Quantity is required" (create-scheduled-transaction)))) (deftest item-quantity-must-be-greater-than-zero (binding [*attr* (assoc-in (init-attr) [:items 0 :quantity] 0M)] (failed-validation [:items 0 :quantity] "Quantity must be greater than zero" (create-scheduled-transaction)))) (def ^:private update-context (assoc basic-context :scheduled-transactions [{:entity-id "Personal" :description "Paycheck" :start-date (t/local-date 2016 1 1) :date-spec {:day 1} :interval-type :month :interval-count 1 :items [{:action :debit :account-id "Checking" :quantity 900M} {:action :debit :account-id "FIT" :quantity 100M} {:action :credit :account-id "Salary" :quantity 1000M}]}])) (defn- update-sched-tran [update-fn] (let [ctx (realize update-context) sched-tran (find-scheduled-transaction ctx "Paycheck") result (-> sched-tran (update-fn ctx) sched-trans/update) retrieved (sched-trans/find sched-tran)] [result retrieved])) (deftest update-a-scheduled-transaction (let [changes {:interval-type :week :interval-count 2} [result retrieved] (update-sched-tran (fn [sched-tran _] (-> sched-tran (merge changes) (assoc-in [:items 0 :quantity] 901M) (assoc-in [:items 2 :quantity] 1001M))))] (is (valid? result)) (is (map? result) "A map is returned") (is (comparable? changes result) "The updated scheduled-transaction is returned") (is (comparable? changes retrieved) "The record is updated in the database") (is (= #{1001M 901M 100M} (->> (:items retrieved) (map :quantity) (into #{}))) "The items are updated in the database."))) (deftest add-an-item (let [[result retrieved] (update-sched-tran (fn [sched-tran ctx] (-> sched-tran (assoc-in [:items 0 :quantity] 850M) (update-in [:items] conj {:action :debit :account-id (:id (find-account ctx "<NAME>")) :quantity 50M}))))] (is (valid? result)) (is (= (->> (:items retrieved) (map #(select-keys % [:action :quantity])) set) #{{:action :credit :quantity 1000M} {:action :debit :quantity 850M} {:action :debit :quantity 100M} {:action :debit :quantity 50M}}) "The new item can be retrieved after update"))) (deftest delete-a-scheduled-transaction (let [ctx (realize update-context) sched-tran (find-scheduled-transaction ctx "Paycheck") _ (sched-trans/delete sched-tran) retrieved (sched-trans/find sched-tran)] (is (nil? retrieved) "The record cannot be retrieved after delete"))) (defn- realize-tran [date] (let [ctx (realize update-context) sched-tran (find-scheduled-transaction ctx "Paycheck")] [(t/do-at date (sched-trans/realize sched-tran)) (trans/search {:description "Paycheck" :transaction-date "2016" :entity-id (:entity-id sched-tran)}) (sched-trans/find sched-tran)])) (defn- assert-successful-realization [[result transactions sched-tran]] (is (every? :id result) "The returned values contain an :id") (is (valid? result)) (is (= (:transaction-date (last transactions)) (:last-occurrence sched-tran)) "The scheduled transaction last occurrence is updated") (is (= (:id sched-tran) (-> result first :scheduled-transaction-id)) "The new transaction has the :scheduled-transaction-id") (let [expected {:transaction-date (t/local-date 2016 2 1) :description "Paycheck"}] (= expected (select-keys result (keys expected)) "The created transaction is returned") (= expected (select-keys (first transactions) (keys expected)) "The transaction can be retrieved"))) (deftest realize-a-scheduled-transaction-after-the-date (assert-successful-realization (realize-tran (t/date-time 2016 2 2))))
true
(ns clj-money.models.scheduled-transactions-test (:require [clojure.test :refer [deftest is use-fixtures]] [clj-time.core :as t] [stowaway.core :refer [tag]] [dgknght.app-lib.test] [clj-money.models :as models] [clj-money.test-helpers :refer [reset-db]] [clj-money.test-context :refer [realize find-entity find-account find-accounts find-scheduled-transaction basic-context]] [clj-money.models.scheduled-transactions :as sched-trans] [clj-money.models.transactions :as trans])) (use-fixtures :each reset-db) (def ^:dynamic *attr* ) (defn- create-scheduled-transaction [] (let [result (sched-trans/create *attr*)] [result (sched-trans/search {})])) (defn- comparable [model] (-> model (select-keys (keys *attr*)) (update-in [:items] (fn [items] (mapv #(select-keys % [:action :account-id :quantity]) items))))) (defn- successful-creation [[result retrieved]] (is (map? result) "A map is returned") (is (valid? result)) (is (= ::models/scheduled-transaction (tag result))) (is (:id result) "The returned value has an :id") (is (= *attr* (comparable (first retrieved))) "The record can be retrieved")) (defn- failed-validation ([path artifacts] (failed-validation path nil artifacts)) ([path error [result retrieved]] {:pre [(vector? path)]} (is (map? result) "A map is returned") (is (invalid? result path error)) (is (empty? retrieved) "The record is not created"))) (defn- init-attr [] (let [ctx (realize basic-context) entity (find-entity ctx "Personal") [checking salary] (find-accounts ctx "Checking" "Salary")] {:entity-id (:id entity) :start-date (t/local-date 2021 3 31) :end-date (t/local-date 2022 12 31) :enabled true :date-spec {:day :last} :interval-type :month :interval-count 1 :description "Paycheck" :memo "scheduled" :items [{:action :debit :account-id (:id checking) :quantity 1000M} {:action :credit :account-id (:id salary) :quantity 1000M}]})) (deftest create-a-scheduled-transaction (binding [*attr* (init-attr)] (successful-creation (create-scheduled-transaction)))) (deftest entity-id-is-required (binding [*attr* (dissoc (init-attr) :entity-id)] (failed-validation [:entity-id] "Entity is required" (create-scheduled-transaction)))) (deftest description-is-required (binding [*attr* (dissoc (init-attr) :description)] (failed-validation [:description] "Description is required" (create-scheduled-transaction)))) (deftest interval-type-is-required (binding [*attr* (dissoc (init-attr) :interval-type)] (failed-validation [:interval-type] "Interval type is required" (create-scheduled-transaction)))) (deftest interval-type-can-be-week (binding [*attr* (assoc (init-attr) :interval-type :week)] (successful-creation (create-scheduled-transaction)))) (deftest interval-type-can-be-month (binding [*attr* (assoc (init-attr) :interval-type :month)] (successful-creation (create-scheduled-transaction)))) (deftest interval-type-can-be-year (binding [*attr* (assoc (init-attr) :interval-type :year)] (successful-creation (create-scheduled-transaction)))) (deftest interval-type-cannot-be-off-list (binding [*attr* (assoc (init-attr) :interval-type :not-valid)] (failed-validation [:interval-type] "Interval type must be day, week, month, or year" (create-scheduled-transaction)))) (deftest start-date-is-required (binding [*attr* (dissoc (init-attr) :start-date)] (failed-validation [:start-date] "Start date is required" (create-scheduled-transaction)))) (deftest date-spec-is-required (binding [*attr* (dissoc (init-attr) :date-spec)] (failed-validation [:date-spec] "Date spec is required" (create-scheduled-transaction)))) (deftest interval-count-is-required (binding [*attr* (dissoc (init-attr) :interval-count)] (failed-validation [:interval-count] "Interval count is required" (create-scheduled-transaction)))) (deftest interval-must-be-greater-than-zero (binding [*attr* (assoc (init-attr) :interval-count 0)] (failed-validation [:interval-count] "Interval count must be greater than zero" (create-scheduled-transaction)))) (deftest at-least-two-items-are-required (binding [*attr* (update-in (init-attr) [:items] #(take 1 %))] (failed-validation [:items] "There must be at least two items" (create-scheduled-transaction)))) (deftest sum-of-credits-must-equal-sum-of-debits (binding [*attr* (assoc-in (init-attr) [:items 0 :quantity] 1001M)] (failed-validation [:items] "The sum of debits must equal the sum of credits" (create-scheduled-transaction)))) (deftest item-account-id-is-required (binding [*attr* (update-in (init-attr) [:items 0] dissoc :account-id)] (failed-validation [:items 0 :account-id] "Account is required" (create-scheduled-transaction)))) (deftest item-action-is-required (binding [*attr* (update-in (init-attr) [:items 0] dissoc :action)] (failed-validation [:items 0 :action] "Action is required" (create-scheduled-transaction)))) (deftest item-action-must-be-credit-or-debit (binding [*attr* (assoc-in (init-attr) [:items 0 :action] :not-valid)] (failed-validation [:items 0 :action] "Action must be debit or credit" (create-scheduled-transaction)))) (deftest item-quantity-is-required (binding [*attr* (update-in (init-attr) [:items 0] dissoc :quantity)] (failed-validation [:items 0 :quantity] "Quantity is required" (create-scheduled-transaction)))) (deftest item-quantity-must-be-greater-than-zero (binding [*attr* (assoc-in (init-attr) [:items 0 :quantity] 0M)] (failed-validation [:items 0 :quantity] "Quantity must be greater than zero" (create-scheduled-transaction)))) (def ^:private update-context (assoc basic-context :scheduled-transactions [{:entity-id "Personal" :description "Paycheck" :start-date (t/local-date 2016 1 1) :date-spec {:day 1} :interval-type :month :interval-count 1 :items [{:action :debit :account-id "Checking" :quantity 900M} {:action :debit :account-id "FIT" :quantity 100M} {:action :credit :account-id "Salary" :quantity 1000M}]}])) (defn- update-sched-tran [update-fn] (let [ctx (realize update-context) sched-tran (find-scheduled-transaction ctx "Paycheck") result (-> sched-tran (update-fn ctx) sched-trans/update) retrieved (sched-trans/find sched-tran)] [result retrieved])) (deftest update-a-scheduled-transaction (let [changes {:interval-type :week :interval-count 2} [result retrieved] (update-sched-tran (fn [sched-tran _] (-> sched-tran (merge changes) (assoc-in [:items 0 :quantity] 901M) (assoc-in [:items 2 :quantity] 1001M))))] (is (valid? result)) (is (map? result) "A map is returned") (is (comparable? changes result) "The updated scheduled-transaction is returned") (is (comparable? changes retrieved) "The record is updated in the database") (is (= #{1001M 901M 100M} (->> (:items retrieved) (map :quantity) (into #{}))) "The items are updated in the database."))) (deftest add-an-item (let [[result retrieved] (update-sched-tran (fn [sched-tran ctx] (-> sched-tran (assoc-in [:items 0 :quantity] 850M) (update-in [:items] conj {:action :debit :account-id (:id (find-account ctx "PI:NAME:<NAME>END_PI")) :quantity 50M}))))] (is (valid? result)) (is (= (->> (:items retrieved) (map #(select-keys % [:action :quantity])) set) #{{:action :credit :quantity 1000M} {:action :debit :quantity 850M} {:action :debit :quantity 100M} {:action :debit :quantity 50M}}) "The new item can be retrieved after update"))) (deftest delete-a-scheduled-transaction (let [ctx (realize update-context) sched-tran (find-scheduled-transaction ctx "Paycheck") _ (sched-trans/delete sched-tran) retrieved (sched-trans/find sched-tran)] (is (nil? retrieved) "The record cannot be retrieved after delete"))) (defn- realize-tran [date] (let [ctx (realize update-context) sched-tran (find-scheduled-transaction ctx "Paycheck")] [(t/do-at date (sched-trans/realize sched-tran)) (trans/search {:description "Paycheck" :transaction-date "2016" :entity-id (:entity-id sched-tran)}) (sched-trans/find sched-tran)])) (defn- assert-successful-realization [[result transactions sched-tran]] (is (every? :id result) "The returned values contain an :id") (is (valid? result)) (is (= (:transaction-date (last transactions)) (:last-occurrence sched-tran)) "The scheduled transaction last occurrence is updated") (is (= (:id sched-tran) (-> result first :scheduled-transaction-id)) "The new transaction has the :scheduled-transaction-id") (let [expected {:transaction-date (t/local-date 2016 2 1) :description "Paycheck"}] (= expected (select-keys result (keys expected)) "The created transaction is returned") (= expected (select-keys (first transactions) (keys expected)) "The transaction can be retrieved"))) (deftest realize-a-scheduled-transaction-after-the-date (assert-successful-realization (realize-tran (t/date-time 2016 2 2))))
[ { "context": ".\"\n [payload ts key ^String secret]\n (let [key (javax.crypto.spec.SecretKeySpec. (.getBytes secret) \"HmacSHA1\")\n bs (-> (", "end": 7663, "score": 0.6977858543395996, "start": 7632, "tag": "KEY", "value": "javax.crypto.spec.SecretKeySpec" }, { "context": "ax.crypto.spec.SecretKeySpec. (.getBytes secret) \"HmacSHA1\")\n bs (-> (doto (javax.crypto.Mac/getInst", "end": 7693, "score": 0.9280953407287598, "start": 7685, "tag": "KEY", "value": "HmacSHA1" }, { "context": " email\n :ip_address ip-address\n :username username}))\n\n(defn add-user!\n \"Add user information to th", "end": 12638, "score": 0.9745192527770996, "start": 12630, "tag": "USERNAME", "value": "username" }, { "context": "t 'request', as\n defined in https://github.com/ring-clojure/ring/wiki/Concepts#requests\"\n [request]\n {:url ", "end": 14120, "score": 0.9989851117134094, "start": 14108, "tag": "USERNAME", "value": "ring-clojure" } ]
src/raven/client.clj
exoscale/raven
15
(ns raven.client "A netty-based Sentry client." (:import java.lang.Throwable java.lang.Exception) (:require [aleph.http :as http] [manifold.deferred :as d] [jsonista.core :as json] [clojure.string :as str] [clojure.spec.alpha :as s] [clojure.java.shell :as sh] [raven.spec :as spec] [raven.exception :as e] [flatland.useful.utils :as useful]) (:import java.io.Closeable (com.fasterxml.jackson.core JsonGenerator) (com.fasterxml.jackson.databind MapperFeature SerializationFeature))) (def user-agent "Our advertized UA" "exoscale-raven/0.4.4") ;; Make sure we enforce spec assertions. (s/check-asserts true) (def thread-storage "Storage for this particular thread. This is a little funny in that it needs to be dereferenced once in order to obtain an atom that is sure to be per-thread." (useful/thread-local (atom {}))) (def http-requests-payload-stub "Storage for stubbed http 'requests' - actually, we store just the request's payload in clojure form (before it's serialized to JSON)." (atom [])) (defn clear-http-stub "A convenience function to clear the http stub. This stub is only used when passing a DSN of ':memory:' to the lib." [] (swap! http-requests-payload-stub (fn [x] (vector)))) (defn clear-context "Reset this thread's context" [] (reset! @thread-storage {})) (defn sentry-uuid! "A random UUID, without dashes" [] (str/replace (str (java.util.UUID/randomUUID)) "-" "")) (def hostname-refresh-interval "How often to allow reading /etc/hostname, in seconds." 60) (defn get-hostname "Get the current hostname by shelling out to 'hostname'" [] (or (try (let [{:keys [exit out]} (sh/sh "hostname")] (if (= exit 0) (str/trim out))) (catch Exception _)) "<unknown>")) (defn hostname "Fetches the hostname by shelling to 'hostname', whenever the given age is stale enough. If the given age is recent, as defined by hostname-refresh-interval, returns age and val instead." [[age val]] (if (and val (<= (* 1000 hostname-refresh-interval) (- (System/currentTimeMillis) age))) [age val] [(System/currentTimeMillis) (get-hostname)])) (let [cache (atom [nil nil])] (defn localhost "Returns the local host name." [] (if (re-find #"^Windows" (System/getProperty "os.name")) (or (System/getenv "COMPUTERNAME") "localhost") (or (System/getenv "HOSTNAME") (second (swap! cache hostname)))))) (def dsn-pattern "The shape of a sentry DSN" #"^(https?)://([^:]*):([^@]*)@(.*)/([0-9]+)$") (defn parse-dsn "Extract DSN parameters into a map" [dsn] (if-let [[_ proto key secret uri ^String pid] (re-find dsn-pattern dsn)] {:key key :secret secret :uri (format "%s://%s" proto uri) :pid (Long. pid)} (throw (ex-info "could not parse sentry DSN" {:dsn dsn})))) (defn default-payload "Provide default values for a payload." [ts localhost] {:level "error" :server_name localhost :timestamp ts :platform "java"}) (defn auth-header "Compute the Sentry auth header." [ts key sig] (let [params [[:version "2.0"] [:signature sig] [:timestamp ts] [:client user-agent] [:key key]] param (fn [[k v]] (format "sentry_%s=%s" (name k) v))] (str "Sentry " (str/join ", " (map param params))))) (defn merged-payload "Return a payload map depending on the type of the event." [event ts localhost] (merge (default-payload ts localhost) (cond (map? event) event (e/exception? event) (e/exception->ev event) :else {:message (str event)}))) (defn add-breadcrumbs-to-payload [context payload] (let [breadcrumbs-list (or (:breadcrumbs payload) (:breadcrumbs context))] (cond-> payload (seq breadcrumbs-list) (assoc :breadcrumbs {:values breadcrumbs-list})))) (defn add-user-to-payload [context payload] (cond-> payload (:user context) (assoc :user (:user context)))) (defn add-http-info-to-payload [context payload] (cond-> payload (:request context) (assoc :request (:request context)))) (defn slurp-pretty-name [path] (try (last (re-find #"PRETTY_NAME=\"(.*)\"" (slurp path))) (catch Exception _))) (defn get-linux-pretty-name "Get the Linux distribution pretty name from /etc/os-release resp. /usr/lib/os-release." [] (or (slurp-pretty-name "/etc/os-release") (slurp-pretty-name "/usr/lib/os-release") "Unknown Linux")) (let [cache (atom nil)] ;; cache version forever (defn get-os-name-linux "Get a human-readable name for the current linux distribution from /etc/os-release, caching the output" [] (or @cache (swap! cache (constantly (get-linux-pretty-name)))))) (defn get-os-context [] (let [os-name (System/getProperty "os.name") os-version (System/getProperty "os.version")] (if (re-find #"^Linux" os-name) {:name os-name :version (get-os-name-linux) :kernel_version os-version} {:name os-name :version os-version}))) (defn get-contexts [] {:java {:name (System/getProperty "java.vendor") :version (System/getProperty "java.version")} :os (get-os-context) :clojure {:name "clojure" :version (clojure-version)}}) (defn add-contexts-to-payload "Add relevant bits of sentry.interfaces.Contexts to our payload." [payload] (assoc payload :contexts (get-contexts))) (defn add-fingerprint-to-payload "If the context provides a fingerprint override entry, pass it to the payload." [context payload] (cond-> payload (:fingerprint context) (assoc :fingerprint (:fingerprint context)))) (defn add-tags-to-payload "If the context provides tags or we were given tags directly during capture!, ad them to the payload. Tags provided by capture! override tags provided by the context map." [context payload tags] (let [merged (merge (:tags context) tags)] (cond-> payload (not (empty? merged)) (assoc :tags merged)))) (defn add-uuid-to-payload [context payload] (assoc payload :event_id (:event_id context (:event_id payload (sentry-uuid!))))) (defn validate-payload "Returns a validated payload." [merged] (s/assert :raven.spec/payload merged)) (defn payload "Build a full valid payload." [context event ts localhost tags] (let [breadcrumbs-adder (partial add-breadcrumbs-to-payload context) user-adder (partial add-user-to-payload context) http-info-adder (partial add-http-info-to-payload context) fingerprint-adder (partial add-fingerprint-to-payload context) tags-adder (partial add-tags-to-payload context) uuid-adder (partial add-uuid-to-payload context)] (-> (merged-payload event ts localhost) (uuid-adder) (breadcrumbs-adder) (user-adder) (fingerprint-adder) (http-info-adder) (tags-adder tags) (add-contexts-to-payload) (validate-payload)))) (defn timestamp! "Retrieve a timestamp. The format used is the same as python's 'time.time()' function - the number of seconds since the epoch, as a double to acount for fractional seconds (since the granularity is miliseconds)." [] (double (/ (System/currentTimeMillis) 1000))) (defn sign "HMAC-SHA1 for Sentry's format." [payload ts key ^String secret] (let [key (javax.crypto.spec.SecretKeySpec. (.getBytes secret) "HmacSHA1") bs (-> (doto (javax.crypto.Mac/getInstance "HmacSHA1") (.init key) (.update (.getBytes (str ts))) (.update (.getBytes " "))) (.doFinal payload))] (reduce str (for [b bs] (format "%02x" b))))) (defn perform-in-memory-request "Perform an in-memory pseudo-request, actually just storing the payload on a storage atom, to let users inspect/retrieve the payload in their tests." [payload] (swap! http-requests-payload-stub conj payload)) (defrecord SafeMap []) (defmethod clojure.core/print-method SafeMap [m ^java.io.Writer writer] (.write writer (format "#exoscale/safe-map [%s]" (str/join " " (keys m))))) (def safe-map "Wraps map into SafeMap record, effectively hidding values from json output, will not allow 2-way roundtrip. ex: (safe-map {:a 1}) -> \"#exoscale/safe-map [:a]\". Can be used to hide secrets and/or shorten large/deep maps" map->SafeMap) (def json-mapper (doto (json/object-mapper {:encoders {SafeMap (fn [x ^JsonGenerator jg] (.writeString jg (pr-str x)))}}) (.configure SerializationFeature/FAIL_ON_EMPTY_BEANS false) (.configure MapperFeature/AUTO_DETECT_GETTERS false) (.configure MapperFeature/AUTO_DETECT_IS_GETTERS false) (.configure MapperFeature/AUTO_DETECT_SETTERS false) (.configure MapperFeature/AUTO_DETECT_FIELDS false) (.configure MapperFeature/DEFAULT_VIEW_INCLUSION false))) (def closable? (partial instance? Closeable)) (defn close-http-connection " When having a connection pool set, the body cannot be closed as it's of a different type. " [response] (let [{:keys [body]} response] (when (closable? body) (.close ^Closeable body)))) (defn re-throw-response " Throw the response in case of its status was not 2xx as we don't want Sentry errors to be unnoticed. " [response] (let [{:keys [status]} response] (when-not (-> status str first (= \2)) (throw (ex-info (format "Sentry HTTP error") response))))) (defn perform-http-request [context dsn ts payload] (let [json-payload (json/write-value-as-bytes payload json-mapper) {:keys [key secret uri]} (parse-dsn dsn) sig (sign json-payload ts key secret)] (d/chain (http/post (str uri "/api/store/") (merge (select-keys context [:pool :middleware :pool-timeout :response-executor :request-timeout :read-timeout :connection-timeout]) {:headers {:x-sentry-auth (auth-header ts key sig) :accept "application/json" :content-type "application/json;charset=utf-8"} :body json-payload :throw-exceptions? false})) (fn [response] (close-http-connection response) (re-throw-response response))))) (defn capture! "Send a capture over the network. If `ev` is an exception, build an appropriate payload for the exception." ([context dsn event tags] (let [ts (timestamp!) payload (payload context event ts (localhost) tags) uuid (:event_id payload)] (d/chain (if (= dsn ":memory:") (perform-in-memory-request payload) (perform-http-request context dsn ts payload)) (fn [_] (clear-context) uuid)))) ([dsn ev tags] (capture! @@thread-storage dsn ev tags)) ([dsn ev] (capture! @@thread-storage dsn ev {}))) (defn make-breadcrumb! "Create a breadcrumb map. level can be one of: ['debug' 'info' 'warning' 'warn' 'error' 'exception' 'critical' 'fatal']" ([message category] (make-breadcrumb! message category "info")) ([message category level] (make-breadcrumb! message category level (timestamp!))) ([message category level timestamp] {:type "default" ;; TODO: Extend to support more than just default breadcrumbs. :timestamp timestamp :level level :message message :category category}) ;; :data (expected in case of non-default) ) (defn add-breadcrumb! "Append a breadcrumb to the list of breadcrumbs. The context is expected to be a map, and if no context is specified, a thread-local storage map will be used instead. " ([breadcrumb] ;; We need to dereference to get the atom since "thread-storage" is thread-local. (swap! @thread-storage add-breadcrumb! breadcrumb)) ([context breadcrumb] ;; We add the breadcrumb to the context instead, in a ":breadcrumb" key. (update context :breadcrumbs conj (s/assert :raven.spec/breadcrumb breadcrumb)))) (defn make-user "Create a user map." ([id] {:id id}) ([id email ip-address username] {:id id :email email :ip_address ip-address :username username})) (defn add-user! "Add user information to the sentry context (or a thread-local storage)." ([user] (swap! @thread-storage add-user! user)) ([context user] (assoc context :user (s/assert :raven.spec/user user)))) (defn make-http-info ([url method] {:url url :method method}) ([url method headers query_string cookies data env] {:url url :method method :headers headers :query_string query_string :cookies cookies :data data :env env})) (defn get-full-ring-url "Given a ring compliant request object, return the full URL. This was lifted from ring's source code so as to not depend on it." [request] (str (-> request :scheme name) "://" (get-in request [:headers "host"]) (:uri request) (when-let [query (:query-string request)] (str "?" query)))) (defn get-ring-env [request] (cond-> {:REMOTE_ADDR (:remote-addr request) :websocket? (:websocket? request) :route-params (:route-params request)} (some? (:compojure/route request)) (assoc :compojure/route (:compojure/route request)) (some? (:route request)) (assoc :bidi/route (get-in request [:route :handler])))) (defn make-ring-request-info "Create well-formatted context map for the Sentry 'HTTP' interface by extracting the information from a standard ring-compliant 'request', as defined in https://github.com/ring-clojure/ring/wiki/Concepts#requests" [request] {:url (get-full-ring-url request) :method (:request-method request) :cookies (get-in request [:headers "cookie"]) :headers (:headers request) :query_string (:query-string request) :env (get-ring-env request) :data (:body request)}) (defn add-http-info! "Add HTTP information to the sentry context (or a thread-local storage)." ([http-info] (swap! @thread-storage add-http-info! http-info)) ([context http-info] (assoc context :request (s/assert :raven.spec/request http-info)))) (defn add-ring-request! "Add HTTP information to the Sentry payload from a ring-compliant request map, excluding its body." ([request] (add-http-info! (make-ring-request-info (dissoc request :body)))) ([context request] (add-http-info! context (make-ring-request-info (dissoc request :body))))) (defn add-full-ring-request! "Add HTTP information to the Sentry payload from a ring-compliant request map, including the request body" ([request] (add-http-info! (make-ring-request-info request))) ([context request] (add-http-info! context (make-ring-request-info request)))) (defn add-fingerprint! "Add a custom fingerprint to the context (or a thread-local storage)." ([fingerprint] (swap! @thread-storage add-fingerprint! fingerprint)) ([context fingerprint] (assoc context :fingerprint (s/assert :raven.spec/fingerprint fingerprint)))) (defn add-tag! "Add a custom tag to the context (or a thread-local storage)." ([tag value] (swap! @thread-storage add-tag! tag value)) ([context tag value] (assoc-in context [:tags tag] value))) (defn add-tags! "Add custom tags to the context (or a thread-local storage)." ([tags] (swap! @thread-storage add-tags! tags)) ([context tags] (reduce-kv add-tag! context tags))) (defn add-extra! "Add a map of extra data to the context (or a thread-local storage) preserving its previous keys." ([extra] (swap! @thread-storage add-extra! extra)) ([context extra] (update context :extra merge extra))) (defn add-exception! "Add an exception to the context (or a thread-local storage)." ([^Throwable e] (swap! @thread-storage add-exception! e)) ([context ^Throwable e] (let [env (e/exception->ev e)] (-> context (merge (dissoc env :extra)) (add-extra! (:extra env)))))) (defn release! "Release new application version with provided webhook release URL." [webhook-endpoint payload] (if (some? (:version payload)) (http/post webhook-endpoint {:headers {:content-type "application/json"} :body (json/write-value-as-bytes payload)}) (throw (ex-info "no version key provided" {:payload payload}))))
51791
(ns raven.client "A netty-based Sentry client." (:import java.lang.Throwable java.lang.Exception) (:require [aleph.http :as http] [manifold.deferred :as d] [jsonista.core :as json] [clojure.string :as str] [clojure.spec.alpha :as s] [clojure.java.shell :as sh] [raven.spec :as spec] [raven.exception :as e] [flatland.useful.utils :as useful]) (:import java.io.Closeable (com.fasterxml.jackson.core JsonGenerator) (com.fasterxml.jackson.databind MapperFeature SerializationFeature))) (def user-agent "Our advertized UA" "exoscale-raven/0.4.4") ;; Make sure we enforce spec assertions. (s/check-asserts true) (def thread-storage "Storage for this particular thread. This is a little funny in that it needs to be dereferenced once in order to obtain an atom that is sure to be per-thread." (useful/thread-local (atom {}))) (def http-requests-payload-stub "Storage for stubbed http 'requests' - actually, we store just the request's payload in clojure form (before it's serialized to JSON)." (atom [])) (defn clear-http-stub "A convenience function to clear the http stub. This stub is only used when passing a DSN of ':memory:' to the lib." [] (swap! http-requests-payload-stub (fn [x] (vector)))) (defn clear-context "Reset this thread's context" [] (reset! @thread-storage {})) (defn sentry-uuid! "A random UUID, without dashes" [] (str/replace (str (java.util.UUID/randomUUID)) "-" "")) (def hostname-refresh-interval "How often to allow reading /etc/hostname, in seconds." 60) (defn get-hostname "Get the current hostname by shelling out to 'hostname'" [] (or (try (let [{:keys [exit out]} (sh/sh "hostname")] (if (= exit 0) (str/trim out))) (catch Exception _)) "<unknown>")) (defn hostname "Fetches the hostname by shelling to 'hostname', whenever the given age is stale enough. If the given age is recent, as defined by hostname-refresh-interval, returns age and val instead." [[age val]] (if (and val (<= (* 1000 hostname-refresh-interval) (- (System/currentTimeMillis) age))) [age val] [(System/currentTimeMillis) (get-hostname)])) (let [cache (atom [nil nil])] (defn localhost "Returns the local host name." [] (if (re-find #"^Windows" (System/getProperty "os.name")) (or (System/getenv "COMPUTERNAME") "localhost") (or (System/getenv "HOSTNAME") (second (swap! cache hostname)))))) (def dsn-pattern "The shape of a sentry DSN" #"^(https?)://([^:]*):([^@]*)@(.*)/([0-9]+)$") (defn parse-dsn "Extract DSN parameters into a map" [dsn] (if-let [[_ proto key secret uri ^String pid] (re-find dsn-pattern dsn)] {:key key :secret secret :uri (format "%s://%s" proto uri) :pid (Long. pid)} (throw (ex-info "could not parse sentry DSN" {:dsn dsn})))) (defn default-payload "Provide default values for a payload." [ts localhost] {:level "error" :server_name localhost :timestamp ts :platform "java"}) (defn auth-header "Compute the Sentry auth header." [ts key sig] (let [params [[:version "2.0"] [:signature sig] [:timestamp ts] [:client user-agent] [:key key]] param (fn [[k v]] (format "sentry_%s=%s" (name k) v))] (str "Sentry " (str/join ", " (map param params))))) (defn merged-payload "Return a payload map depending on the type of the event." [event ts localhost] (merge (default-payload ts localhost) (cond (map? event) event (e/exception? event) (e/exception->ev event) :else {:message (str event)}))) (defn add-breadcrumbs-to-payload [context payload] (let [breadcrumbs-list (or (:breadcrumbs payload) (:breadcrumbs context))] (cond-> payload (seq breadcrumbs-list) (assoc :breadcrumbs {:values breadcrumbs-list})))) (defn add-user-to-payload [context payload] (cond-> payload (:user context) (assoc :user (:user context)))) (defn add-http-info-to-payload [context payload] (cond-> payload (:request context) (assoc :request (:request context)))) (defn slurp-pretty-name [path] (try (last (re-find #"PRETTY_NAME=\"(.*)\"" (slurp path))) (catch Exception _))) (defn get-linux-pretty-name "Get the Linux distribution pretty name from /etc/os-release resp. /usr/lib/os-release." [] (or (slurp-pretty-name "/etc/os-release") (slurp-pretty-name "/usr/lib/os-release") "Unknown Linux")) (let [cache (atom nil)] ;; cache version forever (defn get-os-name-linux "Get a human-readable name for the current linux distribution from /etc/os-release, caching the output" [] (or @cache (swap! cache (constantly (get-linux-pretty-name)))))) (defn get-os-context [] (let [os-name (System/getProperty "os.name") os-version (System/getProperty "os.version")] (if (re-find #"^Linux" os-name) {:name os-name :version (get-os-name-linux) :kernel_version os-version} {:name os-name :version os-version}))) (defn get-contexts [] {:java {:name (System/getProperty "java.vendor") :version (System/getProperty "java.version")} :os (get-os-context) :clojure {:name "clojure" :version (clojure-version)}}) (defn add-contexts-to-payload "Add relevant bits of sentry.interfaces.Contexts to our payload." [payload] (assoc payload :contexts (get-contexts))) (defn add-fingerprint-to-payload "If the context provides a fingerprint override entry, pass it to the payload." [context payload] (cond-> payload (:fingerprint context) (assoc :fingerprint (:fingerprint context)))) (defn add-tags-to-payload "If the context provides tags or we were given tags directly during capture!, ad them to the payload. Tags provided by capture! override tags provided by the context map." [context payload tags] (let [merged (merge (:tags context) tags)] (cond-> payload (not (empty? merged)) (assoc :tags merged)))) (defn add-uuid-to-payload [context payload] (assoc payload :event_id (:event_id context (:event_id payload (sentry-uuid!))))) (defn validate-payload "Returns a validated payload." [merged] (s/assert :raven.spec/payload merged)) (defn payload "Build a full valid payload." [context event ts localhost tags] (let [breadcrumbs-adder (partial add-breadcrumbs-to-payload context) user-adder (partial add-user-to-payload context) http-info-adder (partial add-http-info-to-payload context) fingerprint-adder (partial add-fingerprint-to-payload context) tags-adder (partial add-tags-to-payload context) uuid-adder (partial add-uuid-to-payload context)] (-> (merged-payload event ts localhost) (uuid-adder) (breadcrumbs-adder) (user-adder) (fingerprint-adder) (http-info-adder) (tags-adder tags) (add-contexts-to-payload) (validate-payload)))) (defn timestamp! "Retrieve a timestamp. The format used is the same as python's 'time.time()' function - the number of seconds since the epoch, as a double to acount for fractional seconds (since the granularity is miliseconds)." [] (double (/ (System/currentTimeMillis) 1000))) (defn sign "HMAC-SHA1 for Sentry's format." [payload ts key ^String secret] (let [key (<KEY>. (.getBytes secret) "<KEY>") bs (-> (doto (javax.crypto.Mac/getInstance "HmacSHA1") (.init key) (.update (.getBytes (str ts))) (.update (.getBytes " "))) (.doFinal payload))] (reduce str (for [b bs] (format "%02x" b))))) (defn perform-in-memory-request "Perform an in-memory pseudo-request, actually just storing the payload on a storage atom, to let users inspect/retrieve the payload in their tests." [payload] (swap! http-requests-payload-stub conj payload)) (defrecord SafeMap []) (defmethod clojure.core/print-method SafeMap [m ^java.io.Writer writer] (.write writer (format "#exoscale/safe-map [%s]" (str/join " " (keys m))))) (def safe-map "Wraps map into SafeMap record, effectively hidding values from json output, will not allow 2-way roundtrip. ex: (safe-map {:a 1}) -> \"#exoscale/safe-map [:a]\". Can be used to hide secrets and/or shorten large/deep maps" map->SafeMap) (def json-mapper (doto (json/object-mapper {:encoders {SafeMap (fn [x ^JsonGenerator jg] (.writeString jg (pr-str x)))}}) (.configure SerializationFeature/FAIL_ON_EMPTY_BEANS false) (.configure MapperFeature/AUTO_DETECT_GETTERS false) (.configure MapperFeature/AUTO_DETECT_IS_GETTERS false) (.configure MapperFeature/AUTO_DETECT_SETTERS false) (.configure MapperFeature/AUTO_DETECT_FIELDS false) (.configure MapperFeature/DEFAULT_VIEW_INCLUSION false))) (def closable? (partial instance? Closeable)) (defn close-http-connection " When having a connection pool set, the body cannot be closed as it's of a different type. " [response] (let [{:keys [body]} response] (when (closable? body) (.close ^Closeable body)))) (defn re-throw-response " Throw the response in case of its status was not 2xx as we don't want Sentry errors to be unnoticed. " [response] (let [{:keys [status]} response] (when-not (-> status str first (= \2)) (throw (ex-info (format "Sentry HTTP error") response))))) (defn perform-http-request [context dsn ts payload] (let [json-payload (json/write-value-as-bytes payload json-mapper) {:keys [key secret uri]} (parse-dsn dsn) sig (sign json-payload ts key secret)] (d/chain (http/post (str uri "/api/store/") (merge (select-keys context [:pool :middleware :pool-timeout :response-executor :request-timeout :read-timeout :connection-timeout]) {:headers {:x-sentry-auth (auth-header ts key sig) :accept "application/json" :content-type "application/json;charset=utf-8"} :body json-payload :throw-exceptions? false})) (fn [response] (close-http-connection response) (re-throw-response response))))) (defn capture! "Send a capture over the network. If `ev` is an exception, build an appropriate payload for the exception." ([context dsn event tags] (let [ts (timestamp!) payload (payload context event ts (localhost) tags) uuid (:event_id payload)] (d/chain (if (= dsn ":memory:") (perform-in-memory-request payload) (perform-http-request context dsn ts payload)) (fn [_] (clear-context) uuid)))) ([dsn ev tags] (capture! @@thread-storage dsn ev tags)) ([dsn ev] (capture! @@thread-storage dsn ev {}))) (defn make-breadcrumb! "Create a breadcrumb map. level can be one of: ['debug' 'info' 'warning' 'warn' 'error' 'exception' 'critical' 'fatal']" ([message category] (make-breadcrumb! message category "info")) ([message category level] (make-breadcrumb! message category level (timestamp!))) ([message category level timestamp] {:type "default" ;; TODO: Extend to support more than just default breadcrumbs. :timestamp timestamp :level level :message message :category category}) ;; :data (expected in case of non-default) ) (defn add-breadcrumb! "Append a breadcrumb to the list of breadcrumbs. The context is expected to be a map, and if no context is specified, a thread-local storage map will be used instead. " ([breadcrumb] ;; We need to dereference to get the atom since "thread-storage" is thread-local. (swap! @thread-storage add-breadcrumb! breadcrumb)) ([context breadcrumb] ;; We add the breadcrumb to the context instead, in a ":breadcrumb" key. (update context :breadcrumbs conj (s/assert :raven.spec/breadcrumb breadcrumb)))) (defn make-user "Create a user map." ([id] {:id id}) ([id email ip-address username] {:id id :email email :ip_address ip-address :username username})) (defn add-user! "Add user information to the sentry context (or a thread-local storage)." ([user] (swap! @thread-storage add-user! user)) ([context user] (assoc context :user (s/assert :raven.spec/user user)))) (defn make-http-info ([url method] {:url url :method method}) ([url method headers query_string cookies data env] {:url url :method method :headers headers :query_string query_string :cookies cookies :data data :env env})) (defn get-full-ring-url "Given a ring compliant request object, return the full URL. This was lifted from ring's source code so as to not depend on it." [request] (str (-> request :scheme name) "://" (get-in request [:headers "host"]) (:uri request) (when-let [query (:query-string request)] (str "?" query)))) (defn get-ring-env [request] (cond-> {:REMOTE_ADDR (:remote-addr request) :websocket? (:websocket? request) :route-params (:route-params request)} (some? (:compojure/route request)) (assoc :compojure/route (:compojure/route request)) (some? (:route request)) (assoc :bidi/route (get-in request [:route :handler])))) (defn make-ring-request-info "Create well-formatted context map for the Sentry 'HTTP' interface by extracting the information from a standard ring-compliant 'request', as defined in https://github.com/ring-clojure/ring/wiki/Concepts#requests" [request] {:url (get-full-ring-url request) :method (:request-method request) :cookies (get-in request [:headers "cookie"]) :headers (:headers request) :query_string (:query-string request) :env (get-ring-env request) :data (:body request)}) (defn add-http-info! "Add HTTP information to the sentry context (or a thread-local storage)." ([http-info] (swap! @thread-storage add-http-info! http-info)) ([context http-info] (assoc context :request (s/assert :raven.spec/request http-info)))) (defn add-ring-request! "Add HTTP information to the Sentry payload from a ring-compliant request map, excluding its body." ([request] (add-http-info! (make-ring-request-info (dissoc request :body)))) ([context request] (add-http-info! context (make-ring-request-info (dissoc request :body))))) (defn add-full-ring-request! "Add HTTP information to the Sentry payload from a ring-compliant request map, including the request body" ([request] (add-http-info! (make-ring-request-info request))) ([context request] (add-http-info! context (make-ring-request-info request)))) (defn add-fingerprint! "Add a custom fingerprint to the context (or a thread-local storage)." ([fingerprint] (swap! @thread-storage add-fingerprint! fingerprint)) ([context fingerprint] (assoc context :fingerprint (s/assert :raven.spec/fingerprint fingerprint)))) (defn add-tag! "Add a custom tag to the context (or a thread-local storage)." ([tag value] (swap! @thread-storage add-tag! tag value)) ([context tag value] (assoc-in context [:tags tag] value))) (defn add-tags! "Add custom tags to the context (or a thread-local storage)." ([tags] (swap! @thread-storage add-tags! tags)) ([context tags] (reduce-kv add-tag! context tags))) (defn add-extra! "Add a map of extra data to the context (or a thread-local storage) preserving its previous keys." ([extra] (swap! @thread-storage add-extra! extra)) ([context extra] (update context :extra merge extra))) (defn add-exception! "Add an exception to the context (or a thread-local storage)." ([^Throwable e] (swap! @thread-storage add-exception! e)) ([context ^Throwable e] (let [env (e/exception->ev e)] (-> context (merge (dissoc env :extra)) (add-extra! (:extra env)))))) (defn release! "Release new application version with provided webhook release URL." [webhook-endpoint payload] (if (some? (:version payload)) (http/post webhook-endpoint {:headers {:content-type "application/json"} :body (json/write-value-as-bytes payload)}) (throw (ex-info "no version key provided" {:payload payload}))))
true
(ns raven.client "A netty-based Sentry client." (:import java.lang.Throwable java.lang.Exception) (:require [aleph.http :as http] [manifold.deferred :as d] [jsonista.core :as json] [clojure.string :as str] [clojure.spec.alpha :as s] [clojure.java.shell :as sh] [raven.spec :as spec] [raven.exception :as e] [flatland.useful.utils :as useful]) (:import java.io.Closeable (com.fasterxml.jackson.core JsonGenerator) (com.fasterxml.jackson.databind MapperFeature SerializationFeature))) (def user-agent "Our advertized UA" "exoscale-raven/0.4.4") ;; Make sure we enforce spec assertions. (s/check-asserts true) (def thread-storage "Storage for this particular thread. This is a little funny in that it needs to be dereferenced once in order to obtain an atom that is sure to be per-thread." (useful/thread-local (atom {}))) (def http-requests-payload-stub "Storage for stubbed http 'requests' - actually, we store just the request's payload in clojure form (before it's serialized to JSON)." (atom [])) (defn clear-http-stub "A convenience function to clear the http stub. This stub is only used when passing a DSN of ':memory:' to the lib." [] (swap! http-requests-payload-stub (fn [x] (vector)))) (defn clear-context "Reset this thread's context" [] (reset! @thread-storage {})) (defn sentry-uuid! "A random UUID, without dashes" [] (str/replace (str (java.util.UUID/randomUUID)) "-" "")) (def hostname-refresh-interval "How often to allow reading /etc/hostname, in seconds." 60) (defn get-hostname "Get the current hostname by shelling out to 'hostname'" [] (or (try (let [{:keys [exit out]} (sh/sh "hostname")] (if (= exit 0) (str/trim out))) (catch Exception _)) "<unknown>")) (defn hostname "Fetches the hostname by shelling to 'hostname', whenever the given age is stale enough. If the given age is recent, as defined by hostname-refresh-interval, returns age and val instead." [[age val]] (if (and val (<= (* 1000 hostname-refresh-interval) (- (System/currentTimeMillis) age))) [age val] [(System/currentTimeMillis) (get-hostname)])) (let [cache (atom [nil nil])] (defn localhost "Returns the local host name." [] (if (re-find #"^Windows" (System/getProperty "os.name")) (or (System/getenv "COMPUTERNAME") "localhost") (or (System/getenv "HOSTNAME") (second (swap! cache hostname)))))) (def dsn-pattern "The shape of a sentry DSN" #"^(https?)://([^:]*):([^@]*)@(.*)/([0-9]+)$") (defn parse-dsn "Extract DSN parameters into a map" [dsn] (if-let [[_ proto key secret uri ^String pid] (re-find dsn-pattern dsn)] {:key key :secret secret :uri (format "%s://%s" proto uri) :pid (Long. pid)} (throw (ex-info "could not parse sentry DSN" {:dsn dsn})))) (defn default-payload "Provide default values for a payload." [ts localhost] {:level "error" :server_name localhost :timestamp ts :platform "java"}) (defn auth-header "Compute the Sentry auth header." [ts key sig] (let [params [[:version "2.0"] [:signature sig] [:timestamp ts] [:client user-agent] [:key key]] param (fn [[k v]] (format "sentry_%s=%s" (name k) v))] (str "Sentry " (str/join ", " (map param params))))) (defn merged-payload "Return a payload map depending on the type of the event." [event ts localhost] (merge (default-payload ts localhost) (cond (map? event) event (e/exception? event) (e/exception->ev event) :else {:message (str event)}))) (defn add-breadcrumbs-to-payload [context payload] (let [breadcrumbs-list (or (:breadcrumbs payload) (:breadcrumbs context))] (cond-> payload (seq breadcrumbs-list) (assoc :breadcrumbs {:values breadcrumbs-list})))) (defn add-user-to-payload [context payload] (cond-> payload (:user context) (assoc :user (:user context)))) (defn add-http-info-to-payload [context payload] (cond-> payload (:request context) (assoc :request (:request context)))) (defn slurp-pretty-name [path] (try (last (re-find #"PRETTY_NAME=\"(.*)\"" (slurp path))) (catch Exception _))) (defn get-linux-pretty-name "Get the Linux distribution pretty name from /etc/os-release resp. /usr/lib/os-release." [] (or (slurp-pretty-name "/etc/os-release") (slurp-pretty-name "/usr/lib/os-release") "Unknown Linux")) (let [cache (atom nil)] ;; cache version forever (defn get-os-name-linux "Get a human-readable name for the current linux distribution from /etc/os-release, caching the output" [] (or @cache (swap! cache (constantly (get-linux-pretty-name)))))) (defn get-os-context [] (let [os-name (System/getProperty "os.name") os-version (System/getProperty "os.version")] (if (re-find #"^Linux" os-name) {:name os-name :version (get-os-name-linux) :kernel_version os-version} {:name os-name :version os-version}))) (defn get-contexts [] {:java {:name (System/getProperty "java.vendor") :version (System/getProperty "java.version")} :os (get-os-context) :clojure {:name "clojure" :version (clojure-version)}}) (defn add-contexts-to-payload "Add relevant bits of sentry.interfaces.Contexts to our payload." [payload] (assoc payload :contexts (get-contexts))) (defn add-fingerprint-to-payload "If the context provides a fingerprint override entry, pass it to the payload." [context payload] (cond-> payload (:fingerprint context) (assoc :fingerprint (:fingerprint context)))) (defn add-tags-to-payload "If the context provides tags or we were given tags directly during capture!, ad them to the payload. Tags provided by capture! override tags provided by the context map." [context payload tags] (let [merged (merge (:tags context) tags)] (cond-> payload (not (empty? merged)) (assoc :tags merged)))) (defn add-uuid-to-payload [context payload] (assoc payload :event_id (:event_id context (:event_id payload (sentry-uuid!))))) (defn validate-payload "Returns a validated payload." [merged] (s/assert :raven.spec/payload merged)) (defn payload "Build a full valid payload." [context event ts localhost tags] (let [breadcrumbs-adder (partial add-breadcrumbs-to-payload context) user-adder (partial add-user-to-payload context) http-info-adder (partial add-http-info-to-payload context) fingerprint-adder (partial add-fingerprint-to-payload context) tags-adder (partial add-tags-to-payload context) uuid-adder (partial add-uuid-to-payload context)] (-> (merged-payload event ts localhost) (uuid-adder) (breadcrumbs-adder) (user-adder) (fingerprint-adder) (http-info-adder) (tags-adder tags) (add-contexts-to-payload) (validate-payload)))) (defn timestamp! "Retrieve a timestamp. The format used is the same as python's 'time.time()' function - the number of seconds since the epoch, as a double to acount for fractional seconds (since the granularity is miliseconds)." [] (double (/ (System/currentTimeMillis) 1000))) (defn sign "HMAC-SHA1 for Sentry's format." [payload ts key ^String secret] (let [key (PI:KEY:<KEY>END_PI. (.getBytes secret) "PI:KEY:<KEY>END_PI") bs (-> (doto (javax.crypto.Mac/getInstance "HmacSHA1") (.init key) (.update (.getBytes (str ts))) (.update (.getBytes " "))) (.doFinal payload))] (reduce str (for [b bs] (format "%02x" b))))) (defn perform-in-memory-request "Perform an in-memory pseudo-request, actually just storing the payload on a storage atom, to let users inspect/retrieve the payload in their tests." [payload] (swap! http-requests-payload-stub conj payload)) (defrecord SafeMap []) (defmethod clojure.core/print-method SafeMap [m ^java.io.Writer writer] (.write writer (format "#exoscale/safe-map [%s]" (str/join " " (keys m))))) (def safe-map "Wraps map into SafeMap record, effectively hidding values from json output, will not allow 2-way roundtrip. ex: (safe-map {:a 1}) -> \"#exoscale/safe-map [:a]\". Can be used to hide secrets and/or shorten large/deep maps" map->SafeMap) (def json-mapper (doto (json/object-mapper {:encoders {SafeMap (fn [x ^JsonGenerator jg] (.writeString jg (pr-str x)))}}) (.configure SerializationFeature/FAIL_ON_EMPTY_BEANS false) (.configure MapperFeature/AUTO_DETECT_GETTERS false) (.configure MapperFeature/AUTO_DETECT_IS_GETTERS false) (.configure MapperFeature/AUTO_DETECT_SETTERS false) (.configure MapperFeature/AUTO_DETECT_FIELDS false) (.configure MapperFeature/DEFAULT_VIEW_INCLUSION false))) (def closable? (partial instance? Closeable)) (defn close-http-connection " When having a connection pool set, the body cannot be closed as it's of a different type. " [response] (let [{:keys [body]} response] (when (closable? body) (.close ^Closeable body)))) (defn re-throw-response " Throw the response in case of its status was not 2xx as we don't want Sentry errors to be unnoticed. " [response] (let [{:keys [status]} response] (when-not (-> status str first (= \2)) (throw (ex-info (format "Sentry HTTP error") response))))) (defn perform-http-request [context dsn ts payload] (let [json-payload (json/write-value-as-bytes payload json-mapper) {:keys [key secret uri]} (parse-dsn dsn) sig (sign json-payload ts key secret)] (d/chain (http/post (str uri "/api/store/") (merge (select-keys context [:pool :middleware :pool-timeout :response-executor :request-timeout :read-timeout :connection-timeout]) {:headers {:x-sentry-auth (auth-header ts key sig) :accept "application/json" :content-type "application/json;charset=utf-8"} :body json-payload :throw-exceptions? false})) (fn [response] (close-http-connection response) (re-throw-response response))))) (defn capture! "Send a capture over the network. If `ev` is an exception, build an appropriate payload for the exception." ([context dsn event tags] (let [ts (timestamp!) payload (payload context event ts (localhost) tags) uuid (:event_id payload)] (d/chain (if (= dsn ":memory:") (perform-in-memory-request payload) (perform-http-request context dsn ts payload)) (fn [_] (clear-context) uuid)))) ([dsn ev tags] (capture! @@thread-storage dsn ev tags)) ([dsn ev] (capture! @@thread-storage dsn ev {}))) (defn make-breadcrumb! "Create a breadcrumb map. level can be one of: ['debug' 'info' 'warning' 'warn' 'error' 'exception' 'critical' 'fatal']" ([message category] (make-breadcrumb! message category "info")) ([message category level] (make-breadcrumb! message category level (timestamp!))) ([message category level timestamp] {:type "default" ;; TODO: Extend to support more than just default breadcrumbs. :timestamp timestamp :level level :message message :category category}) ;; :data (expected in case of non-default) ) (defn add-breadcrumb! "Append a breadcrumb to the list of breadcrumbs. The context is expected to be a map, and if no context is specified, a thread-local storage map will be used instead. " ([breadcrumb] ;; We need to dereference to get the atom since "thread-storage" is thread-local. (swap! @thread-storage add-breadcrumb! breadcrumb)) ([context breadcrumb] ;; We add the breadcrumb to the context instead, in a ":breadcrumb" key. (update context :breadcrumbs conj (s/assert :raven.spec/breadcrumb breadcrumb)))) (defn make-user "Create a user map." ([id] {:id id}) ([id email ip-address username] {:id id :email email :ip_address ip-address :username username})) (defn add-user! "Add user information to the sentry context (or a thread-local storage)." ([user] (swap! @thread-storage add-user! user)) ([context user] (assoc context :user (s/assert :raven.spec/user user)))) (defn make-http-info ([url method] {:url url :method method}) ([url method headers query_string cookies data env] {:url url :method method :headers headers :query_string query_string :cookies cookies :data data :env env})) (defn get-full-ring-url "Given a ring compliant request object, return the full URL. This was lifted from ring's source code so as to not depend on it." [request] (str (-> request :scheme name) "://" (get-in request [:headers "host"]) (:uri request) (when-let [query (:query-string request)] (str "?" query)))) (defn get-ring-env [request] (cond-> {:REMOTE_ADDR (:remote-addr request) :websocket? (:websocket? request) :route-params (:route-params request)} (some? (:compojure/route request)) (assoc :compojure/route (:compojure/route request)) (some? (:route request)) (assoc :bidi/route (get-in request [:route :handler])))) (defn make-ring-request-info "Create well-formatted context map for the Sentry 'HTTP' interface by extracting the information from a standard ring-compliant 'request', as defined in https://github.com/ring-clojure/ring/wiki/Concepts#requests" [request] {:url (get-full-ring-url request) :method (:request-method request) :cookies (get-in request [:headers "cookie"]) :headers (:headers request) :query_string (:query-string request) :env (get-ring-env request) :data (:body request)}) (defn add-http-info! "Add HTTP information to the sentry context (or a thread-local storage)." ([http-info] (swap! @thread-storage add-http-info! http-info)) ([context http-info] (assoc context :request (s/assert :raven.spec/request http-info)))) (defn add-ring-request! "Add HTTP information to the Sentry payload from a ring-compliant request map, excluding its body." ([request] (add-http-info! (make-ring-request-info (dissoc request :body)))) ([context request] (add-http-info! context (make-ring-request-info (dissoc request :body))))) (defn add-full-ring-request! "Add HTTP information to the Sentry payload from a ring-compliant request map, including the request body" ([request] (add-http-info! (make-ring-request-info request))) ([context request] (add-http-info! context (make-ring-request-info request)))) (defn add-fingerprint! "Add a custom fingerprint to the context (or a thread-local storage)." ([fingerprint] (swap! @thread-storage add-fingerprint! fingerprint)) ([context fingerprint] (assoc context :fingerprint (s/assert :raven.spec/fingerprint fingerprint)))) (defn add-tag! "Add a custom tag to the context (or a thread-local storage)." ([tag value] (swap! @thread-storage add-tag! tag value)) ([context tag value] (assoc-in context [:tags tag] value))) (defn add-tags! "Add custom tags to the context (or a thread-local storage)." ([tags] (swap! @thread-storage add-tags! tags)) ([context tags] (reduce-kv add-tag! context tags))) (defn add-extra! "Add a map of extra data to the context (or a thread-local storage) preserving its previous keys." ([extra] (swap! @thread-storage add-extra! extra)) ([context extra] (update context :extra merge extra))) (defn add-exception! "Add an exception to the context (or a thread-local storage)." ([^Throwable e] (swap! @thread-storage add-exception! e)) ([context ^Throwable e] (let [env (e/exception->ev e)] (-> context (merge (dissoc env :extra)) (add-extra! (:extra env)))))) (defn release! "Release new application version with provided webhook release URL." [webhook-endpoint payload] (if (some? (:version payload)) (http/post webhook-endpoint {:headers {:content-type "application/json"} :body (json/write-value-as-bytes payload)}) (throw (ex-info "no version key provided" {:payload payload}))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9997995495796204, "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.9998199939727783, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/editor/field_expression_test.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.field-expression-test (:require [clojure.test :refer :all] [editor.field-expression :refer [format-int format-number to-double to-int]])) (deftest format-double-test (are [n s] (= s (#'editor.field-expression/format-double n)) nil "" Double/NaN "NaN" Double/POSITIVE_INFINITY "Infinity" Double/NEGATIVE_INFINITY "-Infinity" 0 "0" -1 "-1" 0.1 "0.1" 0.00001 "0.00001" 1.000001 "1.000001" 1100.11 "1100.11" 9223372036854775807 "9223372036854775807" -9223372036854775808 "-9223372036854775808" 3.141592653589793 "3.141592653589793" 31.41592653589793 "31.41592653589793" 314.1592653589793 "314.1592653589793" 3141.592653589793 "3141.592653589793" 31415.92653589793 "31415.92653589793" 314159.2653589793 "314159.2653589793" 3141592.653589793 "3141592.653589793" 31415926.53589793 "31415926.53589793" 314159265.3589793 "314159265.3589793" 3141592653.589793 "3141592653.589793" 31415926535.89793 "31415926535.89793" 314159265358.9793 "314159265358.9793" 3141592653589.793 "3141592653589.793" 31415926535897.93 "31415926535897.93" 314159265358979.3 "314159265358979.3")) (deftest format-float-test (are [n s] (= s (#'editor.field-expression/format-float (some-> n float))) nil "" Float/NaN "NaN" Float/POSITIVE_INFINITY "Infinity" Float/NEGATIVE_INFINITY "-Infinity" 0 "0" -1 "-1" 0.1 "0.1" 0.00001 "0.00001" 1.000001 "1.000001" 1100.11 "1100.11" 32767 "32767" -32768 "-32768" 8388607 "8388607" -8388608 "-8388608" 3.141593 "3.141593" 31.41593 "31.41593" 314.1593 "314.1593" 3141.593 "3141.593" 31415.93 "31415.93" 314159.3 "314159.3")) (deftest format-int-test (are [n s] (= s (format-int n)) nil "" 0 "0" -1 "-1" 2147483647 "2147483647" -2147483648 "-2147483648")) (deftest format-number-test (are [n s] (= s (format-number n)) nil "" Double/NaN "NaN" Double/POSITIVE_INFINITY "Infinity" Double/NEGATIVE_INFINITY "-Infinity" Float/NaN "NaN" Float/POSITIVE_INFINITY "Infinity" Float/NEGATIVE_INFINITY "-Infinity" 0 "0" -1 "-1" 2147483647 "2147483647" -2147483648 "-2147483648" 9223372036854775807 "9223372036854775807" -9223372036854775808 "-9223372036854775808" (float 0.1) "0.1" (float 0.00001) "0.00001" (float 1.000001) "1.000001" (float 1100.11) "1100.11" 3.141592653589793 "3.141592653589793")) (deftest to-double-test (testing "String conversion" (is (= 0.0 (to-double "0"))) (is (= 1.1 (to-double "1.1"))) (is (= -2.0 (to-double "-2"))) (is (= -2.5 (to-double "-2.5"))) (is (= -1.5 (to-double "-1,5"))) (is (= 3.1 (to-double "+3.1"))) (is (= 0.0001 (to-double "1.0e-4"))) (is (= 0.00001 (to-double "1.0E-5"))) (is (= 100000000000000000000.0 (to-double "1.0E20"))) (is (= 1000000000000000000000.0 (to-double "1.0E+21")))) (testing "Arithmetic" (testing "Whitespace not significant" (is (= 3.0 (to-double "1+2"))) (is (= 4.0 (to-double "2 + 2")))) (testing "Basic operations" (is (= 20.0 (to-double "10 + 10"))) (is (= 10.0 (to-double "20 - 10"))) (is (= 25.0 (to-double "5 * 5"))) (is (= 30.0 (to-double "60 / 2")))) (testing "Scientific notation terms" (is (= 1.0 (to-double "1.0e-4 / 1.0e-4"))) (is (= 1.0 (to-double "1.0E-4 / 1.0E-4")))))) (deftest to-int-test (testing "String conversion" (is (= 0 (to-int "0"))) (is (= 1 (to-int "1"))) (is (= -2 (to-int "-2"))) (is (= 3 (to-int "+3")))) (testing "Arithmetic" (testing "Whitespace not significant" (is (= 3 (to-int "1+2"))) (is (= 4 (to-int "2 + 2")))) (testing "Basic operations" (is (= 20 (to-int "10 + 10"))) (is (= 10 (to-int "20 - 10"))) (is (= 25 (to-int "5 * 5"))) (is (= 30 (to-int "60 / 2")))))) (deftest double-loopback-test (is (true? (Double/isNaN (to-double (#'editor.field-expression/format-double Double/NaN))))) (are [n] (= n (to-double (#'editor.field-expression/format-double n))) Double/MAX_VALUE Double/MIN_VALUE Double/MIN_NORMAL Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY)) (deftest int-loopback-test (are [n] (= n (to-int (format-int n))) Integer/MAX_VALUE Integer/MIN_VALUE)) (deftest number-loopback-test (is (true? (Double/isNaN (to-double (format-number Double/NaN))))) (are [n] (= n (to-double (format-number n))) Double/MAX_VALUE Double/MIN_VALUE Double/MIN_NORMAL Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY 0.0 -1.0 0.1 0.00001 1.000001 1100.11 9223372036854775807.0 -9223372036854775808.0 3.141592653589793 31.41592653589793 314.1592653589793 3141.592653589793 31415.92653589793 314159.2653589793 3141592.653589793 31415926.53589793 314159265.3589793 3141592653.589793 31415926535.89793 314159265358.9793 3141592653589.793 31415926535897.93 314159265358979.3) (is (true? (Double/isNaN (to-double (format-number Float/NaN))))) (is (= Double/POSITIVE_INFINITY (to-double (format-number Float/POSITIVE_INFINITY)))) (is (= Double/NEGATIVE_INFINITY (to-double (format-number Float/NEGATIVE_INFINITY)))) (are [n] (= n (to-double (format-number (float n)))) 0.0 -1.0 0.1 0.00001 1.000001 1100.11 32767.0 -32768.0 8388607.0 -8388608.0 3.141593 31.41593 314.1593 3141.593 31415.93 314159.3))
78792
;; 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.field-expression-test (:require [clojure.test :refer :all] [editor.field-expression :refer [format-int format-number to-double to-int]])) (deftest format-double-test (are [n s] (= s (#'editor.field-expression/format-double n)) nil "" Double/NaN "NaN" Double/POSITIVE_INFINITY "Infinity" Double/NEGATIVE_INFINITY "-Infinity" 0 "0" -1 "-1" 0.1 "0.1" 0.00001 "0.00001" 1.000001 "1.000001" 1100.11 "1100.11" 9223372036854775807 "9223372036854775807" -9223372036854775808 "-9223372036854775808" 3.141592653589793 "3.141592653589793" 31.41592653589793 "31.41592653589793" 314.1592653589793 "314.1592653589793" 3141.592653589793 "3141.592653589793" 31415.92653589793 "31415.92653589793" 314159.2653589793 "314159.2653589793" 3141592.653589793 "3141592.653589793" 31415926.53589793 "31415926.53589793" 314159265.3589793 "314159265.3589793" 3141592653.589793 "3141592653.589793" 31415926535.89793 "31415926535.89793" 314159265358.9793 "314159265358.9793" 3141592653589.793 "3141592653589.793" 31415926535897.93 "31415926535897.93" 314159265358979.3 "314159265358979.3")) (deftest format-float-test (are [n s] (= s (#'editor.field-expression/format-float (some-> n float))) nil "" Float/NaN "NaN" Float/POSITIVE_INFINITY "Infinity" Float/NEGATIVE_INFINITY "-Infinity" 0 "0" -1 "-1" 0.1 "0.1" 0.00001 "0.00001" 1.000001 "1.000001" 1100.11 "1100.11" 32767 "32767" -32768 "-32768" 8388607 "8388607" -8388608 "-8388608" 3.141593 "3.141593" 31.41593 "31.41593" 314.1593 "314.1593" 3141.593 "3141.593" 31415.93 "31415.93" 314159.3 "314159.3")) (deftest format-int-test (are [n s] (= s (format-int n)) nil "" 0 "0" -1 "-1" 2147483647 "2147483647" -2147483648 "-2147483648")) (deftest format-number-test (are [n s] (= s (format-number n)) nil "" Double/NaN "NaN" Double/POSITIVE_INFINITY "Infinity" Double/NEGATIVE_INFINITY "-Infinity" Float/NaN "NaN" Float/POSITIVE_INFINITY "Infinity" Float/NEGATIVE_INFINITY "-Infinity" 0 "0" -1 "-1" 2147483647 "2147483647" -2147483648 "-2147483648" 9223372036854775807 "9223372036854775807" -9223372036854775808 "-9223372036854775808" (float 0.1) "0.1" (float 0.00001) "0.00001" (float 1.000001) "1.000001" (float 1100.11) "1100.11" 3.141592653589793 "3.141592653589793")) (deftest to-double-test (testing "String conversion" (is (= 0.0 (to-double "0"))) (is (= 1.1 (to-double "1.1"))) (is (= -2.0 (to-double "-2"))) (is (= -2.5 (to-double "-2.5"))) (is (= -1.5 (to-double "-1,5"))) (is (= 3.1 (to-double "+3.1"))) (is (= 0.0001 (to-double "1.0e-4"))) (is (= 0.00001 (to-double "1.0E-5"))) (is (= 100000000000000000000.0 (to-double "1.0E20"))) (is (= 1000000000000000000000.0 (to-double "1.0E+21")))) (testing "Arithmetic" (testing "Whitespace not significant" (is (= 3.0 (to-double "1+2"))) (is (= 4.0 (to-double "2 + 2")))) (testing "Basic operations" (is (= 20.0 (to-double "10 + 10"))) (is (= 10.0 (to-double "20 - 10"))) (is (= 25.0 (to-double "5 * 5"))) (is (= 30.0 (to-double "60 / 2")))) (testing "Scientific notation terms" (is (= 1.0 (to-double "1.0e-4 / 1.0e-4"))) (is (= 1.0 (to-double "1.0E-4 / 1.0E-4")))))) (deftest to-int-test (testing "String conversion" (is (= 0 (to-int "0"))) (is (= 1 (to-int "1"))) (is (= -2 (to-int "-2"))) (is (= 3 (to-int "+3")))) (testing "Arithmetic" (testing "Whitespace not significant" (is (= 3 (to-int "1+2"))) (is (= 4 (to-int "2 + 2")))) (testing "Basic operations" (is (= 20 (to-int "10 + 10"))) (is (= 10 (to-int "20 - 10"))) (is (= 25 (to-int "5 * 5"))) (is (= 30 (to-int "60 / 2")))))) (deftest double-loopback-test (is (true? (Double/isNaN (to-double (#'editor.field-expression/format-double Double/NaN))))) (are [n] (= n (to-double (#'editor.field-expression/format-double n))) Double/MAX_VALUE Double/MIN_VALUE Double/MIN_NORMAL Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY)) (deftest int-loopback-test (are [n] (= n (to-int (format-int n))) Integer/MAX_VALUE Integer/MIN_VALUE)) (deftest number-loopback-test (is (true? (Double/isNaN (to-double (format-number Double/NaN))))) (are [n] (= n (to-double (format-number n))) Double/MAX_VALUE Double/MIN_VALUE Double/MIN_NORMAL Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY 0.0 -1.0 0.1 0.00001 1.000001 1100.11 9223372036854775807.0 -9223372036854775808.0 3.141592653589793 31.41592653589793 314.1592653589793 3141.592653589793 31415.92653589793 314159.2653589793 3141592.653589793 31415926.53589793 314159265.3589793 3141592653.589793 31415926535.89793 314159265358.9793 3141592653589.793 31415926535897.93 314159265358979.3) (is (true? (Double/isNaN (to-double (format-number Float/NaN))))) (is (= Double/POSITIVE_INFINITY (to-double (format-number Float/POSITIVE_INFINITY)))) (is (= Double/NEGATIVE_INFINITY (to-double (format-number Float/NEGATIVE_INFINITY)))) (are [n] (= n (to-double (format-number (float n)))) 0.0 -1.0 0.1 0.00001 1.000001 1100.11 32767.0 -32768.0 8388607.0 -8388608.0 3.141593 31.41593 314.1593 3141.593 31415.93 314159.3))
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.field-expression-test (:require [clojure.test :refer :all] [editor.field-expression :refer [format-int format-number to-double to-int]])) (deftest format-double-test (are [n s] (= s (#'editor.field-expression/format-double n)) nil "" Double/NaN "NaN" Double/POSITIVE_INFINITY "Infinity" Double/NEGATIVE_INFINITY "-Infinity" 0 "0" -1 "-1" 0.1 "0.1" 0.00001 "0.00001" 1.000001 "1.000001" 1100.11 "1100.11" 9223372036854775807 "9223372036854775807" -9223372036854775808 "-9223372036854775808" 3.141592653589793 "3.141592653589793" 31.41592653589793 "31.41592653589793" 314.1592653589793 "314.1592653589793" 3141.592653589793 "3141.592653589793" 31415.92653589793 "31415.92653589793" 314159.2653589793 "314159.2653589793" 3141592.653589793 "3141592.653589793" 31415926.53589793 "31415926.53589793" 314159265.3589793 "314159265.3589793" 3141592653.589793 "3141592653.589793" 31415926535.89793 "31415926535.89793" 314159265358.9793 "314159265358.9793" 3141592653589.793 "3141592653589.793" 31415926535897.93 "31415926535897.93" 314159265358979.3 "314159265358979.3")) (deftest format-float-test (are [n s] (= s (#'editor.field-expression/format-float (some-> n float))) nil "" Float/NaN "NaN" Float/POSITIVE_INFINITY "Infinity" Float/NEGATIVE_INFINITY "-Infinity" 0 "0" -1 "-1" 0.1 "0.1" 0.00001 "0.00001" 1.000001 "1.000001" 1100.11 "1100.11" 32767 "32767" -32768 "-32768" 8388607 "8388607" -8388608 "-8388608" 3.141593 "3.141593" 31.41593 "31.41593" 314.1593 "314.1593" 3141.593 "3141.593" 31415.93 "31415.93" 314159.3 "314159.3")) (deftest format-int-test (are [n s] (= s (format-int n)) nil "" 0 "0" -1 "-1" 2147483647 "2147483647" -2147483648 "-2147483648")) (deftest format-number-test (are [n s] (= s (format-number n)) nil "" Double/NaN "NaN" Double/POSITIVE_INFINITY "Infinity" Double/NEGATIVE_INFINITY "-Infinity" Float/NaN "NaN" Float/POSITIVE_INFINITY "Infinity" Float/NEGATIVE_INFINITY "-Infinity" 0 "0" -1 "-1" 2147483647 "2147483647" -2147483648 "-2147483648" 9223372036854775807 "9223372036854775807" -9223372036854775808 "-9223372036854775808" (float 0.1) "0.1" (float 0.00001) "0.00001" (float 1.000001) "1.000001" (float 1100.11) "1100.11" 3.141592653589793 "3.141592653589793")) (deftest to-double-test (testing "String conversion" (is (= 0.0 (to-double "0"))) (is (= 1.1 (to-double "1.1"))) (is (= -2.0 (to-double "-2"))) (is (= -2.5 (to-double "-2.5"))) (is (= -1.5 (to-double "-1,5"))) (is (= 3.1 (to-double "+3.1"))) (is (= 0.0001 (to-double "1.0e-4"))) (is (= 0.00001 (to-double "1.0E-5"))) (is (= 100000000000000000000.0 (to-double "1.0E20"))) (is (= 1000000000000000000000.0 (to-double "1.0E+21")))) (testing "Arithmetic" (testing "Whitespace not significant" (is (= 3.0 (to-double "1+2"))) (is (= 4.0 (to-double "2 + 2")))) (testing "Basic operations" (is (= 20.0 (to-double "10 + 10"))) (is (= 10.0 (to-double "20 - 10"))) (is (= 25.0 (to-double "5 * 5"))) (is (= 30.0 (to-double "60 / 2")))) (testing "Scientific notation terms" (is (= 1.0 (to-double "1.0e-4 / 1.0e-4"))) (is (= 1.0 (to-double "1.0E-4 / 1.0E-4")))))) (deftest to-int-test (testing "String conversion" (is (= 0 (to-int "0"))) (is (= 1 (to-int "1"))) (is (= -2 (to-int "-2"))) (is (= 3 (to-int "+3")))) (testing "Arithmetic" (testing "Whitespace not significant" (is (= 3 (to-int "1+2"))) (is (= 4 (to-int "2 + 2")))) (testing "Basic operations" (is (= 20 (to-int "10 + 10"))) (is (= 10 (to-int "20 - 10"))) (is (= 25 (to-int "5 * 5"))) (is (= 30 (to-int "60 / 2")))))) (deftest double-loopback-test (is (true? (Double/isNaN (to-double (#'editor.field-expression/format-double Double/NaN))))) (are [n] (= n (to-double (#'editor.field-expression/format-double n))) Double/MAX_VALUE Double/MIN_VALUE Double/MIN_NORMAL Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY)) (deftest int-loopback-test (are [n] (= n (to-int (format-int n))) Integer/MAX_VALUE Integer/MIN_VALUE)) (deftest number-loopback-test (is (true? (Double/isNaN (to-double (format-number Double/NaN))))) (are [n] (= n (to-double (format-number n))) Double/MAX_VALUE Double/MIN_VALUE Double/MIN_NORMAL Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY 0.0 -1.0 0.1 0.00001 1.000001 1100.11 9223372036854775807.0 -9223372036854775808.0 3.141592653589793 31.41592653589793 314.1592653589793 3141.592653589793 31415.92653589793 314159.2653589793 3141592.653589793 31415926.53589793 314159265.3589793 3141592653.589793 31415926535.89793 314159265358.9793 3141592653589.793 31415926535897.93 314159265358979.3) (is (true? (Double/isNaN (to-double (format-number Float/NaN))))) (is (= Double/POSITIVE_INFINITY (to-double (format-number Float/POSITIVE_INFINITY)))) (is (= Double/NEGATIVE_INFINITY (to-double (format-number Float/NEGATIVE_INFINITY)))) (are [n] (= n (to-double (format-number (float n)))) 0.0 -1.0 0.1 0.00001 1.000001 1100.11 32767.0 -32768.0 8388607.0 -8388608.0 3.141593 31.41593 314.1593 3141.593 31415.93 314159.3))
[ { "context": ";; Copyright 2018 Chris Rink\n;;\n;; Licensed under the Apache License, Version ", "end": 28, "score": 0.9998436570167542, "start": 18, "tag": "NAME", "value": "Chris Rink" }, { "context": " :as req}]\n (if-let [{:keys [oauth_access_token app_user_id]}\n (db.teams/workspace-detail", "end": 3744, "score": 0.5537167191505432, "start": 3741, "tag": "KEY", "value": "app" } ]
src/clojure/slackbot/middleware.clj
chrisrink10/slackbot-clj
0
;; Copyright 2018 Chris Rink ;; ;; 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 slackbot.middleware (:import java.io.InputStream java.io.OutputStreamWriter java.io.OutputStream) (:require [clojure.pprint :as pprint] [clojure.walk :as walk] [next.jdbc :as jdbc] [muuntaja.core :as muuntaja] [muuntaja.format.core :as fmt] [muuntaja.middleware] [ring.util.codec :as codec] [ring.util.response :as response] [taoensso.timbre :as timbre] [slackbot.config :as config] [slackbot.database :as db] [slackbot.database.teams :as db.teams])) (defn handle-format-exceptions "Handle Muuntaja formatting exceptions and return a response." [^Exception e fmt _] (timbre/error {:message "Could not format request" :format fmt :error (ex-message e)}) {:status 400 :headers {:content-type "application/json"} :body {:error "Error occurred attempting to format body to Content-Type" :format fmt}}) (defn url-encoder [_] (reify fmt/EncodeToBytes (encode-to-bytes [_ data charset] (.getBytes (codec/form-encode data ^String charset) ^String charset)) fmt/EncodeToOutputStream (encode-to-output-stream [_ data charset] (fn [^OutputStream stream] (.write (OutputStreamWriter. stream ^String charset) ^String (codec/form-encode data charset)))))) (defn url-decoder [_] (reify fmt/Decode (decode [_ data charset] (-> (slurp ^InputStream data :encoding charset) (codec/form-decode ^String charset) (walk/keywordize-keys))))) (defn muuntaja [] (->> {:name "application/x-www-form-urlencoded" :encoder [url-encoder] :decoder [url-decoder]} (fmt/map->Format) (assoc-in muuntaja/default-options [:formats "application/x-www-form-urlencoded"]) (muuntaja/create))) (def muuntaja-cache (memoize muuntaja)) (defn wrap-query-params "Format a query string into a standard Clojure map." [handler] (fn [{:keys [query-string] :as req}] (handler (cond-> req (some? query-string) (assoc :query-params (-> query-string (codec/form-decode) (walk/keywordize-keys))))))) (defn wrap-format "Perform content negotiation based on HTTP header values using Muuntaja." [handler] (let [m (muuntaja-cache)] (-> handler (muuntaja.middleware/wrap-params) (wrap-query-params) (muuntaja.middleware/wrap-format-request m) (muuntaja.middleware/wrap-exception handle-format-exceptions) (muuntaja.middleware/wrap-format-response m) (muuntaja.middleware/wrap-format-negotiate m)))) (defn wrap-supply-tx "Hydrate each request with a database transaction." [handler] (fn [req] (jdbc/with-transaction [tx db/datasource] (->> tx (assoc req :slackbot.database/tx) (handler))))) (defn wrap-supply-slack-details "Pull the Slack Team ID from the request and fetch relevant team details for this request." [handler] (fn [{{:keys [team_id type]} :body-params tx :slackbot.database/tx :as req}] (if-let [{:keys [oauth_access_token app_user_id]} (db.teams/workspace-details tx {:workspace_id team_id})] (-> req (assoc :slackbot.slack/oauth-access-token oauth_access_token) (assoc :slackbot.slack/app-user-id app_user_id) (handler)) (if (= "url_verification" type) (do (timbre/info {:message "Received URL verification request, passing through without team or app user ID" :type type}) (handler req)) (do (timbre/warn {:message "Received request from unregistered team" :team-id team_id}) (-> {:message "Invalid team" :team-id team_id} (response/bad-request))))))) (defn wrap-verify-slack-token "Check for a Slack Verification token in the request body and reject the request if it does not match the known verification token." [handler] (let [verification-token (config/config [:slack :verification-token])] (fn [{{:keys [token]} :body-params :as req}] (if (not= token verification-token) (do (timbre/info {:message "Received request with invalid Slack verification token" :token token}) (-> {:message "Not Found"} (response/bad-request))) (handler req))))) (defn wrap-ignore-myself "Ignore Slack Events from the app." [handler] (fn [{{{:keys [user]} :event type :type} :body-params app-user-id :slackbot.slack/app-user-id :as req}] (if (or (not= app-user-id user) (= "url_verification" type)) (handler req) (do (timbre/debug {:message "Ignoring message from myself"}) (-> (response/response nil) (response/status 200)))))) (defn wrap-debug-log-request "Emit the entire request map out as a debug log." [handler] (fn debug-log-request [req] (timbre/debug (with-out-str (pprint/pprint req))) (let [resp (handler req)] (timbre/debug (with-out-str (pprint/pprint resp))) resp)))
37982
;; Copyright 2018 <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 slackbot.middleware (:import java.io.InputStream java.io.OutputStreamWriter java.io.OutputStream) (:require [clojure.pprint :as pprint] [clojure.walk :as walk] [next.jdbc :as jdbc] [muuntaja.core :as muuntaja] [muuntaja.format.core :as fmt] [muuntaja.middleware] [ring.util.codec :as codec] [ring.util.response :as response] [taoensso.timbre :as timbre] [slackbot.config :as config] [slackbot.database :as db] [slackbot.database.teams :as db.teams])) (defn handle-format-exceptions "Handle Muuntaja formatting exceptions and return a response." [^Exception e fmt _] (timbre/error {:message "Could not format request" :format fmt :error (ex-message e)}) {:status 400 :headers {:content-type "application/json"} :body {:error "Error occurred attempting to format body to Content-Type" :format fmt}}) (defn url-encoder [_] (reify fmt/EncodeToBytes (encode-to-bytes [_ data charset] (.getBytes (codec/form-encode data ^String charset) ^String charset)) fmt/EncodeToOutputStream (encode-to-output-stream [_ data charset] (fn [^OutputStream stream] (.write (OutputStreamWriter. stream ^String charset) ^String (codec/form-encode data charset)))))) (defn url-decoder [_] (reify fmt/Decode (decode [_ data charset] (-> (slurp ^InputStream data :encoding charset) (codec/form-decode ^String charset) (walk/keywordize-keys))))) (defn muuntaja [] (->> {:name "application/x-www-form-urlencoded" :encoder [url-encoder] :decoder [url-decoder]} (fmt/map->Format) (assoc-in muuntaja/default-options [:formats "application/x-www-form-urlencoded"]) (muuntaja/create))) (def muuntaja-cache (memoize muuntaja)) (defn wrap-query-params "Format a query string into a standard Clojure map." [handler] (fn [{:keys [query-string] :as req}] (handler (cond-> req (some? query-string) (assoc :query-params (-> query-string (codec/form-decode) (walk/keywordize-keys))))))) (defn wrap-format "Perform content negotiation based on HTTP header values using Muuntaja." [handler] (let [m (muuntaja-cache)] (-> handler (muuntaja.middleware/wrap-params) (wrap-query-params) (muuntaja.middleware/wrap-format-request m) (muuntaja.middleware/wrap-exception handle-format-exceptions) (muuntaja.middleware/wrap-format-response m) (muuntaja.middleware/wrap-format-negotiate m)))) (defn wrap-supply-tx "Hydrate each request with a database transaction." [handler] (fn [req] (jdbc/with-transaction [tx db/datasource] (->> tx (assoc req :slackbot.database/tx) (handler))))) (defn wrap-supply-slack-details "Pull the Slack Team ID from the request and fetch relevant team details for this request." [handler] (fn [{{:keys [team_id type]} :body-params tx :slackbot.database/tx :as req}] (if-let [{:keys [oauth_access_token <KEY>_user_id]} (db.teams/workspace-details tx {:workspace_id team_id})] (-> req (assoc :slackbot.slack/oauth-access-token oauth_access_token) (assoc :slackbot.slack/app-user-id app_user_id) (handler)) (if (= "url_verification" type) (do (timbre/info {:message "Received URL verification request, passing through without team or app user ID" :type type}) (handler req)) (do (timbre/warn {:message "Received request from unregistered team" :team-id team_id}) (-> {:message "Invalid team" :team-id team_id} (response/bad-request))))))) (defn wrap-verify-slack-token "Check for a Slack Verification token in the request body and reject the request if it does not match the known verification token." [handler] (let [verification-token (config/config [:slack :verification-token])] (fn [{{:keys [token]} :body-params :as req}] (if (not= token verification-token) (do (timbre/info {:message "Received request with invalid Slack verification token" :token token}) (-> {:message "Not Found"} (response/bad-request))) (handler req))))) (defn wrap-ignore-myself "Ignore Slack Events from the app." [handler] (fn [{{{:keys [user]} :event type :type} :body-params app-user-id :slackbot.slack/app-user-id :as req}] (if (or (not= app-user-id user) (= "url_verification" type)) (handler req) (do (timbre/debug {:message "Ignoring message from myself"}) (-> (response/response nil) (response/status 200)))))) (defn wrap-debug-log-request "Emit the entire request map out as a debug log." [handler] (fn debug-log-request [req] (timbre/debug (with-out-str (pprint/pprint req))) (let [resp (handler req)] (timbre/debug (with-out-str (pprint/pprint resp))) resp)))
true
;; Copyright 2018 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 slackbot.middleware (:import java.io.InputStream java.io.OutputStreamWriter java.io.OutputStream) (:require [clojure.pprint :as pprint] [clojure.walk :as walk] [next.jdbc :as jdbc] [muuntaja.core :as muuntaja] [muuntaja.format.core :as fmt] [muuntaja.middleware] [ring.util.codec :as codec] [ring.util.response :as response] [taoensso.timbre :as timbre] [slackbot.config :as config] [slackbot.database :as db] [slackbot.database.teams :as db.teams])) (defn handle-format-exceptions "Handle Muuntaja formatting exceptions and return a response." [^Exception e fmt _] (timbre/error {:message "Could not format request" :format fmt :error (ex-message e)}) {:status 400 :headers {:content-type "application/json"} :body {:error "Error occurred attempting to format body to Content-Type" :format fmt}}) (defn url-encoder [_] (reify fmt/EncodeToBytes (encode-to-bytes [_ data charset] (.getBytes (codec/form-encode data ^String charset) ^String charset)) fmt/EncodeToOutputStream (encode-to-output-stream [_ data charset] (fn [^OutputStream stream] (.write (OutputStreamWriter. stream ^String charset) ^String (codec/form-encode data charset)))))) (defn url-decoder [_] (reify fmt/Decode (decode [_ data charset] (-> (slurp ^InputStream data :encoding charset) (codec/form-decode ^String charset) (walk/keywordize-keys))))) (defn muuntaja [] (->> {:name "application/x-www-form-urlencoded" :encoder [url-encoder] :decoder [url-decoder]} (fmt/map->Format) (assoc-in muuntaja/default-options [:formats "application/x-www-form-urlencoded"]) (muuntaja/create))) (def muuntaja-cache (memoize muuntaja)) (defn wrap-query-params "Format a query string into a standard Clojure map." [handler] (fn [{:keys [query-string] :as req}] (handler (cond-> req (some? query-string) (assoc :query-params (-> query-string (codec/form-decode) (walk/keywordize-keys))))))) (defn wrap-format "Perform content negotiation based on HTTP header values using Muuntaja." [handler] (let [m (muuntaja-cache)] (-> handler (muuntaja.middleware/wrap-params) (wrap-query-params) (muuntaja.middleware/wrap-format-request m) (muuntaja.middleware/wrap-exception handle-format-exceptions) (muuntaja.middleware/wrap-format-response m) (muuntaja.middleware/wrap-format-negotiate m)))) (defn wrap-supply-tx "Hydrate each request with a database transaction." [handler] (fn [req] (jdbc/with-transaction [tx db/datasource] (->> tx (assoc req :slackbot.database/tx) (handler))))) (defn wrap-supply-slack-details "Pull the Slack Team ID from the request and fetch relevant team details for this request." [handler] (fn [{{:keys [team_id type]} :body-params tx :slackbot.database/tx :as req}] (if-let [{:keys [oauth_access_token PI:KEY:<KEY>END_PI_user_id]} (db.teams/workspace-details tx {:workspace_id team_id})] (-> req (assoc :slackbot.slack/oauth-access-token oauth_access_token) (assoc :slackbot.slack/app-user-id app_user_id) (handler)) (if (= "url_verification" type) (do (timbre/info {:message "Received URL verification request, passing through without team or app user ID" :type type}) (handler req)) (do (timbre/warn {:message "Received request from unregistered team" :team-id team_id}) (-> {:message "Invalid team" :team-id team_id} (response/bad-request))))))) (defn wrap-verify-slack-token "Check for a Slack Verification token in the request body and reject the request if it does not match the known verification token." [handler] (let [verification-token (config/config [:slack :verification-token])] (fn [{{:keys [token]} :body-params :as req}] (if (not= token verification-token) (do (timbre/info {:message "Received request with invalid Slack verification token" :token token}) (-> {:message "Not Found"} (response/bad-request))) (handler req))))) (defn wrap-ignore-myself "Ignore Slack Events from the app." [handler] (fn [{{{:keys [user]} :event type :type} :body-params app-user-id :slackbot.slack/app-user-id :as req}] (if (or (not= app-user-id user) (= "url_verification" type)) (handler req) (do (timbre/debug {:message "Ignoring message from myself"}) (-> (response/response nil) (response/status 200)))))) (defn wrap-debug-log-request "Emit the entire request map out as a debug log." [handler] (fn debug-log-request [req] (timbre/debug (with-out-str (pprint/pprint req))) (let [resp (handler req)] (timbre/debug (with-out-str (pprint/pprint resp))) resp)))
[ { "context": " [clojure.data.json :as json]\n [robert.bruce :refer [try-try-again]])\n (:gen-class))\n\n(def ap", "end": 420, "score": 0.8652188777923584, "start": 408, "tag": "USERNAME", "value": "robert.bruce" }, { "context": "offset offset\n :mailto \"eventdata@crossref.org\"}\n :as :text\n ", "end": 1051, "score": 0.9999005198478699, "start": 1029, "tag": "EMAIL", "value": "eventdata@crossref.org" }, { "context": "\n :mailto \"eventdata@crossref.org\"}\n :as :text})\n bo", "end": 2711, "score": 0.9999033212661743, "start": 2689, "tag": "EMAIL", "value": "eventdata@crossref.org" } ]
src/event_data_landing_page_sampler/sample_crossref.clj
CrossRef/event-data-landing-page-sampler
0
(ns event-data-landing-page-sampler.sample-crossref "Collect a representative sample of DOIs per member from Crossref. As Crossref has an internal sample function, use this to collect random samples." (:require [org.httpkit.client :as client] [event-data-landing-page-sampler.http :as http] [clojure.tools.logging :as log] [clojure.data.json :as json] [robert.bruce :refer [try-try-again]]) (:gen-class)) (def api-base "https://api.crossref.org/") (def member-page-size 1000) (defn all-members "Return a seq of [member-id, num-dois]." ([] (doall (sort-by first (all-members 0)))) ([offset] (try-try-again {:sleep 1000 :tries 5} (fn [] (log/info "Fetch all members, offset" offset) (let [response @(client/get (str api-base "members") {:query-params { :rows member-page-size :offset offset :mailto "eventdata@crossref.org"} :as :text :header http/headers :client http/sni-client}) body (json/read-str (:body response) :key-fn keyword) members (-> body :message :items) ; A potential REST API bug sometimes returns nil for count. ; Default to 1. results (map #(vector (:id %) (or (-> % :counts :total-dois) 1)) members)] (if (empty? results) [] (lazy-cat results (all-members (+ offset member-page-size))))))))) ; We're limited by the REST API to 100. (def max-sample 100) ; Always take at least this many samples. (def min-sample 10) (defn num-samples-per-member "Transform seq of [member-id num-dois] to [member-id num-samples]" [members-and-counts] (let [max-value (apply max (map second members-and-counts)) scale-factor (/ max-sample max-value)] (map #(vector (first %) (max min-sample (int (* scale-factor (second %))))) members-and-counts))) (defn doi-sample-for-member "Return a seq of a sample of [member-id doi] for the member." [[member-id num-samples]] (log/info "Sample " num-samples " DOIs for member" member-id) (try-try-again {:sleep 10000 :tries 5} (fn [] (let [response @(client/get (str api-base "works") {:query-params {:sample num-samples :select "DOI" :filter (str "member:" member-id) :mailto "eventdata@crossref.org"} :as :text}) body (json/read-str (:body response) :key-fn keyword) works (-> body :message :items) dois (map :DOI works)] (map #(vector member-id %) dois))))) (defn sample-all "Return a randomly shuffled sample of [member-id, doi] for all members." [] (let [; Order doesn't matter, so sort by member ID so we know how far we are through the job. members-and-counts (sort-by first (all-members)) members-and-samples (num-samples-per-member members-and-counts) doi-sets (pmap doi-sample-for-member members-and-samples) dois (mapcat identity doi-sets) shuffled (shuffle dois)] shuffled))
6024
(ns event-data-landing-page-sampler.sample-crossref "Collect a representative sample of DOIs per member from Crossref. As Crossref has an internal sample function, use this to collect random samples." (:require [org.httpkit.client :as client] [event-data-landing-page-sampler.http :as http] [clojure.tools.logging :as log] [clojure.data.json :as json] [robert.bruce :refer [try-try-again]]) (:gen-class)) (def api-base "https://api.crossref.org/") (def member-page-size 1000) (defn all-members "Return a seq of [member-id, num-dois]." ([] (doall (sort-by first (all-members 0)))) ([offset] (try-try-again {:sleep 1000 :tries 5} (fn [] (log/info "Fetch all members, offset" offset) (let [response @(client/get (str api-base "members") {:query-params { :rows member-page-size :offset offset :mailto "<EMAIL>"} :as :text :header http/headers :client http/sni-client}) body (json/read-str (:body response) :key-fn keyword) members (-> body :message :items) ; A potential REST API bug sometimes returns nil for count. ; Default to 1. results (map #(vector (:id %) (or (-> % :counts :total-dois) 1)) members)] (if (empty? results) [] (lazy-cat results (all-members (+ offset member-page-size))))))))) ; We're limited by the REST API to 100. (def max-sample 100) ; Always take at least this many samples. (def min-sample 10) (defn num-samples-per-member "Transform seq of [member-id num-dois] to [member-id num-samples]" [members-and-counts] (let [max-value (apply max (map second members-and-counts)) scale-factor (/ max-sample max-value)] (map #(vector (first %) (max min-sample (int (* scale-factor (second %))))) members-and-counts))) (defn doi-sample-for-member "Return a seq of a sample of [member-id doi] for the member." [[member-id num-samples]] (log/info "Sample " num-samples " DOIs for member" member-id) (try-try-again {:sleep 10000 :tries 5} (fn [] (let [response @(client/get (str api-base "works") {:query-params {:sample num-samples :select "DOI" :filter (str "member:" member-id) :mailto "<EMAIL>"} :as :text}) body (json/read-str (:body response) :key-fn keyword) works (-> body :message :items) dois (map :DOI works)] (map #(vector member-id %) dois))))) (defn sample-all "Return a randomly shuffled sample of [member-id, doi] for all members." [] (let [; Order doesn't matter, so sort by member ID so we know how far we are through the job. members-and-counts (sort-by first (all-members)) members-and-samples (num-samples-per-member members-and-counts) doi-sets (pmap doi-sample-for-member members-and-samples) dois (mapcat identity doi-sets) shuffled (shuffle dois)] shuffled))
true
(ns event-data-landing-page-sampler.sample-crossref "Collect a representative sample of DOIs per member from Crossref. As Crossref has an internal sample function, use this to collect random samples." (:require [org.httpkit.client :as client] [event-data-landing-page-sampler.http :as http] [clojure.tools.logging :as log] [clojure.data.json :as json] [robert.bruce :refer [try-try-again]]) (:gen-class)) (def api-base "https://api.crossref.org/") (def member-page-size 1000) (defn all-members "Return a seq of [member-id, num-dois]." ([] (doall (sort-by first (all-members 0)))) ([offset] (try-try-again {:sleep 1000 :tries 5} (fn [] (log/info "Fetch all members, offset" offset) (let [response @(client/get (str api-base "members") {:query-params { :rows member-page-size :offset offset :mailto "PI:EMAIL:<EMAIL>END_PI"} :as :text :header http/headers :client http/sni-client}) body (json/read-str (:body response) :key-fn keyword) members (-> body :message :items) ; A potential REST API bug sometimes returns nil for count. ; Default to 1. results (map #(vector (:id %) (or (-> % :counts :total-dois) 1)) members)] (if (empty? results) [] (lazy-cat results (all-members (+ offset member-page-size))))))))) ; We're limited by the REST API to 100. (def max-sample 100) ; Always take at least this many samples. (def min-sample 10) (defn num-samples-per-member "Transform seq of [member-id num-dois] to [member-id num-samples]" [members-and-counts] (let [max-value (apply max (map second members-and-counts)) scale-factor (/ max-sample max-value)] (map #(vector (first %) (max min-sample (int (* scale-factor (second %))))) members-and-counts))) (defn doi-sample-for-member "Return a seq of a sample of [member-id doi] for the member." [[member-id num-samples]] (log/info "Sample " num-samples " DOIs for member" member-id) (try-try-again {:sleep 10000 :tries 5} (fn [] (let [response @(client/get (str api-base "works") {:query-params {:sample num-samples :select "DOI" :filter (str "member:" member-id) :mailto "PI:EMAIL:<EMAIL>END_PI"} :as :text}) body (json/read-str (:body response) :key-fn keyword) works (-> body :message :items) dois (map :DOI works)] (map #(vector member-id %) dois))))) (defn sample-all "Return a randomly shuffled sample of [member-id, doi] for all members." [] (let [; Order doesn't matter, so sort by member ID so we know how far we are through the job. members-and-counts (sort-by first (all-members)) members-and-samples (num-samples-per-member members-and-counts) doi-sets (pmap doi-sample-for-member members-and-samples) dois (mapcat identity doi-sets) shuffled (shuffle dois)] shuffled))
[ { "context": "tr \"ID\")\n(def titlestr \"OTSIKKO\")\n(def authorstr \"TEKIJÄ\")\n(def yearstr \"VUOSI\")\n(def greetingstr \"Tervetu", "end": 399, "score": 0.9989849925041199, "start": 393, "tag": "NAME", "value": "TEKIJÄ" }, { "context": "int-entries))\n (.setText result-field \"Anna ainakin kirjan nimi!\"))))))\n\n(defn delete-entry []\n (let [id (.ge", "end": 3784, "score": 0.6507946252822876, "start": 3765, "tag": "NAME", "value": "na ainakin kirjan n" } ]
src/kirjakanta/ui.clj
otjura/kirjakanta
0
(ns kirjakanta.ui (:gen-class) (:require [kirjakanta.db :as db] [clojure.pprint :as pprint]) (:import [javax.swing JFrame JPanel JLabel JButton JTextField JTextArea] [java.awt.event ActionListener] [java.awt GridLayout])) (declare print-entries add-entry delete-entry edit-entry reset-fields) (def idstr "ID") (def titlestr "OTSIKKO") (def authorstr "TEKIJÄ") (def yearstr "VUOSI") (def greetingstr "Tervetuloa Kirjakantaan!") (def ok-button (JButton. "Valmis")) (def result-label (JLabel. "Tulos:")) (def result-field (JTextArea. greetingstr 10 40)) ; rows cols (def id-label (JLabel. idstr)) (def id-field (JTextField. "" 20)) ; default-txt cols (def title-label (JLabel. titlestr)) (def title-field (JTextField. "" 20)) (def author-label (JLabel. authorstr)) (def author-field (JTextField. "" 20)) (def year-label (JLabel. yearstr)) (def year-field (JTextField. "" 20)) (def query-button (doto (JButton. "Kysely"); JButton buttonque = new JButton("Kysely") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (print-entries)))))) (def add-button (doto (JButton. "Lisää") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (add-entry)))))) (def delete-button (doto (JButton. "Poista") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (delete-entry)))))) (def edit-button (doto (JButton. "Muokkaa") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (edit-entry)))))) ; Specifying the number of columns affects the layout only when the number of rows is set to zero (def input-panel (doto (JPanel. (new GridLayout 0 2 10 10)) (.add id-label) (.add id-field) (.add title-label) (.add title-field) (.add author-label) (.add author-field) (.add year-label) (.add year-field))) (def control-panel (doto (JPanel. (new GridLayout 0 4 10 10)) (.add query-button) (.add add-button) (.add delete-button) (.add edit-button) (.add ok-button))) (def view-panel (doto (JPanel.) (.add result-label) (.add result-field) (.add input-panel) (.add control-panel))) (defn kantaview [] (doto (JFrame. "Kirjakanta") (.setContentPane view-panel) (.setSize 640 400) ; golden ratio is 640 400 (.setResizable true) (.setDefaultCloseOperation (JFrame/EXIT_ON_CLOSE)) (.setVisible true))) (defn print-entries [] (.setText result-field (db/pprint-sql (db/query db/allq)))) (defn add-entry [] (let [title (.getText title-field) author (.getText author-field) year (.getText year-field)] (if-not (and (= title titlestr) (= author authorstr) (= year yearstr)) (do (db/add-entry title author year) (reset-fields) (print-entries)) (if-not (and (= title titlestr) (= author authorstr)) (do (db/add-entry title author) (reset-fields) (print-entries)) (if-not (and (= title titlestr)) (do (db/add-entry title) (reset-fields) (print-entries)) (.setText result-field "Anna ainakin kirjan nimi!")))))) (defn delete-entry [] (let [id (.getText id-field)] (if-not (= id idstr) (do (db/delete-entry id) (reset-fields) (print-entries)) (.setText result-field "Anna teoksen ID jonka haluat poistaa!")))) (defn edit-entry [] (let [id (.getText id-field)] (if (= id idstr) (.setText result-field (pprint/cl-format nil "Anna ID ja muokkaa haluamiasi kenttiä alla!~%Muokattuasi tietoja paina Valmis-painiketta tallentaaksesi!")) (let [info (first (db/get-by-id id)) id2 (str (first info)) title (str (first (rest info))) author (str (first (rest (rest info)))) year (str (first (rest (rest (rest info)))))] (.setText id-field id2) (.setText title-field title) (.setText author-field author) (.setText year-field year) (.addActionListener ok-button (proxy [ActionListener] [] (actionPerformed [e] ;TODO FIX gets old values for some reason on second OK (do (if-not (or (= title (.getText title-field)) (= title titlestr)) (db/edit-entry id 1 (.getText title-field))) (if-not (or (= author (.getText author-field)) (= author authorstr)) (db/edit-entry id 2 (.getText author-field))) (if-not (or (= year (.getText year-field)) (= year yearstr)) (db/edit-entry id 3 (.getText year-field))) (reset-fields) (print-entries))))))))) (defn reset-fields [] (.setText id-field "") (.setText title-field "") (.setText author-field "") (.setText year-field ""))
25525
(ns kirjakanta.ui (:gen-class) (:require [kirjakanta.db :as db] [clojure.pprint :as pprint]) (:import [javax.swing JFrame JPanel JLabel JButton JTextField JTextArea] [java.awt.event ActionListener] [java.awt GridLayout])) (declare print-entries add-entry delete-entry edit-entry reset-fields) (def idstr "ID") (def titlestr "OTSIKKO") (def authorstr "<NAME>") (def yearstr "VUOSI") (def greetingstr "Tervetuloa Kirjakantaan!") (def ok-button (JButton. "Valmis")) (def result-label (JLabel. "Tulos:")) (def result-field (JTextArea. greetingstr 10 40)) ; rows cols (def id-label (JLabel. idstr)) (def id-field (JTextField. "" 20)) ; default-txt cols (def title-label (JLabel. titlestr)) (def title-field (JTextField. "" 20)) (def author-label (JLabel. authorstr)) (def author-field (JTextField. "" 20)) (def year-label (JLabel. yearstr)) (def year-field (JTextField. "" 20)) (def query-button (doto (JButton. "Kysely"); JButton buttonque = new JButton("Kysely") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (print-entries)))))) (def add-button (doto (JButton. "Lisää") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (add-entry)))))) (def delete-button (doto (JButton. "Poista") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (delete-entry)))))) (def edit-button (doto (JButton. "Muokkaa") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (edit-entry)))))) ; Specifying the number of columns affects the layout only when the number of rows is set to zero (def input-panel (doto (JPanel. (new GridLayout 0 2 10 10)) (.add id-label) (.add id-field) (.add title-label) (.add title-field) (.add author-label) (.add author-field) (.add year-label) (.add year-field))) (def control-panel (doto (JPanel. (new GridLayout 0 4 10 10)) (.add query-button) (.add add-button) (.add delete-button) (.add edit-button) (.add ok-button))) (def view-panel (doto (JPanel.) (.add result-label) (.add result-field) (.add input-panel) (.add control-panel))) (defn kantaview [] (doto (JFrame. "Kirjakanta") (.setContentPane view-panel) (.setSize 640 400) ; golden ratio is 640 400 (.setResizable true) (.setDefaultCloseOperation (JFrame/EXIT_ON_CLOSE)) (.setVisible true))) (defn print-entries [] (.setText result-field (db/pprint-sql (db/query db/allq)))) (defn add-entry [] (let [title (.getText title-field) author (.getText author-field) year (.getText year-field)] (if-not (and (= title titlestr) (= author authorstr) (= year yearstr)) (do (db/add-entry title author year) (reset-fields) (print-entries)) (if-not (and (= title titlestr) (= author authorstr)) (do (db/add-entry title author) (reset-fields) (print-entries)) (if-not (and (= title titlestr)) (do (db/add-entry title) (reset-fields) (print-entries)) (.setText result-field "An<NAME>imi!")))))) (defn delete-entry [] (let [id (.getText id-field)] (if-not (= id idstr) (do (db/delete-entry id) (reset-fields) (print-entries)) (.setText result-field "Anna teoksen ID jonka haluat poistaa!")))) (defn edit-entry [] (let [id (.getText id-field)] (if (= id idstr) (.setText result-field (pprint/cl-format nil "Anna ID ja muokkaa haluamiasi kenttiä alla!~%Muokattuasi tietoja paina Valmis-painiketta tallentaaksesi!")) (let [info (first (db/get-by-id id)) id2 (str (first info)) title (str (first (rest info))) author (str (first (rest (rest info)))) year (str (first (rest (rest (rest info)))))] (.setText id-field id2) (.setText title-field title) (.setText author-field author) (.setText year-field year) (.addActionListener ok-button (proxy [ActionListener] [] (actionPerformed [e] ;TODO FIX gets old values for some reason on second OK (do (if-not (or (= title (.getText title-field)) (= title titlestr)) (db/edit-entry id 1 (.getText title-field))) (if-not (or (= author (.getText author-field)) (= author authorstr)) (db/edit-entry id 2 (.getText author-field))) (if-not (or (= year (.getText year-field)) (= year yearstr)) (db/edit-entry id 3 (.getText year-field))) (reset-fields) (print-entries))))))))) (defn reset-fields [] (.setText id-field "") (.setText title-field "") (.setText author-field "") (.setText year-field ""))
true
(ns kirjakanta.ui (:gen-class) (:require [kirjakanta.db :as db] [clojure.pprint :as pprint]) (:import [javax.swing JFrame JPanel JLabel JButton JTextField JTextArea] [java.awt.event ActionListener] [java.awt GridLayout])) (declare print-entries add-entry delete-entry edit-entry reset-fields) (def idstr "ID") (def titlestr "OTSIKKO") (def authorstr "PI:NAME:<NAME>END_PI") (def yearstr "VUOSI") (def greetingstr "Tervetuloa Kirjakantaan!") (def ok-button (JButton. "Valmis")) (def result-label (JLabel. "Tulos:")) (def result-field (JTextArea. greetingstr 10 40)) ; rows cols (def id-label (JLabel. idstr)) (def id-field (JTextField. "" 20)) ; default-txt cols (def title-label (JLabel. titlestr)) (def title-field (JTextField. "" 20)) (def author-label (JLabel. authorstr)) (def author-field (JTextField. "" 20)) (def year-label (JLabel. yearstr)) (def year-field (JTextField. "" 20)) (def query-button (doto (JButton. "Kysely"); JButton buttonque = new JButton("Kysely") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (print-entries)))))) (def add-button (doto (JButton. "Lisää") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (add-entry)))))) (def delete-button (doto (JButton. "Poista") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (delete-entry)))))) (def edit-button (doto (JButton. "Muokkaa") (.addActionListener (proxy [ActionListener] [] (actionPerformed [e] (edit-entry)))))) ; Specifying the number of columns affects the layout only when the number of rows is set to zero (def input-panel (doto (JPanel. (new GridLayout 0 2 10 10)) (.add id-label) (.add id-field) (.add title-label) (.add title-field) (.add author-label) (.add author-field) (.add year-label) (.add year-field))) (def control-panel (doto (JPanel. (new GridLayout 0 4 10 10)) (.add query-button) (.add add-button) (.add delete-button) (.add edit-button) (.add ok-button))) (def view-panel (doto (JPanel.) (.add result-label) (.add result-field) (.add input-panel) (.add control-panel))) (defn kantaview [] (doto (JFrame. "Kirjakanta") (.setContentPane view-panel) (.setSize 640 400) ; golden ratio is 640 400 (.setResizable true) (.setDefaultCloseOperation (JFrame/EXIT_ON_CLOSE)) (.setVisible true))) (defn print-entries [] (.setText result-field (db/pprint-sql (db/query db/allq)))) (defn add-entry [] (let [title (.getText title-field) author (.getText author-field) year (.getText year-field)] (if-not (and (= title titlestr) (= author authorstr) (= year yearstr)) (do (db/add-entry title author year) (reset-fields) (print-entries)) (if-not (and (= title titlestr) (= author authorstr)) (do (db/add-entry title author) (reset-fields) (print-entries)) (if-not (and (= title titlestr)) (do (db/add-entry title) (reset-fields) (print-entries)) (.setText result-field "AnPI:NAME:<NAME>END_PIimi!")))))) (defn delete-entry [] (let [id (.getText id-field)] (if-not (= id idstr) (do (db/delete-entry id) (reset-fields) (print-entries)) (.setText result-field "Anna teoksen ID jonka haluat poistaa!")))) (defn edit-entry [] (let [id (.getText id-field)] (if (= id idstr) (.setText result-field (pprint/cl-format nil "Anna ID ja muokkaa haluamiasi kenttiä alla!~%Muokattuasi tietoja paina Valmis-painiketta tallentaaksesi!")) (let [info (first (db/get-by-id id)) id2 (str (first info)) title (str (first (rest info))) author (str (first (rest (rest info)))) year (str (first (rest (rest (rest info)))))] (.setText id-field id2) (.setText title-field title) (.setText author-field author) (.setText year-field year) (.addActionListener ok-button (proxy [ActionListener] [] (actionPerformed [e] ;TODO FIX gets old values for some reason on second OK (do (if-not (or (= title (.getText title-field)) (= title titlestr)) (db/edit-entry id 1 (.getText title-field))) (if-not (or (= author (.getText author-field)) (= author authorstr)) (db/edit-entry id 2 (.getText author-field))) (if-not (or (= year (.getText year-field)) (= year yearstr)) (db/edit-entry id 3 (.getText year-field))) (reset-fields) (print-entries))))))))) (defn reset-fields [] (.setText id-field "") (.setText title-field "") (.setText author-field "") (.setText year-field ""))
[ { "context": "ers\" [\"*\"] {})\n ;; remove chriscourier@test.com\n (remove #(in? [\"9eadx6i", "end": 2331, "score": 0.9999069571495056, "start": 2310, "tag": "EMAIL", "value": "chriscourier@test.com" }, { "context": "'Content-Type: application/json' -H 'Cookie: token=YfZmnG0hqYlC5opndFasR1lvWzQKRFM7pwFk6wZdMnPE29yodw", "end": 8681, "score": 0.4383067190647125, "start": 8681, "tag": "KEY", "value": "" }, { "context": "Content-Type: application/json' -H 'Cookie: token=YfZmnG0hqYlC5opndFasR1lvWzQKRFM7pwFk6wZdMnPE29yodw8ANVCR0exmk8kmSV7Zcto27yzKttp8nstjDLWu47iejts4dyiwBKVb9ejCP6wRbE8eo04frtGPEGjL; user-id=BCzKBHrWlJz9fddj7Xmc' -d '{\"user\": {\"id\"", "end": 8810, "score": 0.8938677906990051, "start": 8682, "tag": "KEY", "value": "YfZmnG0hqYlC5opndFasR1lvWzQKRFM7pwFk6wZdMnPE29yodw8ANVCR0exmk8kmSV7Zcto27yzKttp8nstjDLWu47iejts4dyiwBKVb9ejCP6wRbE8eo04frtGPEGjL" }, { "context": "b9ejCP6wRbE8eo04frtGPEGjL; user-id=BCzKBHrWlJz9fddj7Xmc' -d '{\"user\": {\"id\":\"IVN6rQbtkJiifeRXSFXd\"}}'", "end": 8836, "score": 0.53351229429245, "start": 8835, "tag": "KEY", "value": "j" } ]
src/dashboard/users.clj
Purple-Services/dashboard-service
3
(ns dashboard.users (:require [bouncer.core :as b] [bouncer.validators :as v] [clojure.edn :as edn] [clojure.set :refer [join]] [clojure.string :as s] [crypto.password.bcrypt :as bcrypt] [common.db :refer [mysql-escape-str !select !update !insert]] [common.users :refer [send-push get-user-by-id]] [common.util :refer [in? sns-publish sns-client]] [dashboard.utils :refer [append-to-admin-event-log]])) (def users-select [:id :name :email :phone_number :os :app_version :stripe_default_card :stripe_cards :sift_score :arn_endpoint :timestamp_created :referral_gallons :admin_event_log :subscription_id :referral_code :is_courier :type]) (defn process-admin-log [log admins] (let [edn-log (edn/read-string log) admin-ids (filter (comp not nil?) (distinct (map :admin_id edn-log))) get-admin (fn [a] (first (filter #(= (:id %) a) admins)))] (into [] (map #(assoc % :admin_email (:email (get-admin (:admin_id %)))) edn-log)))) (defn process-user "Process a user to be included as a JSON response" [user admins db-conn] (let [orders-count (:total (first (!select db-conn "orders" ["count(*) as total"] {:user_id (:id user)}))) last-active (:target_time_start (first (!select db-conn "orders" [:target_time_start] {:user_id (:id user)} :append "ORDER BY target_time_start DESC LIMIT 1" )))] (assoc user :timestamp_created (/ (.getTime (:timestamp_created user)) 1000) :admin_event_log (process-admin-log (:admin_event_log user) admins) :orders_count orders-count :last_active last-active))) (defn dash-users "Return all users who are either couriers or a user who has placed an order" [db-conn] (let [all-couriers (->> (!select db-conn "couriers" ["*"] {}) ;; remove chriscourier@test.com (remove #(in? ["9eadx6i2wCCjUI1leBBr"] (:id %)))) couriers-by-id (into {} (map (juxt (comp keyword :id) identity) all-couriers)) courier-ids (distinct (map :id all-couriers)) recent-orders (!select db-conn "orders" ["*"] {} :append " LIMIT 100") users (!select db-conn "users" users-select {} :custom-where (let [customer-ids (distinct (map :user_id recent-orders))] (str "id IN (\"" (s/join "\",\"" (distinct (concat customer-ids courier-ids))) "\")"))) admins (!select db-conn "dashboard_users" [:email :id] {})] (map #(process-user % admins db-conn) users))) (defn send-push-to-all-active-users [db-conn message] (do (future (run! #(send-push db-conn (:id %) message) (!select db-conn "ActiveUsers" [:id :name] {}))) {:success true})) (defn send-push-to-table-view "Send push notifications to all users in mySQL view-table. Assumes that the view will have an arn_enpoint column." [db-conn message table-view] (do (future (run! #(sns-publish sns-client (:arn_endpoint %) message) (!select db-conn table-view [:arn_endpoint] {}))) {:success true :message (str "You sent " message " to " table-view)})) (defn send-push-to-users-list [db-conn message user-ids] (do (future (run! #(send-push db-conn (:id %) message) (!select db-conn "users" [:id :name] {} :custom-where (str "id IN (\"" (->> user-ids (map mysql-escape-str) (interpose "\",\"") (apply str)) "\")")))) {:success true})) (defn send-push-to-user [db-conn message user-id] (do (future (run! #(send-push db-conn (:id %) message) (!select db-conn "users" [:id :name] {} :custom-where (str "id IN (\"" (->> user-id (mysql-escape-str) (apply str)) "\")")))) {:success true})) (defn search-users "Search users by term" [db-conn term] (let [escaped-term (mysql-escape-str term) phone-number-term (-> term (s/replace #"-|\(|\)" "") mysql-escape-str) admins (!select db-conn "dashboard_users" [:email :id] {}) users (!select db-conn "users" users-select {} :custom-where (str "`id` LIKE '%" escaped-term "%' " "OR `name` LIKE '%" escaped-term "%' " "OR `phone_number` LIKE '%" phone-number-term "%' " "OR `email` LIKE '%" escaped-term "%' " "OR `referral_code` LIKE '%" escaped-term "%'") :append "ORDER BY timestamp_created LIMIT 100")] (map #(process-user % admins db-conn) users))) (def user-validations {:referral_gallons [ [v/number :message "Referral gallons must be a number"] [v/in-range [0 50000] :message "Must be within 0 and 50,000 referral gallons"] ]}) (defn update-user! "Given a user map, validate it. If valid, update user else return the bouncer error map" [db-conn user] (if (b/valid? user user-validations) (let [{:keys [admin_id referral_comment referral_gallons id]} user db-user (dissoc (get-user-by-id db-conn id) :account_manager_id) update-result (!update db-conn "users" {:referral_gallons referral_gallons} {:id (:id db-user)})] (if (:success update-result) (do ;; update the log (!update db-conn "users" (append-to-admin-event-log {:admin_event_log (:admin_event_log db-user)} :admin-id admin_id :action "adjust_referral_gallons" :comment (or referral_comment "") :previous-value (:referral_gallons db-user) :new-value referral_gallons) {:id (:id db-user)}) (assoc update-result :id (:id db-user))) ;; update that there was a failure (do ;; update the log (!update db-conn "users" (append-to-admin-event-log {:admin_event_log (:admin_event_log db-user)} :admin-id admin_id :action "adjust_referral_gallons" :comment "There was a failure updating gallons" :previous-value (:referral_gallons db-user) :new-value referral_gallons) {:id (:id db-user)}) (assoc update-result :id (:id db-user))))) {:success false :validation (b/validate user user-validations)})) ;; this is how to get the table views with arn_endpoint ;; SELECT c.table_name FROM INFORMATION_SCHEMA.COLUMNS c INNER JOIN (SELECT table_name,table_type FROM information_schema.tables where table_schema = 'ebdb_prod' AND table_type = 'view') t ON c.table_name = t.table_name WHERE COLUMN_NAME IN ('arn_endpoint') AND TABLE_SCHEMA='ebdb_prod' ; ;;curl 'http://localhost:3001/users/convert-to-courier' -X PUT -H 'Content-Type: application/json' -H 'Cookie: token=YfZmnG0hqYlC5opndFasR1lvWzQKRFM7pwFk6wZdMnPE29yodw8ANVCR0exmk8kmSV7Zcto27yzKttp8nstjDLWu47iejts4dyiwBKVb9ejCP6wRbE8eo04frtGPEGjL; user-id=BCzKBHrWlJz9fddj7Xmc' -d '{"user": {"id":"IVN6rQbtkJiifeRXSFXd"}}' (defn convert-to-courier! "Convert a user to a courier. This creates a courier account" [db-conn user] (let [{:keys [id]} user current-user (first (!select db-conn "users" users-select {:id (:id user)})) is-native? (boolean (= (:type current-user) "native"))] (cond (not is-native?) {:success false :message (str "This user registered with " (:type current-user) ". " "They must register through the app using an email " "address in order to be a courier.")} (> (:total (first (!select db-conn "orders" ["count(*) as total"] {:user_id (:id user)}))) 0) {:success false :message (str "This user already has already made order requests as " "a customer! A courier can not have any fuel delivery " "requests. They will need to create another user " "account with an email address that is different from " "their customer account.")} :else (let [new-courier-result (!insert db-conn "couriers" {:id id :active 1 :busy 0 :lat 0 :lng 0 :zones ""}) set-is-courier-result (!update db-conn "users" {:is_courier 1} {:id id})] (cond (and (:success new-courier-result) (:success set-is-courier-result)) {:success true :message "User successfully converted to a courier."} (not (:success set-is-courier-result)) {:success false :message "User could not be updated"} (not (:success new-courier-result)) {:success false :message "Courier account could not be created"} :else {:success false :message "Unknown error occured"})))))
3621
(ns dashboard.users (:require [bouncer.core :as b] [bouncer.validators :as v] [clojure.edn :as edn] [clojure.set :refer [join]] [clojure.string :as s] [crypto.password.bcrypt :as bcrypt] [common.db :refer [mysql-escape-str !select !update !insert]] [common.users :refer [send-push get-user-by-id]] [common.util :refer [in? sns-publish sns-client]] [dashboard.utils :refer [append-to-admin-event-log]])) (def users-select [:id :name :email :phone_number :os :app_version :stripe_default_card :stripe_cards :sift_score :arn_endpoint :timestamp_created :referral_gallons :admin_event_log :subscription_id :referral_code :is_courier :type]) (defn process-admin-log [log admins] (let [edn-log (edn/read-string log) admin-ids (filter (comp not nil?) (distinct (map :admin_id edn-log))) get-admin (fn [a] (first (filter #(= (:id %) a) admins)))] (into [] (map #(assoc % :admin_email (:email (get-admin (:admin_id %)))) edn-log)))) (defn process-user "Process a user to be included as a JSON response" [user admins db-conn] (let [orders-count (:total (first (!select db-conn "orders" ["count(*) as total"] {:user_id (:id user)}))) last-active (:target_time_start (first (!select db-conn "orders" [:target_time_start] {:user_id (:id user)} :append "ORDER BY target_time_start DESC LIMIT 1" )))] (assoc user :timestamp_created (/ (.getTime (:timestamp_created user)) 1000) :admin_event_log (process-admin-log (:admin_event_log user) admins) :orders_count orders-count :last_active last-active))) (defn dash-users "Return all users who are either couriers or a user who has placed an order" [db-conn] (let [all-couriers (->> (!select db-conn "couriers" ["*"] {}) ;; remove <EMAIL> (remove #(in? ["9eadx6i2wCCjUI1leBBr"] (:id %)))) couriers-by-id (into {} (map (juxt (comp keyword :id) identity) all-couriers)) courier-ids (distinct (map :id all-couriers)) recent-orders (!select db-conn "orders" ["*"] {} :append " LIMIT 100") users (!select db-conn "users" users-select {} :custom-where (let [customer-ids (distinct (map :user_id recent-orders))] (str "id IN (\"" (s/join "\",\"" (distinct (concat customer-ids courier-ids))) "\")"))) admins (!select db-conn "dashboard_users" [:email :id] {})] (map #(process-user % admins db-conn) users))) (defn send-push-to-all-active-users [db-conn message] (do (future (run! #(send-push db-conn (:id %) message) (!select db-conn "ActiveUsers" [:id :name] {}))) {:success true})) (defn send-push-to-table-view "Send push notifications to all users in mySQL view-table. Assumes that the view will have an arn_enpoint column." [db-conn message table-view] (do (future (run! #(sns-publish sns-client (:arn_endpoint %) message) (!select db-conn table-view [:arn_endpoint] {}))) {:success true :message (str "You sent " message " to " table-view)})) (defn send-push-to-users-list [db-conn message user-ids] (do (future (run! #(send-push db-conn (:id %) message) (!select db-conn "users" [:id :name] {} :custom-where (str "id IN (\"" (->> user-ids (map mysql-escape-str) (interpose "\",\"") (apply str)) "\")")))) {:success true})) (defn send-push-to-user [db-conn message user-id] (do (future (run! #(send-push db-conn (:id %) message) (!select db-conn "users" [:id :name] {} :custom-where (str "id IN (\"" (->> user-id (mysql-escape-str) (apply str)) "\")")))) {:success true})) (defn search-users "Search users by term" [db-conn term] (let [escaped-term (mysql-escape-str term) phone-number-term (-> term (s/replace #"-|\(|\)" "") mysql-escape-str) admins (!select db-conn "dashboard_users" [:email :id] {}) users (!select db-conn "users" users-select {} :custom-where (str "`id` LIKE '%" escaped-term "%' " "OR `name` LIKE '%" escaped-term "%' " "OR `phone_number` LIKE '%" phone-number-term "%' " "OR `email` LIKE '%" escaped-term "%' " "OR `referral_code` LIKE '%" escaped-term "%'") :append "ORDER BY timestamp_created LIMIT 100")] (map #(process-user % admins db-conn) users))) (def user-validations {:referral_gallons [ [v/number :message "Referral gallons must be a number"] [v/in-range [0 50000] :message "Must be within 0 and 50,000 referral gallons"] ]}) (defn update-user! "Given a user map, validate it. If valid, update user else return the bouncer error map" [db-conn user] (if (b/valid? user user-validations) (let [{:keys [admin_id referral_comment referral_gallons id]} user db-user (dissoc (get-user-by-id db-conn id) :account_manager_id) update-result (!update db-conn "users" {:referral_gallons referral_gallons} {:id (:id db-user)})] (if (:success update-result) (do ;; update the log (!update db-conn "users" (append-to-admin-event-log {:admin_event_log (:admin_event_log db-user)} :admin-id admin_id :action "adjust_referral_gallons" :comment (or referral_comment "") :previous-value (:referral_gallons db-user) :new-value referral_gallons) {:id (:id db-user)}) (assoc update-result :id (:id db-user))) ;; update that there was a failure (do ;; update the log (!update db-conn "users" (append-to-admin-event-log {:admin_event_log (:admin_event_log db-user)} :admin-id admin_id :action "adjust_referral_gallons" :comment "There was a failure updating gallons" :previous-value (:referral_gallons db-user) :new-value referral_gallons) {:id (:id db-user)}) (assoc update-result :id (:id db-user))))) {:success false :validation (b/validate user user-validations)})) ;; this is how to get the table views with arn_endpoint ;; SELECT c.table_name FROM INFORMATION_SCHEMA.COLUMNS c INNER JOIN (SELECT table_name,table_type FROM information_schema.tables where table_schema = 'ebdb_prod' AND table_type = 'view') t ON c.table_name = t.table_name WHERE COLUMN_NAME IN ('arn_endpoint') AND TABLE_SCHEMA='ebdb_prod' ; ;;curl 'http://localhost:3001/users/convert-to-courier' -X PUT -H 'Content-Type: application/json' -H 'Cookie: token<KEY>=<KEY>; user-id=BCzKBHrWlJz9fdd<KEY>7Xmc' -d '{"user": {"id":"IVN6rQbtkJiifeRXSFXd"}}' (defn convert-to-courier! "Convert a user to a courier. This creates a courier account" [db-conn user] (let [{:keys [id]} user current-user (first (!select db-conn "users" users-select {:id (:id user)})) is-native? (boolean (= (:type current-user) "native"))] (cond (not is-native?) {:success false :message (str "This user registered with " (:type current-user) ". " "They must register through the app using an email " "address in order to be a courier.")} (> (:total (first (!select db-conn "orders" ["count(*) as total"] {:user_id (:id user)}))) 0) {:success false :message (str "This user already has already made order requests as " "a customer! A courier can not have any fuel delivery " "requests. They will need to create another user " "account with an email address that is different from " "their customer account.")} :else (let [new-courier-result (!insert db-conn "couriers" {:id id :active 1 :busy 0 :lat 0 :lng 0 :zones ""}) set-is-courier-result (!update db-conn "users" {:is_courier 1} {:id id})] (cond (and (:success new-courier-result) (:success set-is-courier-result)) {:success true :message "User successfully converted to a courier."} (not (:success set-is-courier-result)) {:success false :message "User could not be updated"} (not (:success new-courier-result)) {:success false :message "Courier account could not be created"} :else {:success false :message "Unknown error occured"})))))
true
(ns dashboard.users (:require [bouncer.core :as b] [bouncer.validators :as v] [clojure.edn :as edn] [clojure.set :refer [join]] [clojure.string :as s] [crypto.password.bcrypt :as bcrypt] [common.db :refer [mysql-escape-str !select !update !insert]] [common.users :refer [send-push get-user-by-id]] [common.util :refer [in? sns-publish sns-client]] [dashboard.utils :refer [append-to-admin-event-log]])) (def users-select [:id :name :email :phone_number :os :app_version :stripe_default_card :stripe_cards :sift_score :arn_endpoint :timestamp_created :referral_gallons :admin_event_log :subscription_id :referral_code :is_courier :type]) (defn process-admin-log [log admins] (let [edn-log (edn/read-string log) admin-ids (filter (comp not nil?) (distinct (map :admin_id edn-log))) get-admin (fn [a] (first (filter #(= (:id %) a) admins)))] (into [] (map #(assoc % :admin_email (:email (get-admin (:admin_id %)))) edn-log)))) (defn process-user "Process a user to be included as a JSON response" [user admins db-conn] (let [orders-count (:total (first (!select db-conn "orders" ["count(*) as total"] {:user_id (:id user)}))) last-active (:target_time_start (first (!select db-conn "orders" [:target_time_start] {:user_id (:id user)} :append "ORDER BY target_time_start DESC LIMIT 1" )))] (assoc user :timestamp_created (/ (.getTime (:timestamp_created user)) 1000) :admin_event_log (process-admin-log (:admin_event_log user) admins) :orders_count orders-count :last_active last-active))) (defn dash-users "Return all users who are either couriers or a user who has placed an order" [db-conn] (let [all-couriers (->> (!select db-conn "couriers" ["*"] {}) ;; remove PI:EMAIL:<EMAIL>END_PI (remove #(in? ["9eadx6i2wCCjUI1leBBr"] (:id %)))) couriers-by-id (into {} (map (juxt (comp keyword :id) identity) all-couriers)) courier-ids (distinct (map :id all-couriers)) recent-orders (!select db-conn "orders" ["*"] {} :append " LIMIT 100") users (!select db-conn "users" users-select {} :custom-where (let [customer-ids (distinct (map :user_id recent-orders))] (str "id IN (\"" (s/join "\",\"" (distinct (concat customer-ids courier-ids))) "\")"))) admins (!select db-conn "dashboard_users" [:email :id] {})] (map #(process-user % admins db-conn) users))) (defn send-push-to-all-active-users [db-conn message] (do (future (run! #(send-push db-conn (:id %) message) (!select db-conn "ActiveUsers" [:id :name] {}))) {:success true})) (defn send-push-to-table-view "Send push notifications to all users in mySQL view-table. Assumes that the view will have an arn_enpoint column." [db-conn message table-view] (do (future (run! #(sns-publish sns-client (:arn_endpoint %) message) (!select db-conn table-view [:arn_endpoint] {}))) {:success true :message (str "You sent " message " to " table-view)})) (defn send-push-to-users-list [db-conn message user-ids] (do (future (run! #(send-push db-conn (:id %) message) (!select db-conn "users" [:id :name] {} :custom-where (str "id IN (\"" (->> user-ids (map mysql-escape-str) (interpose "\",\"") (apply str)) "\")")))) {:success true})) (defn send-push-to-user [db-conn message user-id] (do (future (run! #(send-push db-conn (:id %) message) (!select db-conn "users" [:id :name] {} :custom-where (str "id IN (\"" (->> user-id (mysql-escape-str) (apply str)) "\")")))) {:success true})) (defn search-users "Search users by term" [db-conn term] (let [escaped-term (mysql-escape-str term) phone-number-term (-> term (s/replace #"-|\(|\)" "") mysql-escape-str) admins (!select db-conn "dashboard_users" [:email :id] {}) users (!select db-conn "users" users-select {} :custom-where (str "`id` LIKE '%" escaped-term "%' " "OR `name` LIKE '%" escaped-term "%' " "OR `phone_number` LIKE '%" phone-number-term "%' " "OR `email` LIKE '%" escaped-term "%' " "OR `referral_code` LIKE '%" escaped-term "%'") :append "ORDER BY timestamp_created LIMIT 100")] (map #(process-user % admins db-conn) users))) (def user-validations {:referral_gallons [ [v/number :message "Referral gallons must be a number"] [v/in-range [0 50000] :message "Must be within 0 and 50,000 referral gallons"] ]}) (defn update-user! "Given a user map, validate it. If valid, update user else return the bouncer error map" [db-conn user] (if (b/valid? user user-validations) (let [{:keys [admin_id referral_comment referral_gallons id]} user db-user (dissoc (get-user-by-id db-conn id) :account_manager_id) update-result (!update db-conn "users" {:referral_gallons referral_gallons} {:id (:id db-user)})] (if (:success update-result) (do ;; update the log (!update db-conn "users" (append-to-admin-event-log {:admin_event_log (:admin_event_log db-user)} :admin-id admin_id :action "adjust_referral_gallons" :comment (or referral_comment "") :previous-value (:referral_gallons db-user) :new-value referral_gallons) {:id (:id db-user)}) (assoc update-result :id (:id db-user))) ;; update that there was a failure (do ;; update the log (!update db-conn "users" (append-to-admin-event-log {:admin_event_log (:admin_event_log db-user)} :admin-id admin_id :action "adjust_referral_gallons" :comment "There was a failure updating gallons" :previous-value (:referral_gallons db-user) :new-value referral_gallons) {:id (:id db-user)}) (assoc update-result :id (:id db-user))))) {:success false :validation (b/validate user user-validations)})) ;; this is how to get the table views with arn_endpoint ;; SELECT c.table_name FROM INFORMATION_SCHEMA.COLUMNS c INNER JOIN (SELECT table_name,table_type FROM information_schema.tables where table_schema = 'ebdb_prod' AND table_type = 'view') t ON c.table_name = t.table_name WHERE COLUMN_NAME IN ('arn_endpoint') AND TABLE_SCHEMA='ebdb_prod' ; ;;curl 'http://localhost:3001/users/convert-to-courier' -X PUT -H 'Content-Type: application/json' -H 'Cookie: tokenPI:KEY:<KEY>END_PI=PI:KEY:<KEY>END_PI; user-id=BCzKBHrWlJz9fddPI:KEY:<KEY>END_PI7Xmc' -d '{"user": {"id":"IVN6rQbtkJiifeRXSFXd"}}' (defn convert-to-courier! "Convert a user to a courier. This creates a courier account" [db-conn user] (let [{:keys [id]} user current-user (first (!select db-conn "users" users-select {:id (:id user)})) is-native? (boolean (= (:type current-user) "native"))] (cond (not is-native?) {:success false :message (str "This user registered with " (:type current-user) ". " "They must register through the app using an email " "address in order to be a courier.")} (> (:total (first (!select db-conn "orders" ["count(*) as total"] {:user_id (:id user)}))) 0) {:success false :message (str "This user already has already made order requests as " "a customer! A courier can not have any fuel delivery " "requests. They will need to create another user " "account with an email address that is different from " "their customer account.")} :else (let [new-courier-result (!insert db-conn "couriers" {:id id :active 1 :busy 0 :lat 0 :lng 0 :zones ""}) set-is-courier-result (!update db-conn "users" {:is_courier 1} {:id id})] (cond (and (:success new-courier-result) (:success set-is-courier-result)) {:success true :message "User successfully converted to a courier."} (not (:success set-is-courier-result)) {:success false :message "User could not be updated"} (not (:success new-courier-result)) {:success false :message "Courier account could not be created"} :else {:success false :message "Unknown error occured"})))))
[ { "context": " (ok\n (POST (api \"/authors\")\n {:name \"Li2\"\n :email \"li2@test.com\"\n :nickname ", "end": 391, "score": 0.7304717302322388, "start": 388, "tag": "USERNAME", "value": "Li2" }, { "context": "uthors\")\n {:name \"Li2\"\n :email \"li2@test.com\"\n :nickname \"L\"\n :biography nil})\n {", "end": 423, "score": 0.9999191164970398, "start": 411, "tag": "EMAIL", "value": "li2@test.com" }, { "context": "phy nil})\n {:id integer?\n :name \"Li2\"\n :email \"li2@test.com\"\n :nickname \"L", "end": 511, "score": 0.7703196406364441, "start": 509, "tag": "NAME", "value": "Li" }, { "context": "y nil})\n {:id integer?\n :name \"Li2\"\n :email \"li2@test.com\"\n :nickname \"L\"", "end": 512, "score": 0.6571393609046936, "start": 511, "tag": "USERNAME", "value": "2" }, { "context": " integer?\n :name \"Li2\"\n :email \"li2@test.com\"\n :nickname \"L\"\n :biography nil}))\n\n(defte", "end": 542, "score": 0.9999179244041443, "start": 530, "tag": "EMAIL", "value": "li2@test.com" } ]
wiz.blog.api/test/wiz/blog/api/end_to_end/authors_test.clj
vladkotu/edge-clj-rest-api-example
0
(ns wiz.blog.api.end-to-end.authors-test (:require [clojure.test :as t :refer [deftest is use-fixtures]] [restpect.core :refer [created not-found ok]] [restpect.json :refer [DELETE GET POST PUT]] [wiz.blog.api.setup :refer [setup-fixtures api]] [clojure.tools.logging :as log])) (setup-fixtures) (deftest create-author (ok (POST (api "/authors") {:name "Li2" :email "li2@test.com" :nickname "L" :biography nil}) {:id integer? :name "Li2" :email "li2@test.com" :nickname "L" :biography nil})) (deftest get-author (ok (GET (api "/authors/1")) {:id integer? :name string? :email string? :nickname string? :biography #(or (string? %) (nil? %))})) (deftest not-found-author (not-found (GET (api "/authors/100000")) {:message "not-found"})) (deftest get-all-authors (ok (GET (api "/authors")) #{{:id integer? :name string? :email string? :nickname string? :biography #(or (string? %) (nil? %))}}))
25564
(ns wiz.blog.api.end-to-end.authors-test (:require [clojure.test :as t :refer [deftest is use-fixtures]] [restpect.core :refer [created not-found ok]] [restpect.json :refer [DELETE GET POST PUT]] [wiz.blog.api.setup :refer [setup-fixtures api]] [clojure.tools.logging :as log])) (setup-fixtures) (deftest create-author (ok (POST (api "/authors") {:name "Li2" :email "<EMAIL>" :nickname "L" :biography nil}) {:id integer? :name "<NAME>2" :email "<EMAIL>" :nickname "L" :biography nil})) (deftest get-author (ok (GET (api "/authors/1")) {:id integer? :name string? :email string? :nickname string? :biography #(or (string? %) (nil? %))})) (deftest not-found-author (not-found (GET (api "/authors/100000")) {:message "not-found"})) (deftest get-all-authors (ok (GET (api "/authors")) #{{:id integer? :name string? :email string? :nickname string? :biography #(or (string? %) (nil? %))}}))
true
(ns wiz.blog.api.end-to-end.authors-test (:require [clojure.test :as t :refer [deftest is use-fixtures]] [restpect.core :refer [created not-found ok]] [restpect.json :refer [DELETE GET POST PUT]] [wiz.blog.api.setup :refer [setup-fixtures api]] [clojure.tools.logging :as log])) (setup-fixtures) (deftest create-author (ok (POST (api "/authors") {:name "Li2" :email "PI:EMAIL:<EMAIL>END_PI" :nickname "L" :biography nil}) {:id integer? :name "PI:NAME:<NAME>END_PI2" :email "PI:EMAIL:<EMAIL>END_PI" :nickname "L" :biography nil})) (deftest get-author (ok (GET (api "/authors/1")) {:id integer? :name string? :email string? :nickname string? :biography #(or (string? %) (nil? %))})) (deftest not-found-author (not-found (GET (api "/authors/100000")) {:message "not-found"})) (deftest get-all-authors (ok (GET (api "/authors")) #{{:id integer? :name string? :email string? :nickname string? :biography #(or (string? %) (nil? %))}}))
[ { "context": "y %2) (cons nil b) (range)) \n a)))\n;;;;;;\n\n;; Lee Spector, 20130101\n\n;; buttons to float answer (on stack) ", "end": 3149, "score": 0.9996471405029297, "start": 3138, "tag": "NAME", "value": "Lee Spector" } ]
data/clojure/88fa4ec506d8a16b185c928408f6281e_calc.clj
maxim5/code-inspector
5
(ns clojush.experimental.calc (:use [clojush.pushgp.pushgp] [clojush.pushstate] [clojush.interpreter] [clojush.random] [clojush.util] [clojush.instructions.tag] [clojure.math.numeric-tower] ;[incanter.stats :as stats] )) ;;;;;;;; (defn compute-next-row "computes the next row using the prev-row current-element and the other seq" [prev-row current-element other-seq pred] (reduce (fn [row [diagonal above other-element]] (let [update-val (if (pred other-element current-element) ;; if the elements are deemed equivalent according to the predicate ;; pred, then no change has taken place to the string, so we are ;; going to set it the same value as diagonal (which is the previous edit-distance) diagonal ;; in the case where the elements are not considered equivalent, then we are going ;; to figure out if its a substitution (then there is a change of 1 from the previous ;; edit distance) thus the value is diagonal + 1 or if its a deletion, then the value ;; is present in the columns, but not in the rows, the edit distance is the edit-distance ;; of last of row + 1 (since we will be using vectors, peek is more efficient) ;; or it could be a case of insertion, then the value is above+1, and we chose ;; the minimum of the three (inc (min diagonal above (peek row))) )] (conj row update-val))) ;; we need to initialize the reduce function with the value of a row, since we are ;; constructing this row from the previous one, the row is a vector of 1 element which ;; consists of 1 + the first element in the previous row (edit distance between the prefix so far ;; and an empty string) [(inc (first prev-row))] ;; for the reduction to go over, we need to provide it with three values, the diagonal ;; which is the same as prev-row because it starts from 0, the above, which is the next element ;; from the list and finally the element from the other sequence itself. (map vector prev-row (next prev-row) other-seq))) (defn levenshtein-distance "Levenshtein Distance - http://en.wikipedia.org/wiki/Levenshtein_distance In information theory and computer science, the Levenshtein distance is a metric for measuring the amount of difference between two sequences. This is a functional implementation of the levenshtein edit distance with as little mutability as possible. Still maintains the O(n*m) guarantee. " [a b & {p :predicate :or {p =}}] (peek (reduce ;; we use a simple reduction to convert the previous row into the next-row using the ;; compute-next-row which takes a current element, the previous-row computed so far ;; and the predicate to compare for equality. (fn [prev-row current-element] (compute-next-row prev-row current-element b p)) ;; we need to initialize the prev-row with the edit distance between the various prefixes of ;; b and the empty string. (map #(identity %2) (cons nil b) (range)) a))) ;;;;;; ;; Lee Spector, 20130101 ;; buttons to float answer (on stack) + boolean error signal (via instruction) ;; if no error must have answer on float stack and NOT have signal error ;; if error must signal error ;; modeled on the Staples SPL-110 (def buttons [:percent :square-root :off :on-clear :memory-recall :memory-minus :memory-plus :clear-entry :seven :eight :nine :divided-by :four :five :six :times :one :two :three :minus :zero :point :equals :plus]) (def button-entrypoints (zipmap buttons (iterate #(+ % 100) 0))) ; button-entrypoints (define-registered signal_error (fn [state] (push-item :error :auxiliary state))) (def digit-entry-tests (let [keys [:zero :one :two :three :four :five :six :seven :eight :nine]] (vec (for [k (range 10)] [[(nth keys k)] (float k) false])))) (def digit-entry-pair-tests (let [keys [:zero :one :two :three :four :five :six :seven :eight :nine]] (vec (for [k1 (range 10) k2 (range 10)] [[(nth keys k1) (nth keys k2)] (float (+ (* 10 k1) k2)) false])))) (def single-digit-math-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9} [op-key op-fn] {:plus +, :minus -, :times *, :divided-by /}] [[arg1-key op-key arg2-key :equals] (float (op-fn arg1-val arg2-val)) false]))) ;single-digit-math-tests (def single-digit-incomplete-math-tests (vec (apply concat (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9} [op-key op-fn] {:plus +, :minus -, :times *, :divided-by /}] [[[arg1-key op-key arg2-key] (float arg2-val) false] [[arg1-key op-key] (float arg1-val) false]])))) ;single-digit-incomplete-math-tests (def single-digit-chained-math-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9} [op1-key op1-fn] {:plus +, :minus -, :times *, :divided-by /} [arg3-key arg3-val] {:three 3, :five 5, :eight 8} [op2-key op2-fn] {:plus +, :minus -, :times *, :divided-by /}] [[arg1-key op1-key arg2-key op2-key arg3-key :equals] (float (op2-fn (op1-fn arg1-val arg2-val) arg3-val)) false]))) ;single-digit-chained-math-tests (def division-by-zero-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:zero 0}] [[arg1-key :divided-by arg2-key :equals] 0.0 true]))) ;division-by-zero-tests (def double-digit-float-entry-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9}] [[arg1-key :point arg2-key] (float (+ arg1-val (* 0.1 arg2-val))) false]))) ;(double-digit-float-entry-tests) (def calc-tests ;; [inputs answer error] ;; answer doesn't matter if error is true ;; if no error, answer must be correct on float stack and true cannot be top boolean (concat digit-entry-tests digit-entry-pair-tests single-digit-math-tests ;single-digit-incomplete-math-tests ;single-digit-chained-math-tests ;division-by-zero-tests ;double-digit-float-entry-tests )) (println "Number of tests:" (count calc-tests)) (defn tag-before-entry-points [push-state] (let [tags (->> button-entrypoints (vec) (map second) (map dec) (map #(if (< % 0) 9999 %)))] ;; hardcoded for tag-limit of 10000 (assoc push-state :tag (merge (sorted-map) (:tag push-state) (zipmap tags (repeat ())))))) (defn calc-errors [program] ;; run the program once ;; make an initialized push state with the resulting tag space and 0.0 ;; then, for each fitness case: ;; start with the initialized push state ;; retrieve and execute all of the entry points from the pressed buttons ;; determine errors from float and boolean stacks (let [correct 0.0 incorrect 1000000000.0 first-run-result (run-push program (tag-before-entry-points (make-push-state))) initialized-push-state (push-item 0.0 :float (assoc (make-push-state) :tag (:tag first-run-result))) test-errors (doall (for [t calc-tests] (loop [push-state initialized-push-state buttons (first t)] (if (empty? buttons) (let [top (top-item :float push-state) target (nth t 1)] ;(println "TEST:" t) ;(println "FINAL STATE:" push-state) (if (not (number? top)) [incorrect incorrect] (if (== top target) ;; correct [correct correct] ;incorrect [(Math/abs (- top target)) (float (levenshtein-distance (str top) (str target)))])) ;; ;; error signal error #_(if (nth t 2) (if (= :error (top-item :auxiliary push-state)) correct incorrect) correct) ;]) ) (recur (let [the-tag (get button-entrypoints (first buttons))] (run-push (second (closest-association the-tag push-state)) push-state)) (rest buttons))))))] ;(vec (apply concat test-errors)) (let [all-errors (apply concat test-errors)] (conj (vec all-errors) (count (filter #(not (zero? %)) all-errors)))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def argmap {:error-function calc-errors :atom-generators (concat ;'(signal_error) [0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0] [(tag-instruction-erc [:exec])] (for [t (vals button-entrypoints)] (fn [] (symbol (str "tag_exec_" (str t))))) [(tagged-instruction-erc)] (repeat 46 'code_noop) '(boolean_and boolean_dup boolean_eq ;boolean_flush boolean_fromfloat ;boolean_frominteger boolean_not boolean_or boolean_pop ;boolean_rand boolean_rot ;boolean_shove ;boolean_stackdepth boolean_swap ;boolean_yank ;boolean_yankdup ;code_append ;code_atom ;code_car ;code_cdr ;code_cons ;code_container ;code_contains ;code_do ;code_do* ;code_do*count ;code_do*range ;code_do*times ;code_dup ;code_eq ;code_extract ;code_flush ;;code_fromboolean ;code_fromfloat ;code_frominteger ;;code_fromzipchildren ;;code_fromziplefts ;;code_fromzipnode ;;code_fromziprights ;;code_fromziproot ;code_if ;code_insert ;code_length ;code_list ;code_map ;code_member ;code_noop ;code_nth ;code_nthcdr ;code_null ;code_pop ;code_position ;code_quote ;;code_rand ;code_rot ;code_shove ;code_size ;code_stackdepth ;code_subst ;code_swap ;code_wrap ;code_yank ;code_yankdup ;environment_begin ;environment_end ;environment_new ;exec_do*count ;exec_do*range ;exec_do*times exec_dup exec_eq ;exec_flush ;exec_fromzipchildren ;exec_fromziplefts ;exec_fromzipnode ;exec_fromziprights ;exec_fromziproot exec_if exec_k exec_noop ;exec_pop exec_rot exec_s ;exec_shove ;exec_stackdepth exec_swap exec_when exec_y ;exec_yank ;exec_yankdup float_add float_cos float_div float_dup float_eq ;float_flush float_fromboolean ;float_frominteger float_gt float_lt float_max float_min float_mod float_mult float_pop ;float_rand float_rot ;float_shove float_sin ;float_stackdepth float_sub float_swap float_tan ;float_yank ;float_yankdup ;integer_add ;integer_div ;integer_dup ;integer_eq ;integer_flush ;integer_fromboolean ;integer_fromfloat ;integer_gt ;integer_lt ;integer_max ;integer_min ;integer_mod ;integer_mult ;integer_pop ;integer_rand ;integer_rot ;integer_shove ;integer_stackdepth ;integer_sub ;integer_swap ;integer_yank ;integer_yankdup ;return_boolean_pop ;return_code_pop ;return_exec_pop ;return_float_pop ;return_fromboolean ;return_fromcode ;return_fromexec ;return_fromfloat ;return_frominteger ;return_fromstring ;return_tagspace ;return_integer_pop ;return_string_pop ;return_zip_pop ;string_atoi ;string_concat ;string_contained ;string_dup ;string_eq ;string_flush ;string_length ;string_parse_to_chars ;string_pop ;;string_rand ;string_reverse ;string_rot ;string_shove ;string_stackdepth ;string_swap ;string_take ;string_yank ;string_yankdup ;zip_append_child_fromcode ;zip_append_child_fromexec ;zip_branch? ;zip_down ;zip_dup ;zip_end? ;zip_eq ;zip_flush ;zip_fromcode ;zip_fromexec ;zip_insert_child_fromcode ;zip_insert_child_fromexec ;zip_insert_left_fromcode ;zip_insert_left_fromexec ;zip_insert_right_fromcode ;zip_insert_right_fromexec ;zip_left ;zip_leftmost ;zip_next ;zip_pop ;zip_prev ;zip_remove ;zip_replace_fromcode ;zip_replace_fromexec ;zip_right ;zip_rightmost ;zip_rot ;zip_shove ;zip_stackdepth ;zip_swap ;zip_up ;zip_yank ;zip_yankdup ) ) :use-single-thread false :use-lexicase-selection true :trivial-geography-radius 500 ;:use-elitegroup-lexicase-selection true ;:use-historically-assessed-hardness true ;; just to print them! ;:decimation-ratio 0.01 ;:tournament-size 1 :population-size 10000 ;200 ;50 :max-generations 10001 :evalpush-limit 3000 :tag-limit 10000 :max-points 3000 :max-points-in-initial-program 200 ;;100 :parent-reversion-probability 0.0 :mutation-probability 0 :crossover-probability 0 :simplification-probability 0 :reproduction-simplifications 10 :ultra-probability 1.0 :ultra-alternation-rate 0.005 :ultra-alignment-deviation 5 :ultra-mutation-rate 0.005 :deletion-mutation-probability 0 :parentheses-addition-mutation-probability 0 :tagging-mutation-probability 0 :tag-branch-mutation-probability 0.0 :tag-branch-mutation-type-instruction-pairs [[:boolean 'boolean_eq] [:float 'float_eq] [:float 'float_lt] [:float 'float_gt]] :pop-when-tagging true :report-simplifications 0 :print-history false })
106580
(ns clojush.experimental.calc (:use [clojush.pushgp.pushgp] [clojush.pushstate] [clojush.interpreter] [clojush.random] [clojush.util] [clojush.instructions.tag] [clojure.math.numeric-tower] ;[incanter.stats :as stats] )) ;;;;;;;; (defn compute-next-row "computes the next row using the prev-row current-element and the other seq" [prev-row current-element other-seq pred] (reduce (fn [row [diagonal above other-element]] (let [update-val (if (pred other-element current-element) ;; if the elements are deemed equivalent according to the predicate ;; pred, then no change has taken place to the string, so we are ;; going to set it the same value as diagonal (which is the previous edit-distance) diagonal ;; in the case where the elements are not considered equivalent, then we are going ;; to figure out if its a substitution (then there is a change of 1 from the previous ;; edit distance) thus the value is diagonal + 1 or if its a deletion, then the value ;; is present in the columns, but not in the rows, the edit distance is the edit-distance ;; of last of row + 1 (since we will be using vectors, peek is more efficient) ;; or it could be a case of insertion, then the value is above+1, and we chose ;; the minimum of the three (inc (min diagonal above (peek row))) )] (conj row update-val))) ;; we need to initialize the reduce function with the value of a row, since we are ;; constructing this row from the previous one, the row is a vector of 1 element which ;; consists of 1 + the first element in the previous row (edit distance between the prefix so far ;; and an empty string) [(inc (first prev-row))] ;; for the reduction to go over, we need to provide it with three values, the diagonal ;; which is the same as prev-row because it starts from 0, the above, which is the next element ;; from the list and finally the element from the other sequence itself. (map vector prev-row (next prev-row) other-seq))) (defn levenshtein-distance "Levenshtein Distance - http://en.wikipedia.org/wiki/Levenshtein_distance In information theory and computer science, the Levenshtein distance is a metric for measuring the amount of difference between two sequences. This is a functional implementation of the levenshtein edit distance with as little mutability as possible. Still maintains the O(n*m) guarantee. " [a b & {p :predicate :or {p =}}] (peek (reduce ;; we use a simple reduction to convert the previous row into the next-row using the ;; compute-next-row which takes a current element, the previous-row computed so far ;; and the predicate to compare for equality. (fn [prev-row current-element] (compute-next-row prev-row current-element b p)) ;; we need to initialize the prev-row with the edit distance between the various prefixes of ;; b and the empty string. (map #(identity %2) (cons nil b) (range)) a))) ;;;;;; ;; <NAME>, 20130101 ;; buttons to float answer (on stack) + boolean error signal (via instruction) ;; if no error must have answer on float stack and NOT have signal error ;; if error must signal error ;; modeled on the Staples SPL-110 (def buttons [:percent :square-root :off :on-clear :memory-recall :memory-minus :memory-plus :clear-entry :seven :eight :nine :divided-by :four :five :six :times :one :two :three :minus :zero :point :equals :plus]) (def button-entrypoints (zipmap buttons (iterate #(+ % 100) 0))) ; button-entrypoints (define-registered signal_error (fn [state] (push-item :error :auxiliary state))) (def digit-entry-tests (let [keys [:zero :one :two :three :four :five :six :seven :eight :nine]] (vec (for [k (range 10)] [[(nth keys k)] (float k) false])))) (def digit-entry-pair-tests (let [keys [:zero :one :two :three :four :five :six :seven :eight :nine]] (vec (for [k1 (range 10) k2 (range 10)] [[(nth keys k1) (nth keys k2)] (float (+ (* 10 k1) k2)) false])))) (def single-digit-math-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9} [op-key op-fn] {:plus +, :minus -, :times *, :divided-by /}] [[arg1-key op-key arg2-key :equals] (float (op-fn arg1-val arg2-val)) false]))) ;single-digit-math-tests (def single-digit-incomplete-math-tests (vec (apply concat (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9} [op-key op-fn] {:plus +, :minus -, :times *, :divided-by /}] [[[arg1-key op-key arg2-key] (float arg2-val) false] [[arg1-key op-key] (float arg1-val) false]])))) ;single-digit-incomplete-math-tests (def single-digit-chained-math-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9} [op1-key op1-fn] {:plus +, :minus -, :times *, :divided-by /} [arg3-key arg3-val] {:three 3, :five 5, :eight 8} [op2-key op2-fn] {:plus +, :minus -, :times *, :divided-by /}] [[arg1-key op1-key arg2-key op2-key arg3-key :equals] (float (op2-fn (op1-fn arg1-val arg2-val) arg3-val)) false]))) ;single-digit-chained-math-tests (def division-by-zero-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:zero 0}] [[arg1-key :divided-by arg2-key :equals] 0.0 true]))) ;division-by-zero-tests (def double-digit-float-entry-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9}] [[arg1-key :point arg2-key] (float (+ arg1-val (* 0.1 arg2-val))) false]))) ;(double-digit-float-entry-tests) (def calc-tests ;; [inputs answer error] ;; answer doesn't matter if error is true ;; if no error, answer must be correct on float stack and true cannot be top boolean (concat digit-entry-tests digit-entry-pair-tests single-digit-math-tests ;single-digit-incomplete-math-tests ;single-digit-chained-math-tests ;division-by-zero-tests ;double-digit-float-entry-tests )) (println "Number of tests:" (count calc-tests)) (defn tag-before-entry-points [push-state] (let [tags (->> button-entrypoints (vec) (map second) (map dec) (map #(if (< % 0) 9999 %)))] ;; hardcoded for tag-limit of 10000 (assoc push-state :tag (merge (sorted-map) (:tag push-state) (zipmap tags (repeat ())))))) (defn calc-errors [program] ;; run the program once ;; make an initialized push state with the resulting tag space and 0.0 ;; then, for each fitness case: ;; start with the initialized push state ;; retrieve and execute all of the entry points from the pressed buttons ;; determine errors from float and boolean stacks (let [correct 0.0 incorrect 1000000000.0 first-run-result (run-push program (tag-before-entry-points (make-push-state))) initialized-push-state (push-item 0.0 :float (assoc (make-push-state) :tag (:tag first-run-result))) test-errors (doall (for [t calc-tests] (loop [push-state initialized-push-state buttons (first t)] (if (empty? buttons) (let [top (top-item :float push-state) target (nth t 1)] ;(println "TEST:" t) ;(println "FINAL STATE:" push-state) (if (not (number? top)) [incorrect incorrect] (if (== top target) ;; correct [correct correct] ;incorrect [(Math/abs (- top target)) (float (levenshtein-distance (str top) (str target)))])) ;; ;; error signal error #_(if (nth t 2) (if (= :error (top-item :auxiliary push-state)) correct incorrect) correct) ;]) ) (recur (let [the-tag (get button-entrypoints (first buttons))] (run-push (second (closest-association the-tag push-state)) push-state)) (rest buttons))))))] ;(vec (apply concat test-errors)) (let [all-errors (apply concat test-errors)] (conj (vec all-errors) (count (filter #(not (zero? %)) all-errors)))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def argmap {:error-function calc-errors :atom-generators (concat ;'(signal_error) [0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0] [(tag-instruction-erc [:exec])] (for [t (vals button-entrypoints)] (fn [] (symbol (str "tag_exec_" (str t))))) [(tagged-instruction-erc)] (repeat 46 'code_noop) '(boolean_and boolean_dup boolean_eq ;boolean_flush boolean_fromfloat ;boolean_frominteger boolean_not boolean_or boolean_pop ;boolean_rand boolean_rot ;boolean_shove ;boolean_stackdepth boolean_swap ;boolean_yank ;boolean_yankdup ;code_append ;code_atom ;code_car ;code_cdr ;code_cons ;code_container ;code_contains ;code_do ;code_do* ;code_do*count ;code_do*range ;code_do*times ;code_dup ;code_eq ;code_extract ;code_flush ;;code_fromboolean ;code_fromfloat ;code_frominteger ;;code_fromzipchildren ;;code_fromziplefts ;;code_fromzipnode ;;code_fromziprights ;;code_fromziproot ;code_if ;code_insert ;code_length ;code_list ;code_map ;code_member ;code_noop ;code_nth ;code_nthcdr ;code_null ;code_pop ;code_position ;code_quote ;;code_rand ;code_rot ;code_shove ;code_size ;code_stackdepth ;code_subst ;code_swap ;code_wrap ;code_yank ;code_yankdup ;environment_begin ;environment_end ;environment_new ;exec_do*count ;exec_do*range ;exec_do*times exec_dup exec_eq ;exec_flush ;exec_fromzipchildren ;exec_fromziplefts ;exec_fromzipnode ;exec_fromziprights ;exec_fromziproot exec_if exec_k exec_noop ;exec_pop exec_rot exec_s ;exec_shove ;exec_stackdepth exec_swap exec_when exec_y ;exec_yank ;exec_yankdup float_add float_cos float_div float_dup float_eq ;float_flush float_fromboolean ;float_frominteger float_gt float_lt float_max float_min float_mod float_mult float_pop ;float_rand float_rot ;float_shove float_sin ;float_stackdepth float_sub float_swap float_tan ;float_yank ;float_yankdup ;integer_add ;integer_div ;integer_dup ;integer_eq ;integer_flush ;integer_fromboolean ;integer_fromfloat ;integer_gt ;integer_lt ;integer_max ;integer_min ;integer_mod ;integer_mult ;integer_pop ;integer_rand ;integer_rot ;integer_shove ;integer_stackdepth ;integer_sub ;integer_swap ;integer_yank ;integer_yankdup ;return_boolean_pop ;return_code_pop ;return_exec_pop ;return_float_pop ;return_fromboolean ;return_fromcode ;return_fromexec ;return_fromfloat ;return_frominteger ;return_fromstring ;return_tagspace ;return_integer_pop ;return_string_pop ;return_zip_pop ;string_atoi ;string_concat ;string_contained ;string_dup ;string_eq ;string_flush ;string_length ;string_parse_to_chars ;string_pop ;;string_rand ;string_reverse ;string_rot ;string_shove ;string_stackdepth ;string_swap ;string_take ;string_yank ;string_yankdup ;zip_append_child_fromcode ;zip_append_child_fromexec ;zip_branch? ;zip_down ;zip_dup ;zip_end? ;zip_eq ;zip_flush ;zip_fromcode ;zip_fromexec ;zip_insert_child_fromcode ;zip_insert_child_fromexec ;zip_insert_left_fromcode ;zip_insert_left_fromexec ;zip_insert_right_fromcode ;zip_insert_right_fromexec ;zip_left ;zip_leftmost ;zip_next ;zip_pop ;zip_prev ;zip_remove ;zip_replace_fromcode ;zip_replace_fromexec ;zip_right ;zip_rightmost ;zip_rot ;zip_shove ;zip_stackdepth ;zip_swap ;zip_up ;zip_yank ;zip_yankdup ) ) :use-single-thread false :use-lexicase-selection true :trivial-geography-radius 500 ;:use-elitegroup-lexicase-selection true ;:use-historically-assessed-hardness true ;; just to print them! ;:decimation-ratio 0.01 ;:tournament-size 1 :population-size 10000 ;200 ;50 :max-generations 10001 :evalpush-limit 3000 :tag-limit 10000 :max-points 3000 :max-points-in-initial-program 200 ;;100 :parent-reversion-probability 0.0 :mutation-probability 0 :crossover-probability 0 :simplification-probability 0 :reproduction-simplifications 10 :ultra-probability 1.0 :ultra-alternation-rate 0.005 :ultra-alignment-deviation 5 :ultra-mutation-rate 0.005 :deletion-mutation-probability 0 :parentheses-addition-mutation-probability 0 :tagging-mutation-probability 0 :tag-branch-mutation-probability 0.0 :tag-branch-mutation-type-instruction-pairs [[:boolean 'boolean_eq] [:float 'float_eq] [:float 'float_lt] [:float 'float_gt]] :pop-when-tagging true :report-simplifications 0 :print-history false })
true
(ns clojush.experimental.calc (:use [clojush.pushgp.pushgp] [clojush.pushstate] [clojush.interpreter] [clojush.random] [clojush.util] [clojush.instructions.tag] [clojure.math.numeric-tower] ;[incanter.stats :as stats] )) ;;;;;;;; (defn compute-next-row "computes the next row using the prev-row current-element and the other seq" [prev-row current-element other-seq pred] (reduce (fn [row [diagonal above other-element]] (let [update-val (if (pred other-element current-element) ;; if the elements are deemed equivalent according to the predicate ;; pred, then no change has taken place to the string, so we are ;; going to set it the same value as diagonal (which is the previous edit-distance) diagonal ;; in the case where the elements are not considered equivalent, then we are going ;; to figure out if its a substitution (then there is a change of 1 from the previous ;; edit distance) thus the value is diagonal + 1 or if its a deletion, then the value ;; is present in the columns, but not in the rows, the edit distance is the edit-distance ;; of last of row + 1 (since we will be using vectors, peek is more efficient) ;; or it could be a case of insertion, then the value is above+1, and we chose ;; the minimum of the three (inc (min diagonal above (peek row))) )] (conj row update-val))) ;; we need to initialize the reduce function with the value of a row, since we are ;; constructing this row from the previous one, the row is a vector of 1 element which ;; consists of 1 + the first element in the previous row (edit distance between the prefix so far ;; and an empty string) [(inc (first prev-row))] ;; for the reduction to go over, we need to provide it with three values, the diagonal ;; which is the same as prev-row because it starts from 0, the above, which is the next element ;; from the list and finally the element from the other sequence itself. (map vector prev-row (next prev-row) other-seq))) (defn levenshtein-distance "Levenshtein Distance - http://en.wikipedia.org/wiki/Levenshtein_distance In information theory and computer science, the Levenshtein distance is a metric for measuring the amount of difference between two sequences. This is a functional implementation of the levenshtein edit distance with as little mutability as possible. Still maintains the O(n*m) guarantee. " [a b & {p :predicate :or {p =}}] (peek (reduce ;; we use a simple reduction to convert the previous row into the next-row using the ;; compute-next-row which takes a current element, the previous-row computed so far ;; and the predicate to compare for equality. (fn [prev-row current-element] (compute-next-row prev-row current-element b p)) ;; we need to initialize the prev-row with the edit distance between the various prefixes of ;; b and the empty string. (map #(identity %2) (cons nil b) (range)) a))) ;;;;;; ;; PI:NAME:<NAME>END_PI, 20130101 ;; buttons to float answer (on stack) + boolean error signal (via instruction) ;; if no error must have answer on float stack and NOT have signal error ;; if error must signal error ;; modeled on the Staples SPL-110 (def buttons [:percent :square-root :off :on-clear :memory-recall :memory-minus :memory-plus :clear-entry :seven :eight :nine :divided-by :four :five :six :times :one :two :three :minus :zero :point :equals :plus]) (def button-entrypoints (zipmap buttons (iterate #(+ % 100) 0))) ; button-entrypoints (define-registered signal_error (fn [state] (push-item :error :auxiliary state))) (def digit-entry-tests (let [keys [:zero :one :two :three :four :five :six :seven :eight :nine]] (vec (for [k (range 10)] [[(nth keys k)] (float k) false])))) (def digit-entry-pair-tests (let [keys [:zero :one :two :three :four :five :six :seven :eight :nine]] (vec (for [k1 (range 10) k2 (range 10)] [[(nth keys k1) (nth keys k2)] (float (+ (* 10 k1) k2)) false])))) (def single-digit-math-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9} [op-key op-fn] {:plus +, :minus -, :times *, :divided-by /}] [[arg1-key op-key arg2-key :equals] (float (op-fn arg1-val arg2-val)) false]))) ;single-digit-math-tests (def single-digit-incomplete-math-tests (vec (apply concat (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9} [op-key op-fn] {:plus +, :minus -, :times *, :divided-by /}] [[[arg1-key op-key arg2-key] (float arg2-val) false] [[arg1-key op-key] (float arg1-val) false]])))) ;single-digit-incomplete-math-tests (def single-digit-chained-math-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9} [op1-key op1-fn] {:plus +, :minus -, :times *, :divided-by /} [arg3-key arg3-val] {:three 3, :five 5, :eight 8} [op2-key op2-fn] {:plus +, :minus -, :times *, :divided-by /}] [[arg1-key op1-key arg2-key op2-key arg3-key :equals] (float (op2-fn (op1-fn arg1-val arg2-val) arg3-val)) false]))) ;single-digit-chained-math-tests (def division-by-zero-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:zero 0}] [[arg1-key :divided-by arg2-key :equals] 0.0 true]))) ;division-by-zero-tests (def double-digit-float-entry-tests (vec (for [[arg1-key arg1-val] {:zero 0, :three 3, :seven 7} [arg2-key arg2-val] {:two 2, :four 4, :nine 9}] [[arg1-key :point arg2-key] (float (+ arg1-val (* 0.1 arg2-val))) false]))) ;(double-digit-float-entry-tests) (def calc-tests ;; [inputs answer error] ;; answer doesn't matter if error is true ;; if no error, answer must be correct on float stack and true cannot be top boolean (concat digit-entry-tests digit-entry-pair-tests single-digit-math-tests ;single-digit-incomplete-math-tests ;single-digit-chained-math-tests ;division-by-zero-tests ;double-digit-float-entry-tests )) (println "Number of tests:" (count calc-tests)) (defn tag-before-entry-points [push-state] (let [tags (->> button-entrypoints (vec) (map second) (map dec) (map #(if (< % 0) 9999 %)))] ;; hardcoded for tag-limit of 10000 (assoc push-state :tag (merge (sorted-map) (:tag push-state) (zipmap tags (repeat ())))))) (defn calc-errors [program] ;; run the program once ;; make an initialized push state with the resulting tag space and 0.0 ;; then, for each fitness case: ;; start with the initialized push state ;; retrieve and execute all of the entry points from the pressed buttons ;; determine errors from float and boolean stacks (let [correct 0.0 incorrect 1000000000.0 first-run-result (run-push program (tag-before-entry-points (make-push-state))) initialized-push-state (push-item 0.0 :float (assoc (make-push-state) :tag (:tag first-run-result))) test-errors (doall (for [t calc-tests] (loop [push-state initialized-push-state buttons (first t)] (if (empty? buttons) (let [top (top-item :float push-state) target (nth t 1)] ;(println "TEST:" t) ;(println "FINAL STATE:" push-state) (if (not (number? top)) [incorrect incorrect] (if (== top target) ;; correct [correct correct] ;incorrect [(Math/abs (- top target)) (float (levenshtein-distance (str top) (str target)))])) ;; ;; error signal error #_(if (nth t 2) (if (= :error (top-item :auxiliary push-state)) correct incorrect) correct) ;]) ) (recur (let [the-tag (get button-entrypoints (first buttons))] (run-push (second (closest-association the-tag push-state)) push-state)) (rest buttons))))))] ;(vec (apply concat test-errors)) (let [all-errors (apply concat test-errors)] (conj (vec all-errors) (count (filter #(not (zero? %)) all-errors)))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def argmap {:error-function calc-errors :atom-generators (concat ;'(signal_error) [0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0] [(tag-instruction-erc [:exec])] (for [t (vals button-entrypoints)] (fn [] (symbol (str "tag_exec_" (str t))))) [(tagged-instruction-erc)] (repeat 46 'code_noop) '(boolean_and boolean_dup boolean_eq ;boolean_flush boolean_fromfloat ;boolean_frominteger boolean_not boolean_or boolean_pop ;boolean_rand boolean_rot ;boolean_shove ;boolean_stackdepth boolean_swap ;boolean_yank ;boolean_yankdup ;code_append ;code_atom ;code_car ;code_cdr ;code_cons ;code_container ;code_contains ;code_do ;code_do* ;code_do*count ;code_do*range ;code_do*times ;code_dup ;code_eq ;code_extract ;code_flush ;;code_fromboolean ;code_fromfloat ;code_frominteger ;;code_fromzipchildren ;;code_fromziplefts ;;code_fromzipnode ;;code_fromziprights ;;code_fromziproot ;code_if ;code_insert ;code_length ;code_list ;code_map ;code_member ;code_noop ;code_nth ;code_nthcdr ;code_null ;code_pop ;code_position ;code_quote ;;code_rand ;code_rot ;code_shove ;code_size ;code_stackdepth ;code_subst ;code_swap ;code_wrap ;code_yank ;code_yankdup ;environment_begin ;environment_end ;environment_new ;exec_do*count ;exec_do*range ;exec_do*times exec_dup exec_eq ;exec_flush ;exec_fromzipchildren ;exec_fromziplefts ;exec_fromzipnode ;exec_fromziprights ;exec_fromziproot exec_if exec_k exec_noop ;exec_pop exec_rot exec_s ;exec_shove ;exec_stackdepth exec_swap exec_when exec_y ;exec_yank ;exec_yankdup float_add float_cos float_div float_dup float_eq ;float_flush float_fromboolean ;float_frominteger float_gt float_lt float_max float_min float_mod float_mult float_pop ;float_rand float_rot ;float_shove float_sin ;float_stackdepth float_sub float_swap float_tan ;float_yank ;float_yankdup ;integer_add ;integer_div ;integer_dup ;integer_eq ;integer_flush ;integer_fromboolean ;integer_fromfloat ;integer_gt ;integer_lt ;integer_max ;integer_min ;integer_mod ;integer_mult ;integer_pop ;integer_rand ;integer_rot ;integer_shove ;integer_stackdepth ;integer_sub ;integer_swap ;integer_yank ;integer_yankdup ;return_boolean_pop ;return_code_pop ;return_exec_pop ;return_float_pop ;return_fromboolean ;return_fromcode ;return_fromexec ;return_fromfloat ;return_frominteger ;return_fromstring ;return_tagspace ;return_integer_pop ;return_string_pop ;return_zip_pop ;string_atoi ;string_concat ;string_contained ;string_dup ;string_eq ;string_flush ;string_length ;string_parse_to_chars ;string_pop ;;string_rand ;string_reverse ;string_rot ;string_shove ;string_stackdepth ;string_swap ;string_take ;string_yank ;string_yankdup ;zip_append_child_fromcode ;zip_append_child_fromexec ;zip_branch? ;zip_down ;zip_dup ;zip_end? ;zip_eq ;zip_flush ;zip_fromcode ;zip_fromexec ;zip_insert_child_fromcode ;zip_insert_child_fromexec ;zip_insert_left_fromcode ;zip_insert_left_fromexec ;zip_insert_right_fromcode ;zip_insert_right_fromexec ;zip_left ;zip_leftmost ;zip_next ;zip_pop ;zip_prev ;zip_remove ;zip_replace_fromcode ;zip_replace_fromexec ;zip_right ;zip_rightmost ;zip_rot ;zip_shove ;zip_stackdepth ;zip_swap ;zip_up ;zip_yank ;zip_yankdup ) ) :use-single-thread false :use-lexicase-selection true :trivial-geography-radius 500 ;:use-elitegroup-lexicase-selection true ;:use-historically-assessed-hardness true ;; just to print them! ;:decimation-ratio 0.01 ;:tournament-size 1 :population-size 10000 ;200 ;50 :max-generations 10001 :evalpush-limit 3000 :tag-limit 10000 :max-points 3000 :max-points-in-initial-program 200 ;;100 :parent-reversion-probability 0.0 :mutation-probability 0 :crossover-probability 0 :simplification-probability 0 :reproduction-simplifications 10 :ultra-probability 1.0 :ultra-alternation-rate 0.005 :ultra-alignment-deviation 5 :ultra-mutation-rate 0.005 :deletion-mutation-probability 0 :parentheses-addition-mutation-probability 0 :tagging-mutation-probability 0 :tag-branch-mutation-probability 0.0 :tag-branch-mutation-type-instruction-pairs [[:boolean 'boolean_eq] [:float 'float_eq] [:float 'float_lt] [:float 'float_gt]] :pop-when-tagging true :report-simplifications 0 :print-history false })
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998217225074768, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
ext/clojure-clojurescript-bef56a7/src/clj/cljs/compiler.clj
yokolet/clementine
35
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (set! *warn-on-reflection* true) (ns cljs.compiler (:refer-clojure :exclude [munge macroexpand-1]) (:require [clojure.java.io :as io] [clojure.string :as string] [cljs.tagged-literals :as tags] [cljs.analyzer :as ana]) (:import java.lang.StringBuilder)) (declare munge) (def js-reserved #{"abstract" "boolean" "break" "byte" "case" "catch" "char" "class" "const" "continue" "debugger" "default" "delete" "do" "double" "else" "enum" "export" "extends" "final" "finally" "float" "for" "function" "goto" "if" "implements" "import" "in" "instanceof" "int" "interface" "let" "long" "native" "new" "package" "private" "protected" "public" "return" "short" "static" "super" "switch" "synchronized" "this" "throw" "throws" "transient" "try" "typeof" "var" "void" "volatile" "while" "with" "yield" "methods"}) (def ^:dynamic *position* nil) (def ^:dynamic *emitted-provides* nil) (def cljs-reserved-file-names #{"deps.cljs"}) (defonce ns-first-segments (atom '#{"cljs" "clojure"})) (defn munge ([s] (munge s js-reserved)) ([s reserved] (if (map? s) ; Unshadowing (let [{:keys [name field] :as info} s depth (loop [d 0, {:keys [shadow]} info] (cond shadow (recur (inc d) shadow) (@ns-first-segments (str name)) (inc d) :else d)) name (if field (str "self__." name) name)] (if (zero? depth) (munge name reserved) (symbol (str (munge name reserved) "__$" depth)))) ; String munging (let [ss (string/replace (str s) #"\/(.)" ".$1") ; Division is special ss (apply str (map #(if (reserved %) (str % "$") %) (string/split ss #"(?<=\.)|(?=\.)"))) ms (clojure.lang.Compiler/munge ss)] (if (symbol? s) (symbol ms) ms))))) (defn- comma-sep [xs] (interpose "," xs)) (defn- escape-char [^Character c] (let [cp (.hashCode c)] (case cp ; Handle printable escapes before ASCII 34 "\\\"" 92 "\\\\" ; Handle non-printable escapes 8 "\\b" 12 "\\f" 10 "\\n" 13 "\\r" 9 "\\t" (if (< 31 cp 127) c ; Print simple ASCII characters (format "\\u%04X" cp))))) ; Any other character is Unicode (defn- escape-string [^CharSequence s] (let [sb (StringBuilder. (count s))] (doseq [c s] (.append sb (escape-char c))) (.toString sb))) (defn- wrap-in-double-quotes [x] (str \" x \")) (defmulti emit :op) (defn emits [& xs] (doseq [x xs] (cond (nil? x) nil (map? x) (emit x) (seq? x) (apply emits x) (fn? x) (x) :else (do (let [s (print-str x)] (when *position* (swap! *position* (fn [[line column]] [line (+ column (count s))]))) (print s))))) nil) (defn ^String emit-str [expr] (with-out-str (emit expr))) (defn emitln [& xs] (apply emits xs) ;; Prints column-aligned line number comments; good test of *position*. ;(when *position* ; (let [[line column] @*position*] ; (print (apply str (concat (repeat (- 120 column) \space) ["// " (inc line)]))))) (println) (when *position* (swap! *position* (fn [[line column]] [(inc line) 0]))) nil) (defmulti emit-constant class) (defmethod emit-constant nil [x] (emits "null")) (defmethod emit-constant Long [x] (emits x)) (defmethod emit-constant Integer [x] (emits x)) ; reader puts Integers in metadata (defmethod emit-constant Double [x] (emits x)) (defmethod emit-constant String [x] (emits (wrap-in-double-quotes (escape-string x)))) (defmethod emit-constant Boolean [x] (emits (if x "true" "false"))) (defmethod emit-constant Character [x] (emits (wrap-in-double-quotes (escape-char x)))) (defmethod emit-constant java.util.regex.Pattern [x] (let [[_ flags pattern] (re-find #"^(?:\(\?([idmsux]*)\))?(.*)" (str x))] (emits \/ (.replaceAll (re-matcher #"/" pattern) "\\\\/") \/ flags))) (defmethod emit-constant clojure.lang.Keyword [x] (emits \" "\\uFDD0" \' (if (namespace x) (str (namespace x) "/") "") (name x) \")) (defmethod emit-constant clojure.lang.Symbol [x] (emits \" "\\uFDD1" \' (if (namespace x) (str (namespace x) "/") "") (name x) \")) (defn- emit-meta-constant [x & body] (if (meta x) (do (emits "cljs.core.with_meta(" body ",") (emit-constant (meta x)) (emits ")")) (emits body))) (defmethod emit-constant clojure.lang.PersistentList$EmptyList [x] (emit-meta-constant x "cljs.core.List.EMPTY")) (defmethod emit-constant clojure.lang.PersistentList [x] (emit-meta-constant x (concat ["cljs.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.Cons [x] (emit-meta-constant x (concat ["cljs.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.IPersistentVector [x] (emit-meta-constant x (concat ["cljs.core.vec(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defmethod emit-constant clojure.lang.IPersistentMap [x] (emit-meta-constant x (concat ["cljs.core.hash_map("] (comma-sep (map #(fn [] (emit-constant %)) (apply concat x))) [")"]))) (defmethod emit-constant clojure.lang.PersistentHashSet [x] (emit-meta-constant x (concat ["cljs.core.set(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defn emit-block [context statements ret] (when statements (emits statements)) (emit ret)) (defmacro emit-wrap [env & body] `(let [env# ~env] (when (= :return (:context env#)) (emits "return ")) ~@body (when-not (= :expr (:context env#)) (emitln ";")))) (defmethod emit :no-op [m]) (defmethod emit :var [{:keys [info env] :as arg}] (let [n (:name info) n (if (= (namespace n) "js") (name n) info)] (emit-wrap env (emits (munge n))))) (defmethod emit :meta [{:keys [expr meta env]}] (emit-wrap env (emits "cljs.core.with_meta(" expr "," meta ")"))) (def ^:private array-map-threshold 16) (def ^:private obj-map-threshold 32) (defmethod emit :map [{:keys [env simple-keys? keys vals]}] (emit-wrap env (cond (zero? (count keys)) (emits "cljs.core.ObjMap.EMPTY") (and simple-keys? (<= (count keys) obj-map-threshold)) (emits "cljs.core.ObjMap.fromObject([" (comma-sep keys) ; keys "],{" (comma-sep (map (fn [k v] (with-out-str (emit k) (print ":") (emit v))) keys vals)) ; js obj "})") (<= (count keys) array-map-threshold) (emits "cljs.core.PersistentArrayMap.fromArrays([" (comma-sep keys) "],[" (comma-sep vals) "])") :else (emits "cljs.core.PersistentHashMap.fromArrays([" (comma-sep keys) "],[" (comma-sep vals) "])")))) (defmethod emit :vector [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "cljs.core.PersistentVector.EMPTY") (emits "cljs.core.PersistentVector.fromArray([" (comma-sep items) "], true)")))) (defmethod emit :set [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "cljs.core.PersistentHashSet.EMPTY") (emits "cljs.core.PersistentHashSet.fromArray([" (comma-sep items) "])")))) (defmethod emit :constant [{:keys [form env]}] (when-not (= :statement (:context env)) (emit-wrap env (emit-constant form)))) (defn get-tag [e] (or (-> e :tag) (-> e :info :tag))) (defn infer-tag [e] (if-let [tag (get-tag e)] tag (case (:op e) :let (infer-tag (:ret e)) :if (let [then-tag (infer-tag (:then e)) else-tag (infer-tag (:else e))] (when (= then-tag else-tag) then-tag)) :constant (case (:form e) true 'boolean false 'boolean nil) nil))) (defn safe-test? [e] (let [tag (infer-tag e)] (or (#{'boolean 'seq} tag) (when (= (:op e) :constant) (let [form (:form e)] (not (or (and (string? form) (= form "")) (and (number? form) (zero? form))))))))) (defmethod emit :if [{:keys [test then else env unchecked]}] (let [context (:context env) checked (not (or unchecked (safe-test? test)))] (if (= :expr context) (emits "(" (when checked "cljs.core.truth_") "(" test ")?" then ":" else ")") (do (if checked (emitln "if(cljs.core.truth_(" test "))") (emitln "if(" test ")")) (emitln "{" then "} else") (emitln "{" else "}"))))) (defmethod emit :throw [{:keys [throw env]}] (if (= :expr (:context env)) (emits "(function(){throw " throw "})()") (emitln "throw " throw ";"))) (defn emit-comment "Emit a nicely formatted comment string." [doc jsdoc] (let [docs (when doc [doc]) docs (if jsdoc (concat docs jsdoc) docs) docs (remove nil? docs)] (letfn [(print-comment-lines [e] (doseq [next-line (string/split-lines e)] (emitln "* " (string/trim next-line))))] (when (seq docs) (emitln "/**") (doseq [e docs] (when e (print-comment-lines e))) (emitln "*/"))))) (defmethod emit :def [{:keys [name init env doc export]}] (when init (let [mname (munge name)] (emit-comment doc (:jsdoc init)) (emits mname) (emits " = " init) (when-not (= :expr (:context env)) (emitln ";")) (when export (emitln "goog.exportSymbol('" (munge export) "', " mname ");"))))) (defn emit-apply-to [{:keys [name params env]}] (let [arglist (gensym "arglist__") delegate-name (str (munge name) "__delegate") params (map munge params)] (emitln "(function (" arglist "){") (doseq [[i param] (map-indexed vector (butlast params))] (emits "var " param " = cljs.core.first(") (dotimes [_ i] (emits "cljs.core.next(")) (emits arglist ")") (dotimes [_ i] (emits ")")) (emitln ";")) (if (< 1 (count params)) (do (emits "var " (last params) " = cljs.core.rest(") (dotimes [_ (- (count params) 2)] (emits "cljs.core.next(")) (emits arglist) (dotimes [_ (- (count params) 2)] (emits ")")) (emitln ");") (emitln "return " delegate-name "(" (string/join ", " params) ");")) (do (emits "var " (last params) " = ") (emits "cljs.core.seq(" arglist ");") (emitln ";") (emitln "return " delegate-name "(" (string/join ", " params) ");"))) (emits "})"))) (defn emit-fn-method [{:keys [type name variadic params statements ret env recurs max-fixed-arity]}] (emit-wrap env (emitln "(function " (munge name) "(" (comma-sep (map munge params)) "){") (when type (emitln "var self__ = this;")) (when recurs (emitln "while(true){")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emits "})"))) (defn emit-variadic-fn-method [{:keys [type name variadic params statements ret env recurs max-fixed-arity] :as f}] (emit-wrap env (let [name (or name (gensym)) mname (munge name) params (map munge params) delegate-name (str mname "__delegate")] (emitln "(function() { ") (emitln "var " delegate-name " = function (" (comma-sep params) "){") (when recurs (emitln "while(true){")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emitln "};") (emitln "var " mname " = function (" (comma-sep (if variadic (concat (butlast params) ['var_args]) params)) "){") (when type (emitln "var self__ = this;")) (when variadic (emitln "var " (last params) " = null;") (emitln "if (goog.isDef(var_args)) {") (emitln " " (last params) " = cljs.core.array_seq(Array.prototype.slice.call(arguments, " (dec (count params)) "),0);") (emitln "} ")) (emitln "return " delegate-name ".call(" (string/join ", " (cons "this" params)) ");") (emitln "};") (emitln mname ".cljs$lang$maxFixedArity = " max-fixed-arity ";") (emits mname ".cljs$lang$applyTo = ") (emit-apply-to (assoc f :name name)) (emitln ";") (emitln mname ".cljs$lang$arity$variadic = " delegate-name ";") (emitln "return " mname ";") (emitln "})()")))) (defmethod emit :fn [{:keys [name env methods max-fixed-arity variadic recur-frames loop-lets]}] ;;fn statements get erased, serve no purpose and can pollute scope if named (when-not (= :statement (:context env)) (let [loop-locals (->> (concat (mapcat :params (filter #(and % @(:flag %)) recur-frames)) (mapcat :params loop-lets)) (map munge) seq)] (when loop-locals (when (= :return (:context env)) (emits "return ")) (emitln "((function (" (comma-sep (map munge loop-locals)) "){") (when-not (= :return (:context env)) (emits "return "))) (if (= 1 (count methods)) (if variadic (emit-variadic-fn-method (assoc (first methods) :name name)) (emit-fn-method (assoc (first methods) :name name))) (let [has-name? (and name true) name (or name (gensym)) mname (munge name) maxparams (map munge (apply max-key count (map :params methods))) mmap (into {} (map (fn [method] [(munge (symbol (str mname "__" (count (:params method))))) method]) methods)) ms (sort-by #(-> % second :params count) (seq mmap))] (when (= :return (:context env)) (emits "return ")) (emitln "(function() {") (emitln "var " mname " = null;") (doseq [[n meth] ms] (emits "var " n " = ") (if (:variadic meth) (emit-variadic-fn-method meth) (emit-fn-method meth)) (emitln ";")) (emitln mname " = function(" (comma-sep (if variadic (concat (butlast maxparams) ['var_args]) maxparams)) "){") (when variadic (emitln "var " (last maxparams) " = var_args;")) (emitln "switch(arguments.length){") (doseq [[n meth] ms] (if (:variadic meth) (do (emitln "default:") (emitln "return " n ".cljs$lang$arity$variadic(" (comma-sep (butlast maxparams)) (when (> (count maxparams) 1) ", ") "cljs.core.array_seq(arguments, " max-fixed-arity "));")) (let [pcnt (count (:params meth))] (emitln "case " pcnt ":") (emitln "return " n ".call(this" (if (zero? pcnt) nil (list "," (comma-sep (take pcnt maxparams)))) ");")))) (emitln "}") (emitln "throw(new Error('Invalid arity: ' + arguments.length));") (emitln "};") (when variadic (emitln mname ".cljs$lang$maxFixedArity = " max-fixed-arity ";") (emitln mname ".cljs$lang$applyTo = " (some #(let [[n m] %] (when (:variadic m) n)) ms) ".cljs$lang$applyTo;")) (when has-name? (doseq [[n meth] ms] (let [c (count (:params meth))] (if (:variadic meth) (emitln mname ".cljs$lang$arity$variadic = " n ".cljs$lang$arity$variadic;") (emitln mname ".cljs$lang$arity$" c " = " n ";"))))) (emitln "return " mname ";") (emitln "})()"))) (when loop-locals (emitln ";})(" (comma-sep loop-locals) "))"))))) (defmethod emit :do [{:keys [statements ret env]}] (let [context (:context env)] (when (and statements (= :expr context)) (emits "(function (){")) ;(when statements (emitln "{")) (emit-block context statements ret) ;(when statements (emits "}")) (when (and statements (= :expr context)) (emits "})()")))) (defmethod emit :try* [{:keys [env try catch name finally]}] (let [context (:context env) subcontext (if (= :expr context) :return context)] (if (or name finally) (do (when (= :expr context) (emits "(function (){")) (emits "try{") (let [{:keys [statements ret]} try] (emit-block subcontext statements ret)) (emits "}") (when name (emits "catch (" (munge name) "){") (when catch (let [{:keys [statements ret]} catch] (emit-block subcontext statements ret))) (emits "}")) (when finally (let [{:keys [statements ret]} finally] (assert (not= :constant (:op ret)) "finally block cannot contain constant") (emits "finally {") (emit-block subcontext statements ret) (emits "}"))) (when (= :expr context) (emits "})()"))) (let [{:keys [statements ret]} try] (when (and statements (= :expr context)) (emits "(function (){")) (emit-block subcontext statements ret) (when (and statements (= :expr context)) (emits "})()")))))) (defmethod emit :let [{:keys [bindings statements ret env loop]}] (let [context (:context env)] (when (= :expr context) (emits "(function (){")) (doseq [{:keys [init] :as binding} bindings] (emitln "var " (munge binding) " = " init ";")) (when loop (emitln "while(true){")) (emit-block (if (= :expr context) :return context) statements ret) (when loop (emitln "break;") (emitln "}")) ;(emits "}") (when (= :expr context) (emits "})()")))) (defmethod emit :recur [{:keys [frame exprs env]}] (let [temps (vec (take (count exprs) (repeatedly gensym))) params (:params frame)] (emitln "{") (dotimes [i (count exprs)] (emitln "var " (temps i) " = " (exprs i) ";")) (dotimes [i (count exprs)] (emitln (munge (params i)) " = " (temps i) ";")) (emitln "continue;") (emitln "}"))) (defmethod emit :letfn [{:keys [bindings statements ret env]}] (let [context (:context env)] (when (= :expr context) (emits "(function (){")) (doseq [{:keys [init] :as binding} bindings] (emitln "var " (munge binding) " = " init ";")) (emit-block (if (= :expr context) :return context) statements ret) (when (= :expr context) (emits "})()")))) (defn protocol-prefix [psym] (symbol (str (-> (str psym) (.replace \. \$) (.replace \/ \$)) "$"))) (defmethod emit :invoke [{:keys [f args env] :as expr}] (let [info (:info f) fn? (and ana/*cljs-static-fns* (not (:dynamic info)) (:fn-var info)) protocol (:protocol info) proto? (let [tag (infer-tag (first (:args expr)))] (and protocol tag (or ana/*cljs-static-fns* (:protocol-inline env)) (or (= protocol tag) (when-let [ps (:protocols (ana/resolve-existing-var (dissoc env :locals) tag))] (ps protocol))))) opt-not? (and (= (:name info) 'cljs.core/not) (= (infer-tag (first (:args expr))) 'boolean)) ns (:ns info) js? (= ns 'js) goog? (when ns (or (= ns 'goog) (when-let [ns-str (str ns)] (= (get (string/split ns-str #"\.") 0 nil) "goog")))) keyword? (and (= (-> f :op) :constant) (keyword? (-> f :form))) [f variadic-invoke] (if fn? (let [arity (count args) variadic? (:variadic info) mps (:method-params info) mfa (:max-fixed-arity info)] (cond ;; if only one method, no renaming needed (and (not variadic?) (= (count mps) 1)) [f nil] ;; direct dispatch to variadic case (and variadic? (> arity mfa)) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljs$lang$arity$variadic")))) {:max-fixed-arity mfa}] ;; direct dispatch to specific arity case :else (let [arities (map count mps)] (if (some #{arity} arities) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljs$lang$arity$" arity)))) nil] [f nil])))) [f nil])] (emit-wrap env (cond opt-not? (emits "!(" (first args) ")") proto? (let [pimpl (str (munge (protocol-prefix protocol)) (munge (name (:name info))) "$arity$" (count args))] (emits (first args) "." pimpl "(" (comma-sep args) ")")) keyword? (emits "(new cljs.core.Keyword(" f ")).call(" (comma-sep (cons "null" args)) ")") variadic-invoke (let [mfa (:max-fixed-arity variadic-invoke)] (emits f "(" (comma-sep (take mfa args)) (when-not (zero? mfa) ",") "cljs.core.array_seq([" (comma-sep (drop mfa args)) "], 0))")) (or fn? js? goog?) (emits f "(" (comma-sep args) ")") :else (if (and ana/*cljs-static-fns* (= (:op f) :var)) (let [fprop (str ".cljs$lang$arity$" (count args))] (emits "(" f fprop " ? " f fprop "(" (comma-sep args) ") : " f ".call(" (comma-sep (cons "null" args)) "))")) (emits f ".call(" (comma-sep (cons "null" args)) ")")))))) (defmethod emit :new [{:keys [ctor args env]}] (emit-wrap env (emits "(new " ctor "(" (comma-sep args) "))"))) (defmethod emit :set! [{:keys [target val env]}] (emit-wrap env (emits target " = " val))) (defmethod emit :ns [{:keys [name requires uses requires-macros env]}] (swap! ns-first-segments conj (first (string/split (str name) #"\."))) (emitln "goog.provide('" (munge name) "');") (when-not (= name 'cljs.core) (emitln "goog.require('cljs.core');")) (doseq [lib (into (vals requires) (distinct (vals uses)))] (emitln "goog.require('" (munge lib) "');"))) (defmethod emit :deftype* [{:keys [t fields pmasks]}] (let [fields (map munge fields)] (when-not (or (nil? *emitted-provides*) (contains? @*emitted-provides* t)) (swap! *emitted-provides* conj t) (emitln "") (emitln "goog.provide('" (munge t) "');")) (emitln "") (emitln "/**") (emitln "* @constructor") (emitln "*/") (emitln (munge t) " = (function (" (comma-sep fields) "){") (doseq [fld fields] (emitln "this." fld " = " fld ";")) (doseq [[pno pmask] pmasks] (emitln "this.cljs$lang$protocol_mask$partition" pno "$ = " pmask ";")) (emitln "})"))) (defmethod emit :defrecord* [{:keys [t fields pmasks]}] (let [fields (concat (map munge fields) '[__meta __extmap])] (when-not (or (nil? *emitted-provides*) (contains? @*emitted-provides* t)) (swap! *emitted-provides* conj t) (emitln "") (emitln "goog.provide('" (munge t) "');")) (emitln "") (emitln "/**") (emitln "* @constructor") (doseq [fld fields] (emitln "* @param {*} " fld)) (emitln "* @param {*=} __meta ") (emitln "* @param {*=} __extmap") (emitln "*/") (emitln (munge t) " = (function (" (comma-sep fields) "){") (doseq [fld fields] (emitln "this." fld " = " fld ";")) (doseq [[pno pmask] pmasks] (emitln "this.cljs$lang$protocol_mask$partition" pno "$ = " pmask ";")) (emitln "if(arguments.length>" (- (count fields) 2) "){") (emitln "this.__meta = __meta;") (emitln "this.__extmap = __extmap;") (emitln "} else {") (emits "this.__meta=") (emit-constant nil) (emitln ";") (emits "this.__extmap=") (emit-constant nil) (emitln ";") (emitln "}") (emitln "})"))) (defmethod emit :dot [{:keys [target field method args env]}] (emit-wrap env (if field (emits target "." (munge field #{})) (emits target "." (munge method #{}) "(" (comma-sep args) ")")))) (defmethod emit :js [{:keys [env code segs args]}] (emit-wrap env (if code (emits code) (emits (interleave (concat segs (repeat nil)) (concat args [nil])))))) (defn forms-seq "Seq of forms in a Clojure or ClojureScript file." ([f] (forms-seq f (clojure.lang.LineNumberingPushbackReader. (io/reader f)))) ([f ^java.io.PushbackReader rdr] (if-let [form (binding [*ns* ana/*reader-ns*] (read rdr nil nil))] (lazy-seq (cons form (forms-seq f rdr))) (.close rdr)))) (defn rename-to-js "Change the file extension from .cljs to .js. Takes a File or a String. Always returns a String." [file-str] (clojure.string/replace file-str #"\.cljs$" ".js")) (defn mkdirs "Create all parent directories for the passed file." [^java.io.File f] (.mkdirs (.getParentFile (.getCanonicalFile f)))) (defmacro with-core-cljs "Ensure that core.cljs has been loaded." [& body] `(do (when-not (:defs (get @ana/namespaces 'cljs.core)) (ana/analyze-file "cljs/core.cljs")) ~@body)) (defn compile-file* [src dest] (with-core-cljs (with-open [out ^java.io.Writer (io/make-writer dest {})] (binding [*out* out ana/*cljs-ns* 'cljs.user ana/*cljs-file* (.getPath ^java.io.File src) *data-readers* tags/*cljs-data-readers* *position* (atom [0 0]) *emitted-provides* (atom #{})] (loop [forms (forms-seq src) ns-name nil deps nil] (if (seq forms) (let [env (ana/empty-env) ast (ana/analyze env (first forms))] (do (emit ast) (if (= (:op ast) :ns) (recur (rest forms) (:name ast) (merge (:uses ast) (:requires ast))) (recur (rest forms) ns-name deps)))) {:ns (or ns-name 'cljs.user) :provides [ns-name] :requires (if (= ns-name 'cljs.core) (set (vals deps)) (conj (set (vals deps)) 'cljs.core)) :file dest})))))) (defn requires-compilation? "Return true if the src file requires compilation." [^java.io.File src ^java.io.File dest] (or (not (.exists dest)) (> (.lastModified src) (.lastModified dest)))) (defn compile-file "Compiles src to a file of the same name, but with a .js extension, in the src file's directory. With dest argument, write file to provided location. If the dest argument is a file outside the source tree, missing parent directories will be created. The src file will only be compiled if the dest file has an older modification time. Both src and dest may be either a String or a File. Returns a map containing {:ns .. :provides .. :requires .. :file ..}. If the file was not compiled returns only {:file ...}" ([src] (let [dest (rename-to-js src)] (compile-file src dest))) ([src dest] (let [src-file (io/file src) dest-file (io/file dest)] (if (.exists src-file) (if (requires-compilation? src-file dest-file) (do (mkdirs dest-file) (compile-file* src-file dest-file)) {:file dest-file}) (throw (java.io.FileNotFoundException. (str "The file " src " does not exist."))))))) (comment ;; flex compile-file (do (compile-file "/tmp/hello.cljs" "/tmp/something.js") (slurp "/tmp/hello.js") (compile-file "/tmp/somescript.cljs") (slurp "/tmp/somescript.js"))) (defn path-seq [file-str] (->> java.io.File/separator java.util.regex.Pattern/quote re-pattern (string/split file-str))) (defn to-path ([parts] (to-path parts java.io.File/separator)) ([parts sep] (apply str (interpose sep parts)))) (defn to-target-file "Given the source root directory, the output target directory and file under the source root, produce the target file." [^java.io.File dir ^String target ^java.io.File file] (let [dir-path (path-seq (.getAbsolutePath dir)) file-path (path-seq (.getAbsolutePath file)) relative-path (drop (count dir-path) file-path) parents (butlast relative-path) parent-file (java.io.File. ^String (to-path (cons target parents)))] (java.io.File. parent-file ^String (rename-to-js (last relative-path))))) (defn cljs-files-in "Return a sequence of all .cljs files in the given directory." [dir] (filter #(let [name (.getName ^java.io.File %)] (and (.endsWith name ".cljs") (not= \. (first name)) (not (contains? cljs-reserved-file-names name)))) (file-seq dir))) (defn compile-root "Looks recursively in src-dir for .cljs files and compiles them to .js files. If target-dir is provided, output will go into this directory mirroring the source directory structure. Returns a list of maps containing information about each file which was compiled in dependency order." ([src-dir] (compile-root src-dir "out")) ([src-dir target-dir] (let [src-dir-file (io/file src-dir)] (loop [cljs-files (cljs-files-in src-dir-file) output-files []] (if (seq cljs-files) (let [cljs-file (first cljs-files) output-file ^java.io.File (to-target-file src-dir-file target-dir cljs-file) ns-info (compile-file cljs-file output-file)] (recur (rest cljs-files) (conj output-files (assoc ns-info :file-name (.getPath output-file))))) output-files))))) (comment ;; compile-root ;; If you have a standard project layout with all file in src (compile-root "src") ;; will produce a mirrored directory structure under "out" but all ;; files will be compiled to js. ) (comment ;;the new way - use the REPL!! (require '[cljs.compiler :as comp]) (def repl-env (comp/repl-env)) (comp/repl repl-env) ;having problems?, try verbose mode (comp/repl repl-env :verbose true) ;don't forget to check for uses of undeclared vars (comp/repl repl-env :warn-on-undeclared true) (test-stuff) (+ 1 2 3) ([ 1 2 3 4] 2) ({:a 1 :b 2} :a) ({1 1 2 2} 1) (#{1 2 3} 2) (:b {:a 1 :b 2}) ('b '{:a 1 b 2}) (extend-type number ISeq (-seq [x] x)) (seq 42) ;(aset cljs.core.ISeq "number" true) ;(aget cljs.core.ISeq "number") (satisfies? ISeq 42) (extend-type nil ISeq (-seq [x] x)) (satisfies? ISeq nil) (seq nil) (extend-type default ISeq (-seq [x] x)) (satisfies? ISeq true) (seq true) (test-stuff) (array-seq []) (defn f [& etc] etc) (f) (in-ns 'cljs.core) ;;hack on core (deftype Foo [a] IMeta (-meta [_] (fn [] a))) ((-meta (Foo. 42))) ;;OLD way, don't you want to use the REPL? (in-ns 'cljs.compiler) (import '[javax.script ScriptEngineManager]) (def jse (-> (ScriptEngineManager.) (.getEngineByName "JavaScript"))) (.eval jse cljs.compiler/bootjs) (def envx {:ns (@namespaces 'cljs.user) :context :expr :locals '{ethel {:name ethel__123 :init nil}}}) (analyze envx nil) (analyze envx 42) (analyze envx "foo") (analyze envx 'fred) (analyze envx 'fred.x) (analyze envx 'ethel) (analyze envx 'ethel.x) (analyze envx 'my.ns/fred) (analyze envx 'your.ns.fred) (analyze envx '(if test then else)) (analyze envx '(if test then)) (analyze envx '(and fred ethel)) (analyze (assoc envx :context :statement) '(def test "fortytwo" 42)) (analyze (assoc envx :context :expr) '(fn* ^{::fields [a b c]} [x y] a y x)) (analyze (assoc envx :context :statement) '(let* [a 1 b 2] a)) (analyze (assoc envx :context :statement) '(defprotocol P (bar [a]) (baz [b c]))) (analyze (assoc envx :context :statement) '(. x y)) (analyze envx '(fn foo [x] (let [x 42] (js* "~{x}['foobar']")))) (analyze envx '(ns fred (:require [your.ns :as yn]) (:require-macros [clojure.core :as core]))) (defmacro js [form] `(emit (ana/analyze {:ns (@ana/namespaces 'cljs.user) :context :statement :locals {}} '~form))) (defn jscapture [form] "just grabs the js, doesn't print it" (with-out-str (emit (analyze {:ns (@namespaces 'cljs.user) :context :expr :locals {}} form)))) (defn jseval [form] (let [js (jscapture form)] ;;(prn js) (.eval jse (str "print(" js ")")))) ;; from closure.clj (optimize (jscapture '(defn foo [x y] (if true 46 (recur 1 x))))) (js (if a b c)) (js (def x 42)) (js (defn foo [a b] a)) (js (do 1 2 3)) (js (let [a 1 b 2 a b] a)) (js (ns fred (:require [your.ns :as yn]) (:require-macros [cljs.core :as core]))) (js (def foo? (fn* ^{::fields [a? b c]} [x y] (if true a? (recur 1 x))))) (js (def foo (fn* ^{::fields [a b c]} [x y] (if true a (recur 1 x))))) (js (defn foo [x y] (if true x y))) (jseval '(defn foo [x y] (if true x y))) (js (defn foo [x y] (if true 46 (recur 1 x)))) (jseval '(defn foo [x y] (if true 46 (recur 1 x)))) (jseval '(foo 1 2)) (js (and fred ethel)) (jseval '(ns fred (:require [your.ns :as yn]) (:require-macros [cljs.core :as core]))) (js (def x 42)) (jseval '(def x 42)) (jseval 'x) (jseval '(if 42 1 2)) (jseval '(or 1 2)) (jseval '(fn* [x y] (if true 46 (recur 1 x)))) (.eval jse "print(test)") (.eval jse "print(cljs.user.Foo)") (.eval jse "print(cljs.user.Foo = function (){\n}\n)") (js (def fred 42)) (js (deftype* Foo [a b-foo c])) (jseval '(deftype* Foo [a b-foo c])) (jseval '(. (new Foo 1 2 3) b-foo)) (js (. (new Foo 1 2 3) b)) (.eval jse "print(new cljs.user.Foo(1, 42, 3).b)") (.eval jse "(function (x, ys){return Array.prototype.slice.call(arguments, 1);})(1,2)[0]") (macroexpand-1 '(cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] b) (ethel [x] c) Ethel (foo [] d))) (-> (macroexpand-1 '(cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] b) (ethel [x] c) Ethel (foo [] d))) last last last first meta) (macroexpand-1 '(cljs.core/extend-type Foo Fred (fred ([x] a) ([x y] b)) (ethel ([x] c)) Ethel (foo ([] d)))) (js (new foo.Bar 65)) (js (defprotocol P (bar [a]) (baz [b c]))) (js (. x y)) (js (. "fred" (y))) (js (. x y 42 43)) (js (.. a b c d)) (js (. x (y 42 43))) (js (fn [x] x)) (js (fn ([t] t) ([x y] y) ([ a b & zs] b))) (js (. (fn foo ([t] t) ([x y] y) ([a b & zs] b)) call nil 1 2)) (js (fn foo ([t] t) ([x y] y) ([ a b & zs] b))) (js ((fn foo ([t] (foo t nil)) ([x y] y) ([ a b & zs] b)) 1 2 3)) (jseval '((fn foo ([t] t) ([x y] y) ([ a b & zs] zs)) 12 13 14 15)) (js (defn foo [this] this)) (js (defn foo [a b c & ys] ys)) (js ((fn [x & ys] ys) 1 2 3 4)) (jseval '((fn [x & ys] ys) 1 2 3 4)) (js (cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] a) (ethel [x] c) Ethel (foo [] d))) (jseval '(cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] a) (ethel [x] c) Ethel (foo [] d))) (js (do (defprotocol Proto (foo [this])) (deftype Type [a] Proto (foo [this] a)) (foo (new Type 42)))) (jseval '(do (defprotocol P-roto (foo? [this])) (deftype T-ype [a] P-roto (foo? [this] a)) (foo? (new T-ype 42)))) (js (def x (fn foo [x] (let [x 42] (js* "~{x}['foobar']"))))) (js (let [a 1 b 2 a b] a)) (doseq [e '[nil true false 42 "fred" fred ethel my.ns/fred your.ns.fred (if test then "fooelse") (def x 45) (do x y y) (fn* [x y] x y x) (fn* [x y] (if true 46 (recur 1 x))) (let* [a 1 b 2 a a] a b) (do "do1") (loop* [x 1 y 2] (if true 42 (do (recur 43 44)))) (my.foo 1 2 3) (let* [a 1 b 2 c 3] (set! y.s.d b) (new fred.Ethel a b c)) (let [x (do 1 2 3)] x) ]] (->> e (analyze envx) emit) (newline)))
87983
; 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. (set! *warn-on-reflection* true) (ns cljs.compiler (:refer-clojure :exclude [munge macroexpand-1]) (:require [clojure.java.io :as io] [clojure.string :as string] [cljs.tagged-literals :as tags] [cljs.analyzer :as ana]) (:import java.lang.StringBuilder)) (declare munge) (def js-reserved #{"abstract" "boolean" "break" "byte" "case" "catch" "char" "class" "const" "continue" "debugger" "default" "delete" "do" "double" "else" "enum" "export" "extends" "final" "finally" "float" "for" "function" "goto" "if" "implements" "import" "in" "instanceof" "int" "interface" "let" "long" "native" "new" "package" "private" "protected" "public" "return" "short" "static" "super" "switch" "synchronized" "this" "throw" "throws" "transient" "try" "typeof" "var" "void" "volatile" "while" "with" "yield" "methods"}) (def ^:dynamic *position* nil) (def ^:dynamic *emitted-provides* nil) (def cljs-reserved-file-names #{"deps.cljs"}) (defonce ns-first-segments (atom '#{"cljs" "clojure"})) (defn munge ([s] (munge s js-reserved)) ([s reserved] (if (map? s) ; Unshadowing (let [{:keys [name field] :as info} s depth (loop [d 0, {:keys [shadow]} info] (cond shadow (recur (inc d) shadow) (@ns-first-segments (str name)) (inc d) :else d)) name (if field (str "self__." name) name)] (if (zero? depth) (munge name reserved) (symbol (str (munge name reserved) "__$" depth)))) ; String munging (let [ss (string/replace (str s) #"\/(.)" ".$1") ; Division is special ss (apply str (map #(if (reserved %) (str % "$") %) (string/split ss #"(?<=\.)|(?=\.)"))) ms (clojure.lang.Compiler/munge ss)] (if (symbol? s) (symbol ms) ms))))) (defn- comma-sep [xs] (interpose "," xs)) (defn- escape-char [^Character c] (let [cp (.hashCode c)] (case cp ; Handle printable escapes before ASCII 34 "\\\"" 92 "\\\\" ; Handle non-printable escapes 8 "\\b" 12 "\\f" 10 "\\n" 13 "\\r" 9 "\\t" (if (< 31 cp 127) c ; Print simple ASCII characters (format "\\u%04X" cp))))) ; Any other character is Unicode (defn- escape-string [^CharSequence s] (let [sb (StringBuilder. (count s))] (doseq [c s] (.append sb (escape-char c))) (.toString sb))) (defn- wrap-in-double-quotes [x] (str \" x \")) (defmulti emit :op) (defn emits [& xs] (doseq [x xs] (cond (nil? x) nil (map? x) (emit x) (seq? x) (apply emits x) (fn? x) (x) :else (do (let [s (print-str x)] (when *position* (swap! *position* (fn [[line column]] [line (+ column (count s))]))) (print s))))) nil) (defn ^String emit-str [expr] (with-out-str (emit expr))) (defn emitln [& xs] (apply emits xs) ;; Prints column-aligned line number comments; good test of *position*. ;(when *position* ; (let [[line column] @*position*] ; (print (apply str (concat (repeat (- 120 column) \space) ["// " (inc line)]))))) (println) (when *position* (swap! *position* (fn [[line column]] [(inc line) 0]))) nil) (defmulti emit-constant class) (defmethod emit-constant nil [x] (emits "null")) (defmethod emit-constant Long [x] (emits x)) (defmethod emit-constant Integer [x] (emits x)) ; reader puts Integers in metadata (defmethod emit-constant Double [x] (emits x)) (defmethod emit-constant String [x] (emits (wrap-in-double-quotes (escape-string x)))) (defmethod emit-constant Boolean [x] (emits (if x "true" "false"))) (defmethod emit-constant Character [x] (emits (wrap-in-double-quotes (escape-char x)))) (defmethod emit-constant java.util.regex.Pattern [x] (let [[_ flags pattern] (re-find #"^(?:\(\?([idmsux]*)\))?(.*)" (str x))] (emits \/ (.replaceAll (re-matcher #"/" pattern) "\\\\/") \/ flags))) (defmethod emit-constant clojure.lang.Keyword [x] (emits \" "\\uFDD0" \' (if (namespace x) (str (namespace x) "/") "") (name x) \")) (defmethod emit-constant clojure.lang.Symbol [x] (emits \" "\\uFDD1" \' (if (namespace x) (str (namespace x) "/") "") (name x) \")) (defn- emit-meta-constant [x & body] (if (meta x) (do (emits "cljs.core.with_meta(" body ",") (emit-constant (meta x)) (emits ")")) (emits body))) (defmethod emit-constant clojure.lang.PersistentList$EmptyList [x] (emit-meta-constant x "cljs.core.List.EMPTY")) (defmethod emit-constant clojure.lang.PersistentList [x] (emit-meta-constant x (concat ["cljs.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.Cons [x] (emit-meta-constant x (concat ["cljs.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.IPersistentVector [x] (emit-meta-constant x (concat ["cljs.core.vec(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defmethod emit-constant clojure.lang.IPersistentMap [x] (emit-meta-constant x (concat ["cljs.core.hash_map("] (comma-sep (map #(fn [] (emit-constant %)) (apply concat x))) [")"]))) (defmethod emit-constant clojure.lang.PersistentHashSet [x] (emit-meta-constant x (concat ["cljs.core.set(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defn emit-block [context statements ret] (when statements (emits statements)) (emit ret)) (defmacro emit-wrap [env & body] `(let [env# ~env] (when (= :return (:context env#)) (emits "return ")) ~@body (when-not (= :expr (:context env#)) (emitln ";")))) (defmethod emit :no-op [m]) (defmethod emit :var [{:keys [info env] :as arg}] (let [n (:name info) n (if (= (namespace n) "js") (name n) info)] (emit-wrap env (emits (munge n))))) (defmethod emit :meta [{:keys [expr meta env]}] (emit-wrap env (emits "cljs.core.with_meta(" expr "," meta ")"))) (def ^:private array-map-threshold 16) (def ^:private obj-map-threshold 32) (defmethod emit :map [{:keys [env simple-keys? keys vals]}] (emit-wrap env (cond (zero? (count keys)) (emits "cljs.core.ObjMap.EMPTY") (and simple-keys? (<= (count keys) obj-map-threshold)) (emits "cljs.core.ObjMap.fromObject([" (comma-sep keys) ; keys "],{" (comma-sep (map (fn [k v] (with-out-str (emit k) (print ":") (emit v))) keys vals)) ; js obj "})") (<= (count keys) array-map-threshold) (emits "cljs.core.PersistentArrayMap.fromArrays([" (comma-sep keys) "],[" (comma-sep vals) "])") :else (emits "cljs.core.PersistentHashMap.fromArrays([" (comma-sep keys) "],[" (comma-sep vals) "])")))) (defmethod emit :vector [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "cljs.core.PersistentVector.EMPTY") (emits "cljs.core.PersistentVector.fromArray([" (comma-sep items) "], true)")))) (defmethod emit :set [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "cljs.core.PersistentHashSet.EMPTY") (emits "cljs.core.PersistentHashSet.fromArray([" (comma-sep items) "])")))) (defmethod emit :constant [{:keys [form env]}] (when-not (= :statement (:context env)) (emit-wrap env (emit-constant form)))) (defn get-tag [e] (or (-> e :tag) (-> e :info :tag))) (defn infer-tag [e] (if-let [tag (get-tag e)] tag (case (:op e) :let (infer-tag (:ret e)) :if (let [then-tag (infer-tag (:then e)) else-tag (infer-tag (:else e))] (when (= then-tag else-tag) then-tag)) :constant (case (:form e) true 'boolean false 'boolean nil) nil))) (defn safe-test? [e] (let [tag (infer-tag e)] (or (#{'boolean 'seq} tag) (when (= (:op e) :constant) (let [form (:form e)] (not (or (and (string? form) (= form "")) (and (number? form) (zero? form))))))))) (defmethod emit :if [{:keys [test then else env unchecked]}] (let [context (:context env) checked (not (or unchecked (safe-test? test)))] (if (= :expr context) (emits "(" (when checked "cljs.core.truth_") "(" test ")?" then ":" else ")") (do (if checked (emitln "if(cljs.core.truth_(" test "))") (emitln "if(" test ")")) (emitln "{" then "} else") (emitln "{" else "}"))))) (defmethod emit :throw [{:keys [throw env]}] (if (= :expr (:context env)) (emits "(function(){throw " throw "})()") (emitln "throw " throw ";"))) (defn emit-comment "Emit a nicely formatted comment string." [doc jsdoc] (let [docs (when doc [doc]) docs (if jsdoc (concat docs jsdoc) docs) docs (remove nil? docs)] (letfn [(print-comment-lines [e] (doseq [next-line (string/split-lines e)] (emitln "* " (string/trim next-line))))] (when (seq docs) (emitln "/**") (doseq [e docs] (when e (print-comment-lines e))) (emitln "*/"))))) (defmethod emit :def [{:keys [name init env doc export]}] (when init (let [mname (munge name)] (emit-comment doc (:jsdoc init)) (emits mname) (emits " = " init) (when-not (= :expr (:context env)) (emitln ";")) (when export (emitln "goog.exportSymbol('" (munge export) "', " mname ");"))))) (defn emit-apply-to [{:keys [name params env]}] (let [arglist (gensym "arglist__") delegate-name (str (munge name) "__delegate") params (map munge params)] (emitln "(function (" arglist "){") (doseq [[i param] (map-indexed vector (butlast params))] (emits "var " param " = cljs.core.first(") (dotimes [_ i] (emits "cljs.core.next(")) (emits arglist ")") (dotimes [_ i] (emits ")")) (emitln ";")) (if (< 1 (count params)) (do (emits "var " (last params) " = cljs.core.rest(") (dotimes [_ (- (count params) 2)] (emits "cljs.core.next(")) (emits arglist) (dotimes [_ (- (count params) 2)] (emits ")")) (emitln ");") (emitln "return " delegate-name "(" (string/join ", " params) ");")) (do (emits "var " (last params) " = ") (emits "cljs.core.seq(" arglist ");") (emitln ";") (emitln "return " delegate-name "(" (string/join ", " params) ");"))) (emits "})"))) (defn emit-fn-method [{:keys [type name variadic params statements ret env recurs max-fixed-arity]}] (emit-wrap env (emitln "(function " (munge name) "(" (comma-sep (map munge params)) "){") (when type (emitln "var self__ = this;")) (when recurs (emitln "while(true){")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emits "})"))) (defn emit-variadic-fn-method [{:keys [type name variadic params statements ret env recurs max-fixed-arity] :as f}] (emit-wrap env (let [name (or name (gensym)) mname (munge name) params (map munge params) delegate-name (str mname "__delegate")] (emitln "(function() { ") (emitln "var " delegate-name " = function (" (comma-sep params) "){") (when recurs (emitln "while(true){")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emitln "};") (emitln "var " mname " = function (" (comma-sep (if variadic (concat (butlast params) ['var_args]) params)) "){") (when type (emitln "var self__ = this;")) (when variadic (emitln "var " (last params) " = null;") (emitln "if (goog.isDef(var_args)) {") (emitln " " (last params) " = cljs.core.array_seq(Array.prototype.slice.call(arguments, " (dec (count params)) "),0);") (emitln "} ")) (emitln "return " delegate-name ".call(" (string/join ", " (cons "this" params)) ");") (emitln "};") (emitln mname ".cljs$lang$maxFixedArity = " max-fixed-arity ";") (emits mname ".cljs$lang$applyTo = ") (emit-apply-to (assoc f :name name)) (emitln ";") (emitln mname ".cljs$lang$arity$variadic = " delegate-name ";") (emitln "return " mname ";") (emitln "})()")))) (defmethod emit :fn [{:keys [name env methods max-fixed-arity variadic recur-frames loop-lets]}] ;;fn statements get erased, serve no purpose and can pollute scope if named (when-not (= :statement (:context env)) (let [loop-locals (->> (concat (mapcat :params (filter #(and % @(:flag %)) recur-frames)) (mapcat :params loop-lets)) (map munge) seq)] (when loop-locals (when (= :return (:context env)) (emits "return ")) (emitln "((function (" (comma-sep (map munge loop-locals)) "){") (when-not (= :return (:context env)) (emits "return "))) (if (= 1 (count methods)) (if variadic (emit-variadic-fn-method (assoc (first methods) :name name)) (emit-fn-method (assoc (first methods) :name name))) (let [has-name? (and name true) name (or name (gensym)) mname (munge name) maxparams (map munge (apply max-key count (map :params methods))) mmap (into {} (map (fn [method] [(munge (symbol (str mname "__" (count (:params method))))) method]) methods)) ms (sort-by #(-> % second :params count) (seq mmap))] (when (= :return (:context env)) (emits "return ")) (emitln "(function() {") (emitln "var " mname " = null;") (doseq [[n meth] ms] (emits "var " n " = ") (if (:variadic meth) (emit-variadic-fn-method meth) (emit-fn-method meth)) (emitln ";")) (emitln mname " = function(" (comma-sep (if variadic (concat (butlast maxparams) ['var_args]) maxparams)) "){") (when variadic (emitln "var " (last maxparams) " = var_args;")) (emitln "switch(arguments.length){") (doseq [[n meth] ms] (if (:variadic meth) (do (emitln "default:") (emitln "return " n ".cljs$lang$arity$variadic(" (comma-sep (butlast maxparams)) (when (> (count maxparams) 1) ", ") "cljs.core.array_seq(arguments, " max-fixed-arity "));")) (let [pcnt (count (:params meth))] (emitln "case " pcnt ":") (emitln "return " n ".call(this" (if (zero? pcnt) nil (list "," (comma-sep (take pcnt maxparams)))) ");")))) (emitln "}") (emitln "throw(new Error('Invalid arity: ' + arguments.length));") (emitln "};") (when variadic (emitln mname ".cljs$lang$maxFixedArity = " max-fixed-arity ";") (emitln mname ".cljs$lang$applyTo = " (some #(let [[n m] %] (when (:variadic m) n)) ms) ".cljs$lang$applyTo;")) (when has-name? (doseq [[n meth] ms] (let [c (count (:params meth))] (if (:variadic meth) (emitln mname ".cljs$lang$arity$variadic = " n ".cljs$lang$arity$variadic;") (emitln mname ".cljs$lang$arity$" c " = " n ";"))))) (emitln "return " mname ";") (emitln "})()"))) (when loop-locals (emitln ";})(" (comma-sep loop-locals) "))"))))) (defmethod emit :do [{:keys [statements ret env]}] (let [context (:context env)] (when (and statements (= :expr context)) (emits "(function (){")) ;(when statements (emitln "{")) (emit-block context statements ret) ;(when statements (emits "}")) (when (and statements (= :expr context)) (emits "})()")))) (defmethod emit :try* [{:keys [env try catch name finally]}] (let [context (:context env) subcontext (if (= :expr context) :return context)] (if (or name finally) (do (when (= :expr context) (emits "(function (){")) (emits "try{") (let [{:keys [statements ret]} try] (emit-block subcontext statements ret)) (emits "}") (when name (emits "catch (" (munge name) "){") (when catch (let [{:keys [statements ret]} catch] (emit-block subcontext statements ret))) (emits "}")) (when finally (let [{:keys [statements ret]} finally] (assert (not= :constant (:op ret)) "finally block cannot contain constant") (emits "finally {") (emit-block subcontext statements ret) (emits "}"))) (when (= :expr context) (emits "})()"))) (let [{:keys [statements ret]} try] (when (and statements (= :expr context)) (emits "(function (){")) (emit-block subcontext statements ret) (when (and statements (= :expr context)) (emits "})()")))))) (defmethod emit :let [{:keys [bindings statements ret env loop]}] (let [context (:context env)] (when (= :expr context) (emits "(function (){")) (doseq [{:keys [init] :as binding} bindings] (emitln "var " (munge binding) " = " init ";")) (when loop (emitln "while(true){")) (emit-block (if (= :expr context) :return context) statements ret) (when loop (emitln "break;") (emitln "}")) ;(emits "}") (when (= :expr context) (emits "})()")))) (defmethod emit :recur [{:keys [frame exprs env]}] (let [temps (vec (take (count exprs) (repeatedly gensym))) params (:params frame)] (emitln "{") (dotimes [i (count exprs)] (emitln "var " (temps i) " = " (exprs i) ";")) (dotimes [i (count exprs)] (emitln (munge (params i)) " = " (temps i) ";")) (emitln "continue;") (emitln "}"))) (defmethod emit :letfn [{:keys [bindings statements ret env]}] (let [context (:context env)] (when (= :expr context) (emits "(function (){")) (doseq [{:keys [init] :as binding} bindings] (emitln "var " (munge binding) " = " init ";")) (emit-block (if (= :expr context) :return context) statements ret) (when (= :expr context) (emits "})()")))) (defn protocol-prefix [psym] (symbol (str (-> (str psym) (.replace \. \$) (.replace \/ \$)) "$"))) (defmethod emit :invoke [{:keys [f args env] :as expr}] (let [info (:info f) fn? (and ana/*cljs-static-fns* (not (:dynamic info)) (:fn-var info)) protocol (:protocol info) proto? (let [tag (infer-tag (first (:args expr)))] (and protocol tag (or ana/*cljs-static-fns* (:protocol-inline env)) (or (= protocol tag) (when-let [ps (:protocols (ana/resolve-existing-var (dissoc env :locals) tag))] (ps protocol))))) opt-not? (and (= (:name info) 'cljs.core/not) (= (infer-tag (first (:args expr))) 'boolean)) ns (:ns info) js? (= ns 'js) goog? (when ns (or (= ns 'goog) (when-let [ns-str (str ns)] (= (get (string/split ns-str #"\.") 0 nil) "goog")))) keyword? (and (= (-> f :op) :constant) (keyword? (-> f :form))) [f variadic-invoke] (if fn? (let [arity (count args) variadic? (:variadic info) mps (:method-params info) mfa (:max-fixed-arity info)] (cond ;; if only one method, no renaming needed (and (not variadic?) (= (count mps) 1)) [f nil] ;; direct dispatch to variadic case (and variadic? (> arity mfa)) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljs$lang$arity$variadic")))) {:max-fixed-arity mfa}] ;; direct dispatch to specific arity case :else (let [arities (map count mps)] (if (some #{arity} arities) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljs$lang$arity$" arity)))) nil] [f nil])))) [f nil])] (emit-wrap env (cond opt-not? (emits "!(" (first args) ")") proto? (let [pimpl (str (munge (protocol-prefix protocol)) (munge (name (:name info))) "$arity$" (count args))] (emits (first args) "." pimpl "(" (comma-sep args) ")")) keyword? (emits "(new cljs.core.Keyword(" f ")).call(" (comma-sep (cons "null" args)) ")") variadic-invoke (let [mfa (:max-fixed-arity variadic-invoke)] (emits f "(" (comma-sep (take mfa args)) (when-not (zero? mfa) ",") "cljs.core.array_seq([" (comma-sep (drop mfa args)) "], 0))")) (or fn? js? goog?) (emits f "(" (comma-sep args) ")") :else (if (and ana/*cljs-static-fns* (= (:op f) :var)) (let [fprop (str ".cljs$lang$arity$" (count args))] (emits "(" f fprop " ? " f fprop "(" (comma-sep args) ") : " f ".call(" (comma-sep (cons "null" args)) "))")) (emits f ".call(" (comma-sep (cons "null" args)) ")")))))) (defmethod emit :new [{:keys [ctor args env]}] (emit-wrap env (emits "(new " ctor "(" (comma-sep args) "))"))) (defmethod emit :set! [{:keys [target val env]}] (emit-wrap env (emits target " = " val))) (defmethod emit :ns [{:keys [name requires uses requires-macros env]}] (swap! ns-first-segments conj (first (string/split (str name) #"\."))) (emitln "goog.provide('" (munge name) "');") (when-not (= name 'cljs.core) (emitln "goog.require('cljs.core');")) (doseq [lib (into (vals requires) (distinct (vals uses)))] (emitln "goog.require('" (munge lib) "');"))) (defmethod emit :deftype* [{:keys [t fields pmasks]}] (let [fields (map munge fields)] (when-not (or (nil? *emitted-provides*) (contains? @*emitted-provides* t)) (swap! *emitted-provides* conj t) (emitln "") (emitln "goog.provide('" (munge t) "');")) (emitln "") (emitln "/**") (emitln "* @constructor") (emitln "*/") (emitln (munge t) " = (function (" (comma-sep fields) "){") (doseq [fld fields] (emitln "this." fld " = " fld ";")) (doseq [[pno pmask] pmasks] (emitln "this.cljs$lang$protocol_mask$partition" pno "$ = " pmask ";")) (emitln "})"))) (defmethod emit :defrecord* [{:keys [t fields pmasks]}] (let [fields (concat (map munge fields) '[__meta __extmap])] (when-not (or (nil? *emitted-provides*) (contains? @*emitted-provides* t)) (swap! *emitted-provides* conj t) (emitln "") (emitln "goog.provide('" (munge t) "');")) (emitln "") (emitln "/**") (emitln "* @constructor") (doseq [fld fields] (emitln "* @param {*} " fld)) (emitln "* @param {*=} __meta ") (emitln "* @param {*=} __extmap") (emitln "*/") (emitln (munge t) " = (function (" (comma-sep fields) "){") (doseq [fld fields] (emitln "this." fld " = " fld ";")) (doseq [[pno pmask] pmasks] (emitln "this.cljs$lang$protocol_mask$partition" pno "$ = " pmask ";")) (emitln "if(arguments.length>" (- (count fields) 2) "){") (emitln "this.__meta = __meta;") (emitln "this.__extmap = __extmap;") (emitln "} else {") (emits "this.__meta=") (emit-constant nil) (emitln ";") (emits "this.__extmap=") (emit-constant nil) (emitln ";") (emitln "}") (emitln "})"))) (defmethod emit :dot [{:keys [target field method args env]}] (emit-wrap env (if field (emits target "." (munge field #{})) (emits target "." (munge method #{}) "(" (comma-sep args) ")")))) (defmethod emit :js [{:keys [env code segs args]}] (emit-wrap env (if code (emits code) (emits (interleave (concat segs (repeat nil)) (concat args [nil])))))) (defn forms-seq "Seq of forms in a Clojure or ClojureScript file." ([f] (forms-seq f (clojure.lang.LineNumberingPushbackReader. (io/reader f)))) ([f ^java.io.PushbackReader rdr] (if-let [form (binding [*ns* ana/*reader-ns*] (read rdr nil nil))] (lazy-seq (cons form (forms-seq f rdr))) (.close rdr)))) (defn rename-to-js "Change the file extension from .cljs to .js. Takes a File or a String. Always returns a String." [file-str] (clojure.string/replace file-str #"\.cljs$" ".js")) (defn mkdirs "Create all parent directories for the passed file." [^java.io.File f] (.mkdirs (.getParentFile (.getCanonicalFile f)))) (defmacro with-core-cljs "Ensure that core.cljs has been loaded." [& body] `(do (when-not (:defs (get @ana/namespaces 'cljs.core)) (ana/analyze-file "cljs/core.cljs")) ~@body)) (defn compile-file* [src dest] (with-core-cljs (with-open [out ^java.io.Writer (io/make-writer dest {})] (binding [*out* out ana/*cljs-ns* 'cljs.user ana/*cljs-file* (.getPath ^java.io.File src) *data-readers* tags/*cljs-data-readers* *position* (atom [0 0]) *emitted-provides* (atom #{})] (loop [forms (forms-seq src) ns-name nil deps nil] (if (seq forms) (let [env (ana/empty-env) ast (ana/analyze env (first forms))] (do (emit ast) (if (= (:op ast) :ns) (recur (rest forms) (:name ast) (merge (:uses ast) (:requires ast))) (recur (rest forms) ns-name deps)))) {:ns (or ns-name 'cljs.user) :provides [ns-name] :requires (if (= ns-name 'cljs.core) (set (vals deps)) (conj (set (vals deps)) 'cljs.core)) :file dest})))))) (defn requires-compilation? "Return true if the src file requires compilation." [^java.io.File src ^java.io.File dest] (or (not (.exists dest)) (> (.lastModified src) (.lastModified dest)))) (defn compile-file "Compiles src to a file of the same name, but with a .js extension, in the src file's directory. With dest argument, write file to provided location. If the dest argument is a file outside the source tree, missing parent directories will be created. The src file will only be compiled if the dest file has an older modification time. Both src and dest may be either a String or a File. Returns a map containing {:ns .. :provides .. :requires .. :file ..}. If the file was not compiled returns only {:file ...}" ([src] (let [dest (rename-to-js src)] (compile-file src dest))) ([src dest] (let [src-file (io/file src) dest-file (io/file dest)] (if (.exists src-file) (if (requires-compilation? src-file dest-file) (do (mkdirs dest-file) (compile-file* src-file dest-file)) {:file dest-file}) (throw (java.io.FileNotFoundException. (str "The file " src " does not exist."))))))) (comment ;; flex compile-file (do (compile-file "/tmp/hello.cljs" "/tmp/something.js") (slurp "/tmp/hello.js") (compile-file "/tmp/somescript.cljs") (slurp "/tmp/somescript.js"))) (defn path-seq [file-str] (->> java.io.File/separator java.util.regex.Pattern/quote re-pattern (string/split file-str))) (defn to-path ([parts] (to-path parts java.io.File/separator)) ([parts sep] (apply str (interpose sep parts)))) (defn to-target-file "Given the source root directory, the output target directory and file under the source root, produce the target file." [^java.io.File dir ^String target ^java.io.File file] (let [dir-path (path-seq (.getAbsolutePath dir)) file-path (path-seq (.getAbsolutePath file)) relative-path (drop (count dir-path) file-path) parents (butlast relative-path) parent-file (java.io.File. ^String (to-path (cons target parents)))] (java.io.File. parent-file ^String (rename-to-js (last relative-path))))) (defn cljs-files-in "Return a sequence of all .cljs files in the given directory." [dir] (filter #(let [name (.getName ^java.io.File %)] (and (.endsWith name ".cljs") (not= \. (first name)) (not (contains? cljs-reserved-file-names name)))) (file-seq dir))) (defn compile-root "Looks recursively in src-dir for .cljs files and compiles them to .js files. If target-dir is provided, output will go into this directory mirroring the source directory structure. Returns a list of maps containing information about each file which was compiled in dependency order." ([src-dir] (compile-root src-dir "out")) ([src-dir target-dir] (let [src-dir-file (io/file src-dir)] (loop [cljs-files (cljs-files-in src-dir-file) output-files []] (if (seq cljs-files) (let [cljs-file (first cljs-files) output-file ^java.io.File (to-target-file src-dir-file target-dir cljs-file) ns-info (compile-file cljs-file output-file)] (recur (rest cljs-files) (conj output-files (assoc ns-info :file-name (.getPath output-file))))) output-files))))) (comment ;; compile-root ;; If you have a standard project layout with all file in src (compile-root "src") ;; will produce a mirrored directory structure under "out" but all ;; files will be compiled to js. ) (comment ;;the new way - use the REPL!! (require '[cljs.compiler :as comp]) (def repl-env (comp/repl-env)) (comp/repl repl-env) ;having problems?, try verbose mode (comp/repl repl-env :verbose true) ;don't forget to check for uses of undeclared vars (comp/repl repl-env :warn-on-undeclared true) (test-stuff) (+ 1 2 3) ([ 1 2 3 4] 2) ({:a 1 :b 2} :a) ({1 1 2 2} 1) (#{1 2 3} 2) (:b {:a 1 :b 2}) ('b '{:a 1 b 2}) (extend-type number ISeq (-seq [x] x)) (seq 42) ;(aset cljs.core.ISeq "number" true) ;(aget cljs.core.ISeq "number") (satisfies? ISeq 42) (extend-type nil ISeq (-seq [x] x)) (satisfies? ISeq nil) (seq nil) (extend-type default ISeq (-seq [x] x)) (satisfies? ISeq true) (seq true) (test-stuff) (array-seq []) (defn f [& etc] etc) (f) (in-ns 'cljs.core) ;;hack on core (deftype Foo [a] IMeta (-meta [_] (fn [] a))) ((-meta (Foo. 42))) ;;OLD way, don't you want to use the REPL? (in-ns 'cljs.compiler) (import '[javax.script ScriptEngineManager]) (def jse (-> (ScriptEngineManager.) (.getEngineByName "JavaScript"))) (.eval jse cljs.compiler/bootjs) (def envx {:ns (@namespaces 'cljs.user) :context :expr :locals '{ethel {:name ethel__123 :init nil}}}) (analyze envx nil) (analyze envx 42) (analyze envx "foo") (analyze envx 'fred) (analyze envx 'fred.x) (analyze envx 'ethel) (analyze envx 'ethel.x) (analyze envx 'my.ns/fred) (analyze envx 'your.ns.fred) (analyze envx '(if test then else)) (analyze envx '(if test then)) (analyze envx '(and fred ethel)) (analyze (assoc envx :context :statement) '(def test "fortytwo" 42)) (analyze (assoc envx :context :expr) '(fn* ^{::fields [a b c]} [x y] a y x)) (analyze (assoc envx :context :statement) '(let* [a 1 b 2] a)) (analyze (assoc envx :context :statement) '(defprotocol P (bar [a]) (baz [b c]))) (analyze (assoc envx :context :statement) '(. x y)) (analyze envx '(fn foo [x] (let [x 42] (js* "~{x}['foobar']")))) (analyze envx '(ns fred (:require [your.ns :as yn]) (:require-macros [clojure.core :as core]))) (defmacro js [form] `(emit (ana/analyze {:ns (@ana/namespaces 'cljs.user) :context :statement :locals {}} '~form))) (defn jscapture [form] "just grabs the js, doesn't print it" (with-out-str (emit (analyze {:ns (@namespaces 'cljs.user) :context :expr :locals {}} form)))) (defn jseval [form] (let [js (jscapture form)] ;;(prn js) (.eval jse (str "print(" js ")")))) ;; from closure.clj (optimize (jscapture '(defn foo [x y] (if true 46 (recur 1 x))))) (js (if a b c)) (js (def x 42)) (js (defn foo [a b] a)) (js (do 1 2 3)) (js (let [a 1 b 2 a b] a)) (js (ns fred (:require [your.ns :as yn]) (:require-macros [cljs.core :as core]))) (js (def foo? (fn* ^{::fields [a? b c]} [x y] (if true a? (recur 1 x))))) (js (def foo (fn* ^{::fields [a b c]} [x y] (if true a (recur 1 x))))) (js (defn foo [x y] (if true x y))) (jseval '(defn foo [x y] (if true x y))) (js (defn foo [x y] (if true 46 (recur 1 x)))) (jseval '(defn foo [x y] (if true 46 (recur 1 x)))) (jseval '(foo 1 2)) (js (and fred ethel)) (jseval '(ns fred (:require [your.ns :as yn]) (:require-macros [cljs.core :as core]))) (js (def x 42)) (jseval '(def x 42)) (jseval 'x) (jseval '(if 42 1 2)) (jseval '(or 1 2)) (jseval '(fn* [x y] (if true 46 (recur 1 x)))) (.eval jse "print(test)") (.eval jse "print(cljs.user.Foo)") (.eval jse "print(cljs.user.Foo = function (){\n}\n)") (js (def fred 42)) (js (deftype* Foo [a b-foo c])) (jseval '(deftype* Foo [a b-foo c])) (jseval '(. (new Foo 1 2 3) b-foo)) (js (. (new Foo 1 2 3) b)) (.eval jse "print(new cljs.user.Foo(1, 42, 3).b)") (.eval jse "(function (x, ys){return Array.prototype.slice.call(arguments, 1);})(1,2)[0]") (macroexpand-1 '(cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] b) (ethel [x] c) Ethel (foo [] d))) (-> (macroexpand-1 '(cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] b) (ethel [x] c) Ethel (foo [] d))) last last last first meta) (macroexpand-1 '(cljs.core/extend-type Foo Fred (fred ([x] a) ([x y] b)) (ethel ([x] c)) Ethel (foo ([] d)))) (js (new foo.Bar 65)) (js (defprotocol P (bar [a]) (baz [b c]))) (js (. x y)) (js (. "fred" (y))) (js (. x y 42 43)) (js (.. a b c d)) (js (. x (y 42 43))) (js (fn [x] x)) (js (fn ([t] t) ([x y] y) ([ a b & zs] b))) (js (. (fn foo ([t] t) ([x y] y) ([a b & zs] b)) call nil 1 2)) (js (fn foo ([t] t) ([x y] y) ([ a b & zs] b))) (js ((fn foo ([t] (foo t nil)) ([x y] y) ([ a b & zs] b)) 1 2 3)) (jseval '((fn foo ([t] t) ([x y] y) ([ a b & zs] zs)) 12 13 14 15)) (js (defn foo [this] this)) (js (defn foo [a b c & ys] ys)) (js ((fn [x & ys] ys) 1 2 3 4)) (jseval '((fn [x & ys] ys) 1 2 3 4)) (js (cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] a) (ethel [x] c) Ethel (foo [] d))) (jseval '(cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] a) (ethel [x] c) Ethel (foo [] d))) (js (do (defprotocol Proto (foo [this])) (deftype Type [a] Proto (foo [this] a)) (foo (new Type 42)))) (jseval '(do (defprotocol P-roto (foo? [this])) (deftype T-ype [a] P-roto (foo? [this] a)) (foo? (new T-ype 42)))) (js (def x (fn foo [x] (let [x 42] (js* "~{x}['foobar']"))))) (js (let [a 1 b 2 a b] a)) (doseq [e '[nil true false 42 "fred" fred ethel my.ns/fred your.ns.fred (if test then "fooelse") (def x 45) (do x y y) (fn* [x y] x y x) (fn* [x y] (if true 46 (recur 1 x))) (let* [a 1 b 2 a a] a b) (do "do1") (loop* [x 1 y 2] (if true 42 (do (recur 43 44)))) (my.foo 1 2 3) (let* [a 1 b 2 c 3] (set! y.s.d b) (new fred.Ethel a b c)) (let [x (do 1 2 3)] x) ]] (->> e (analyze envx) emit) (newline)))
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. (set! *warn-on-reflection* true) (ns cljs.compiler (:refer-clojure :exclude [munge macroexpand-1]) (:require [clojure.java.io :as io] [clojure.string :as string] [cljs.tagged-literals :as tags] [cljs.analyzer :as ana]) (:import java.lang.StringBuilder)) (declare munge) (def js-reserved #{"abstract" "boolean" "break" "byte" "case" "catch" "char" "class" "const" "continue" "debugger" "default" "delete" "do" "double" "else" "enum" "export" "extends" "final" "finally" "float" "for" "function" "goto" "if" "implements" "import" "in" "instanceof" "int" "interface" "let" "long" "native" "new" "package" "private" "protected" "public" "return" "short" "static" "super" "switch" "synchronized" "this" "throw" "throws" "transient" "try" "typeof" "var" "void" "volatile" "while" "with" "yield" "methods"}) (def ^:dynamic *position* nil) (def ^:dynamic *emitted-provides* nil) (def cljs-reserved-file-names #{"deps.cljs"}) (defonce ns-first-segments (atom '#{"cljs" "clojure"})) (defn munge ([s] (munge s js-reserved)) ([s reserved] (if (map? s) ; Unshadowing (let [{:keys [name field] :as info} s depth (loop [d 0, {:keys [shadow]} info] (cond shadow (recur (inc d) shadow) (@ns-first-segments (str name)) (inc d) :else d)) name (if field (str "self__." name) name)] (if (zero? depth) (munge name reserved) (symbol (str (munge name reserved) "__$" depth)))) ; String munging (let [ss (string/replace (str s) #"\/(.)" ".$1") ; Division is special ss (apply str (map #(if (reserved %) (str % "$") %) (string/split ss #"(?<=\.)|(?=\.)"))) ms (clojure.lang.Compiler/munge ss)] (if (symbol? s) (symbol ms) ms))))) (defn- comma-sep [xs] (interpose "," xs)) (defn- escape-char [^Character c] (let [cp (.hashCode c)] (case cp ; Handle printable escapes before ASCII 34 "\\\"" 92 "\\\\" ; Handle non-printable escapes 8 "\\b" 12 "\\f" 10 "\\n" 13 "\\r" 9 "\\t" (if (< 31 cp 127) c ; Print simple ASCII characters (format "\\u%04X" cp))))) ; Any other character is Unicode (defn- escape-string [^CharSequence s] (let [sb (StringBuilder. (count s))] (doseq [c s] (.append sb (escape-char c))) (.toString sb))) (defn- wrap-in-double-quotes [x] (str \" x \")) (defmulti emit :op) (defn emits [& xs] (doseq [x xs] (cond (nil? x) nil (map? x) (emit x) (seq? x) (apply emits x) (fn? x) (x) :else (do (let [s (print-str x)] (when *position* (swap! *position* (fn [[line column]] [line (+ column (count s))]))) (print s))))) nil) (defn ^String emit-str [expr] (with-out-str (emit expr))) (defn emitln [& xs] (apply emits xs) ;; Prints column-aligned line number comments; good test of *position*. ;(when *position* ; (let [[line column] @*position*] ; (print (apply str (concat (repeat (- 120 column) \space) ["// " (inc line)]))))) (println) (when *position* (swap! *position* (fn [[line column]] [(inc line) 0]))) nil) (defmulti emit-constant class) (defmethod emit-constant nil [x] (emits "null")) (defmethod emit-constant Long [x] (emits x)) (defmethod emit-constant Integer [x] (emits x)) ; reader puts Integers in metadata (defmethod emit-constant Double [x] (emits x)) (defmethod emit-constant String [x] (emits (wrap-in-double-quotes (escape-string x)))) (defmethod emit-constant Boolean [x] (emits (if x "true" "false"))) (defmethod emit-constant Character [x] (emits (wrap-in-double-quotes (escape-char x)))) (defmethod emit-constant java.util.regex.Pattern [x] (let [[_ flags pattern] (re-find #"^(?:\(\?([idmsux]*)\))?(.*)" (str x))] (emits \/ (.replaceAll (re-matcher #"/" pattern) "\\\\/") \/ flags))) (defmethod emit-constant clojure.lang.Keyword [x] (emits \" "\\uFDD0" \' (if (namespace x) (str (namespace x) "/") "") (name x) \")) (defmethod emit-constant clojure.lang.Symbol [x] (emits \" "\\uFDD1" \' (if (namespace x) (str (namespace x) "/") "") (name x) \")) (defn- emit-meta-constant [x & body] (if (meta x) (do (emits "cljs.core.with_meta(" body ",") (emit-constant (meta x)) (emits ")")) (emits body))) (defmethod emit-constant clojure.lang.PersistentList$EmptyList [x] (emit-meta-constant x "cljs.core.List.EMPTY")) (defmethod emit-constant clojure.lang.PersistentList [x] (emit-meta-constant x (concat ["cljs.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.Cons [x] (emit-meta-constant x (concat ["cljs.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.IPersistentVector [x] (emit-meta-constant x (concat ["cljs.core.vec(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defmethod emit-constant clojure.lang.IPersistentMap [x] (emit-meta-constant x (concat ["cljs.core.hash_map("] (comma-sep (map #(fn [] (emit-constant %)) (apply concat x))) [")"]))) (defmethod emit-constant clojure.lang.PersistentHashSet [x] (emit-meta-constant x (concat ["cljs.core.set(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defn emit-block [context statements ret] (when statements (emits statements)) (emit ret)) (defmacro emit-wrap [env & body] `(let [env# ~env] (when (= :return (:context env#)) (emits "return ")) ~@body (when-not (= :expr (:context env#)) (emitln ";")))) (defmethod emit :no-op [m]) (defmethod emit :var [{:keys [info env] :as arg}] (let [n (:name info) n (if (= (namespace n) "js") (name n) info)] (emit-wrap env (emits (munge n))))) (defmethod emit :meta [{:keys [expr meta env]}] (emit-wrap env (emits "cljs.core.with_meta(" expr "," meta ")"))) (def ^:private array-map-threshold 16) (def ^:private obj-map-threshold 32) (defmethod emit :map [{:keys [env simple-keys? keys vals]}] (emit-wrap env (cond (zero? (count keys)) (emits "cljs.core.ObjMap.EMPTY") (and simple-keys? (<= (count keys) obj-map-threshold)) (emits "cljs.core.ObjMap.fromObject([" (comma-sep keys) ; keys "],{" (comma-sep (map (fn [k v] (with-out-str (emit k) (print ":") (emit v))) keys vals)) ; js obj "})") (<= (count keys) array-map-threshold) (emits "cljs.core.PersistentArrayMap.fromArrays([" (comma-sep keys) "],[" (comma-sep vals) "])") :else (emits "cljs.core.PersistentHashMap.fromArrays([" (comma-sep keys) "],[" (comma-sep vals) "])")))) (defmethod emit :vector [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "cljs.core.PersistentVector.EMPTY") (emits "cljs.core.PersistentVector.fromArray([" (comma-sep items) "], true)")))) (defmethod emit :set [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "cljs.core.PersistentHashSet.EMPTY") (emits "cljs.core.PersistentHashSet.fromArray([" (comma-sep items) "])")))) (defmethod emit :constant [{:keys [form env]}] (when-not (= :statement (:context env)) (emit-wrap env (emit-constant form)))) (defn get-tag [e] (or (-> e :tag) (-> e :info :tag))) (defn infer-tag [e] (if-let [tag (get-tag e)] tag (case (:op e) :let (infer-tag (:ret e)) :if (let [then-tag (infer-tag (:then e)) else-tag (infer-tag (:else e))] (when (= then-tag else-tag) then-tag)) :constant (case (:form e) true 'boolean false 'boolean nil) nil))) (defn safe-test? [e] (let [tag (infer-tag e)] (or (#{'boolean 'seq} tag) (when (= (:op e) :constant) (let [form (:form e)] (not (or (and (string? form) (= form "")) (and (number? form) (zero? form))))))))) (defmethod emit :if [{:keys [test then else env unchecked]}] (let [context (:context env) checked (not (or unchecked (safe-test? test)))] (if (= :expr context) (emits "(" (when checked "cljs.core.truth_") "(" test ")?" then ":" else ")") (do (if checked (emitln "if(cljs.core.truth_(" test "))") (emitln "if(" test ")")) (emitln "{" then "} else") (emitln "{" else "}"))))) (defmethod emit :throw [{:keys [throw env]}] (if (= :expr (:context env)) (emits "(function(){throw " throw "})()") (emitln "throw " throw ";"))) (defn emit-comment "Emit a nicely formatted comment string." [doc jsdoc] (let [docs (when doc [doc]) docs (if jsdoc (concat docs jsdoc) docs) docs (remove nil? docs)] (letfn [(print-comment-lines [e] (doseq [next-line (string/split-lines e)] (emitln "* " (string/trim next-line))))] (when (seq docs) (emitln "/**") (doseq [e docs] (when e (print-comment-lines e))) (emitln "*/"))))) (defmethod emit :def [{:keys [name init env doc export]}] (when init (let [mname (munge name)] (emit-comment doc (:jsdoc init)) (emits mname) (emits " = " init) (when-not (= :expr (:context env)) (emitln ";")) (when export (emitln "goog.exportSymbol('" (munge export) "', " mname ");"))))) (defn emit-apply-to [{:keys [name params env]}] (let [arglist (gensym "arglist__") delegate-name (str (munge name) "__delegate") params (map munge params)] (emitln "(function (" arglist "){") (doseq [[i param] (map-indexed vector (butlast params))] (emits "var " param " = cljs.core.first(") (dotimes [_ i] (emits "cljs.core.next(")) (emits arglist ")") (dotimes [_ i] (emits ")")) (emitln ";")) (if (< 1 (count params)) (do (emits "var " (last params) " = cljs.core.rest(") (dotimes [_ (- (count params) 2)] (emits "cljs.core.next(")) (emits arglist) (dotimes [_ (- (count params) 2)] (emits ")")) (emitln ");") (emitln "return " delegate-name "(" (string/join ", " params) ");")) (do (emits "var " (last params) " = ") (emits "cljs.core.seq(" arglist ");") (emitln ";") (emitln "return " delegate-name "(" (string/join ", " params) ");"))) (emits "})"))) (defn emit-fn-method [{:keys [type name variadic params statements ret env recurs max-fixed-arity]}] (emit-wrap env (emitln "(function " (munge name) "(" (comma-sep (map munge params)) "){") (when type (emitln "var self__ = this;")) (when recurs (emitln "while(true){")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emits "})"))) (defn emit-variadic-fn-method [{:keys [type name variadic params statements ret env recurs max-fixed-arity] :as f}] (emit-wrap env (let [name (or name (gensym)) mname (munge name) params (map munge params) delegate-name (str mname "__delegate")] (emitln "(function() { ") (emitln "var " delegate-name " = function (" (comma-sep params) "){") (when recurs (emitln "while(true){")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emitln "};") (emitln "var " mname " = function (" (comma-sep (if variadic (concat (butlast params) ['var_args]) params)) "){") (when type (emitln "var self__ = this;")) (when variadic (emitln "var " (last params) " = null;") (emitln "if (goog.isDef(var_args)) {") (emitln " " (last params) " = cljs.core.array_seq(Array.prototype.slice.call(arguments, " (dec (count params)) "),0);") (emitln "} ")) (emitln "return " delegate-name ".call(" (string/join ", " (cons "this" params)) ");") (emitln "};") (emitln mname ".cljs$lang$maxFixedArity = " max-fixed-arity ";") (emits mname ".cljs$lang$applyTo = ") (emit-apply-to (assoc f :name name)) (emitln ";") (emitln mname ".cljs$lang$arity$variadic = " delegate-name ";") (emitln "return " mname ";") (emitln "})()")))) (defmethod emit :fn [{:keys [name env methods max-fixed-arity variadic recur-frames loop-lets]}] ;;fn statements get erased, serve no purpose and can pollute scope if named (when-not (= :statement (:context env)) (let [loop-locals (->> (concat (mapcat :params (filter #(and % @(:flag %)) recur-frames)) (mapcat :params loop-lets)) (map munge) seq)] (when loop-locals (when (= :return (:context env)) (emits "return ")) (emitln "((function (" (comma-sep (map munge loop-locals)) "){") (when-not (= :return (:context env)) (emits "return "))) (if (= 1 (count methods)) (if variadic (emit-variadic-fn-method (assoc (first methods) :name name)) (emit-fn-method (assoc (first methods) :name name))) (let [has-name? (and name true) name (or name (gensym)) mname (munge name) maxparams (map munge (apply max-key count (map :params methods))) mmap (into {} (map (fn [method] [(munge (symbol (str mname "__" (count (:params method))))) method]) methods)) ms (sort-by #(-> % second :params count) (seq mmap))] (when (= :return (:context env)) (emits "return ")) (emitln "(function() {") (emitln "var " mname " = null;") (doseq [[n meth] ms] (emits "var " n " = ") (if (:variadic meth) (emit-variadic-fn-method meth) (emit-fn-method meth)) (emitln ";")) (emitln mname " = function(" (comma-sep (if variadic (concat (butlast maxparams) ['var_args]) maxparams)) "){") (when variadic (emitln "var " (last maxparams) " = var_args;")) (emitln "switch(arguments.length){") (doseq [[n meth] ms] (if (:variadic meth) (do (emitln "default:") (emitln "return " n ".cljs$lang$arity$variadic(" (comma-sep (butlast maxparams)) (when (> (count maxparams) 1) ", ") "cljs.core.array_seq(arguments, " max-fixed-arity "));")) (let [pcnt (count (:params meth))] (emitln "case " pcnt ":") (emitln "return " n ".call(this" (if (zero? pcnt) nil (list "," (comma-sep (take pcnt maxparams)))) ");")))) (emitln "}") (emitln "throw(new Error('Invalid arity: ' + arguments.length));") (emitln "};") (when variadic (emitln mname ".cljs$lang$maxFixedArity = " max-fixed-arity ";") (emitln mname ".cljs$lang$applyTo = " (some #(let [[n m] %] (when (:variadic m) n)) ms) ".cljs$lang$applyTo;")) (when has-name? (doseq [[n meth] ms] (let [c (count (:params meth))] (if (:variadic meth) (emitln mname ".cljs$lang$arity$variadic = " n ".cljs$lang$arity$variadic;") (emitln mname ".cljs$lang$arity$" c " = " n ";"))))) (emitln "return " mname ";") (emitln "})()"))) (when loop-locals (emitln ";})(" (comma-sep loop-locals) "))"))))) (defmethod emit :do [{:keys [statements ret env]}] (let [context (:context env)] (when (and statements (= :expr context)) (emits "(function (){")) ;(when statements (emitln "{")) (emit-block context statements ret) ;(when statements (emits "}")) (when (and statements (= :expr context)) (emits "})()")))) (defmethod emit :try* [{:keys [env try catch name finally]}] (let [context (:context env) subcontext (if (= :expr context) :return context)] (if (or name finally) (do (when (= :expr context) (emits "(function (){")) (emits "try{") (let [{:keys [statements ret]} try] (emit-block subcontext statements ret)) (emits "}") (when name (emits "catch (" (munge name) "){") (when catch (let [{:keys [statements ret]} catch] (emit-block subcontext statements ret))) (emits "}")) (when finally (let [{:keys [statements ret]} finally] (assert (not= :constant (:op ret)) "finally block cannot contain constant") (emits "finally {") (emit-block subcontext statements ret) (emits "}"))) (when (= :expr context) (emits "})()"))) (let [{:keys [statements ret]} try] (when (and statements (= :expr context)) (emits "(function (){")) (emit-block subcontext statements ret) (when (and statements (= :expr context)) (emits "})()")))))) (defmethod emit :let [{:keys [bindings statements ret env loop]}] (let [context (:context env)] (when (= :expr context) (emits "(function (){")) (doseq [{:keys [init] :as binding} bindings] (emitln "var " (munge binding) " = " init ";")) (when loop (emitln "while(true){")) (emit-block (if (= :expr context) :return context) statements ret) (when loop (emitln "break;") (emitln "}")) ;(emits "}") (when (= :expr context) (emits "})()")))) (defmethod emit :recur [{:keys [frame exprs env]}] (let [temps (vec (take (count exprs) (repeatedly gensym))) params (:params frame)] (emitln "{") (dotimes [i (count exprs)] (emitln "var " (temps i) " = " (exprs i) ";")) (dotimes [i (count exprs)] (emitln (munge (params i)) " = " (temps i) ";")) (emitln "continue;") (emitln "}"))) (defmethod emit :letfn [{:keys [bindings statements ret env]}] (let [context (:context env)] (when (= :expr context) (emits "(function (){")) (doseq [{:keys [init] :as binding} bindings] (emitln "var " (munge binding) " = " init ";")) (emit-block (if (= :expr context) :return context) statements ret) (when (= :expr context) (emits "})()")))) (defn protocol-prefix [psym] (symbol (str (-> (str psym) (.replace \. \$) (.replace \/ \$)) "$"))) (defmethod emit :invoke [{:keys [f args env] :as expr}] (let [info (:info f) fn? (and ana/*cljs-static-fns* (not (:dynamic info)) (:fn-var info)) protocol (:protocol info) proto? (let [tag (infer-tag (first (:args expr)))] (and protocol tag (or ana/*cljs-static-fns* (:protocol-inline env)) (or (= protocol tag) (when-let [ps (:protocols (ana/resolve-existing-var (dissoc env :locals) tag))] (ps protocol))))) opt-not? (and (= (:name info) 'cljs.core/not) (= (infer-tag (first (:args expr))) 'boolean)) ns (:ns info) js? (= ns 'js) goog? (when ns (or (= ns 'goog) (when-let [ns-str (str ns)] (= (get (string/split ns-str #"\.") 0 nil) "goog")))) keyword? (and (= (-> f :op) :constant) (keyword? (-> f :form))) [f variadic-invoke] (if fn? (let [arity (count args) variadic? (:variadic info) mps (:method-params info) mfa (:max-fixed-arity info)] (cond ;; if only one method, no renaming needed (and (not variadic?) (= (count mps) 1)) [f nil] ;; direct dispatch to variadic case (and variadic? (> arity mfa)) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljs$lang$arity$variadic")))) {:max-fixed-arity mfa}] ;; direct dispatch to specific arity case :else (let [arities (map count mps)] (if (some #{arity} arities) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljs$lang$arity$" arity)))) nil] [f nil])))) [f nil])] (emit-wrap env (cond opt-not? (emits "!(" (first args) ")") proto? (let [pimpl (str (munge (protocol-prefix protocol)) (munge (name (:name info))) "$arity$" (count args))] (emits (first args) "." pimpl "(" (comma-sep args) ")")) keyword? (emits "(new cljs.core.Keyword(" f ")).call(" (comma-sep (cons "null" args)) ")") variadic-invoke (let [mfa (:max-fixed-arity variadic-invoke)] (emits f "(" (comma-sep (take mfa args)) (when-not (zero? mfa) ",") "cljs.core.array_seq([" (comma-sep (drop mfa args)) "], 0))")) (or fn? js? goog?) (emits f "(" (comma-sep args) ")") :else (if (and ana/*cljs-static-fns* (= (:op f) :var)) (let [fprop (str ".cljs$lang$arity$" (count args))] (emits "(" f fprop " ? " f fprop "(" (comma-sep args) ") : " f ".call(" (comma-sep (cons "null" args)) "))")) (emits f ".call(" (comma-sep (cons "null" args)) ")")))))) (defmethod emit :new [{:keys [ctor args env]}] (emit-wrap env (emits "(new " ctor "(" (comma-sep args) "))"))) (defmethod emit :set! [{:keys [target val env]}] (emit-wrap env (emits target " = " val))) (defmethod emit :ns [{:keys [name requires uses requires-macros env]}] (swap! ns-first-segments conj (first (string/split (str name) #"\."))) (emitln "goog.provide('" (munge name) "');") (when-not (= name 'cljs.core) (emitln "goog.require('cljs.core');")) (doseq [lib (into (vals requires) (distinct (vals uses)))] (emitln "goog.require('" (munge lib) "');"))) (defmethod emit :deftype* [{:keys [t fields pmasks]}] (let [fields (map munge fields)] (when-not (or (nil? *emitted-provides*) (contains? @*emitted-provides* t)) (swap! *emitted-provides* conj t) (emitln "") (emitln "goog.provide('" (munge t) "');")) (emitln "") (emitln "/**") (emitln "* @constructor") (emitln "*/") (emitln (munge t) " = (function (" (comma-sep fields) "){") (doseq [fld fields] (emitln "this." fld " = " fld ";")) (doseq [[pno pmask] pmasks] (emitln "this.cljs$lang$protocol_mask$partition" pno "$ = " pmask ";")) (emitln "})"))) (defmethod emit :defrecord* [{:keys [t fields pmasks]}] (let [fields (concat (map munge fields) '[__meta __extmap])] (when-not (or (nil? *emitted-provides*) (contains? @*emitted-provides* t)) (swap! *emitted-provides* conj t) (emitln "") (emitln "goog.provide('" (munge t) "');")) (emitln "") (emitln "/**") (emitln "* @constructor") (doseq [fld fields] (emitln "* @param {*} " fld)) (emitln "* @param {*=} __meta ") (emitln "* @param {*=} __extmap") (emitln "*/") (emitln (munge t) " = (function (" (comma-sep fields) "){") (doseq [fld fields] (emitln "this." fld " = " fld ";")) (doseq [[pno pmask] pmasks] (emitln "this.cljs$lang$protocol_mask$partition" pno "$ = " pmask ";")) (emitln "if(arguments.length>" (- (count fields) 2) "){") (emitln "this.__meta = __meta;") (emitln "this.__extmap = __extmap;") (emitln "} else {") (emits "this.__meta=") (emit-constant nil) (emitln ";") (emits "this.__extmap=") (emit-constant nil) (emitln ";") (emitln "}") (emitln "})"))) (defmethod emit :dot [{:keys [target field method args env]}] (emit-wrap env (if field (emits target "." (munge field #{})) (emits target "." (munge method #{}) "(" (comma-sep args) ")")))) (defmethod emit :js [{:keys [env code segs args]}] (emit-wrap env (if code (emits code) (emits (interleave (concat segs (repeat nil)) (concat args [nil])))))) (defn forms-seq "Seq of forms in a Clojure or ClojureScript file." ([f] (forms-seq f (clojure.lang.LineNumberingPushbackReader. (io/reader f)))) ([f ^java.io.PushbackReader rdr] (if-let [form (binding [*ns* ana/*reader-ns*] (read rdr nil nil))] (lazy-seq (cons form (forms-seq f rdr))) (.close rdr)))) (defn rename-to-js "Change the file extension from .cljs to .js. Takes a File or a String. Always returns a String." [file-str] (clojure.string/replace file-str #"\.cljs$" ".js")) (defn mkdirs "Create all parent directories for the passed file." [^java.io.File f] (.mkdirs (.getParentFile (.getCanonicalFile f)))) (defmacro with-core-cljs "Ensure that core.cljs has been loaded." [& body] `(do (when-not (:defs (get @ana/namespaces 'cljs.core)) (ana/analyze-file "cljs/core.cljs")) ~@body)) (defn compile-file* [src dest] (with-core-cljs (with-open [out ^java.io.Writer (io/make-writer dest {})] (binding [*out* out ana/*cljs-ns* 'cljs.user ana/*cljs-file* (.getPath ^java.io.File src) *data-readers* tags/*cljs-data-readers* *position* (atom [0 0]) *emitted-provides* (atom #{})] (loop [forms (forms-seq src) ns-name nil deps nil] (if (seq forms) (let [env (ana/empty-env) ast (ana/analyze env (first forms))] (do (emit ast) (if (= (:op ast) :ns) (recur (rest forms) (:name ast) (merge (:uses ast) (:requires ast))) (recur (rest forms) ns-name deps)))) {:ns (or ns-name 'cljs.user) :provides [ns-name] :requires (if (= ns-name 'cljs.core) (set (vals deps)) (conj (set (vals deps)) 'cljs.core)) :file dest})))))) (defn requires-compilation? "Return true if the src file requires compilation." [^java.io.File src ^java.io.File dest] (or (not (.exists dest)) (> (.lastModified src) (.lastModified dest)))) (defn compile-file "Compiles src to a file of the same name, but with a .js extension, in the src file's directory. With dest argument, write file to provided location. If the dest argument is a file outside the source tree, missing parent directories will be created. The src file will only be compiled if the dest file has an older modification time. Both src and dest may be either a String or a File. Returns a map containing {:ns .. :provides .. :requires .. :file ..}. If the file was not compiled returns only {:file ...}" ([src] (let [dest (rename-to-js src)] (compile-file src dest))) ([src dest] (let [src-file (io/file src) dest-file (io/file dest)] (if (.exists src-file) (if (requires-compilation? src-file dest-file) (do (mkdirs dest-file) (compile-file* src-file dest-file)) {:file dest-file}) (throw (java.io.FileNotFoundException. (str "The file " src " does not exist."))))))) (comment ;; flex compile-file (do (compile-file "/tmp/hello.cljs" "/tmp/something.js") (slurp "/tmp/hello.js") (compile-file "/tmp/somescript.cljs") (slurp "/tmp/somescript.js"))) (defn path-seq [file-str] (->> java.io.File/separator java.util.regex.Pattern/quote re-pattern (string/split file-str))) (defn to-path ([parts] (to-path parts java.io.File/separator)) ([parts sep] (apply str (interpose sep parts)))) (defn to-target-file "Given the source root directory, the output target directory and file under the source root, produce the target file." [^java.io.File dir ^String target ^java.io.File file] (let [dir-path (path-seq (.getAbsolutePath dir)) file-path (path-seq (.getAbsolutePath file)) relative-path (drop (count dir-path) file-path) parents (butlast relative-path) parent-file (java.io.File. ^String (to-path (cons target parents)))] (java.io.File. parent-file ^String (rename-to-js (last relative-path))))) (defn cljs-files-in "Return a sequence of all .cljs files in the given directory." [dir] (filter #(let [name (.getName ^java.io.File %)] (and (.endsWith name ".cljs") (not= \. (first name)) (not (contains? cljs-reserved-file-names name)))) (file-seq dir))) (defn compile-root "Looks recursively in src-dir for .cljs files and compiles them to .js files. If target-dir is provided, output will go into this directory mirroring the source directory structure. Returns a list of maps containing information about each file which was compiled in dependency order." ([src-dir] (compile-root src-dir "out")) ([src-dir target-dir] (let [src-dir-file (io/file src-dir)] (loop [cljs-files (cljs-files-in src-dir-file) output-files []] (if (seq cljs-files) (let [cljs-file (first cljs-files) output-file ^java.io.File (to-target-file src-dir-file target-dir cljs-file) ns-info (compile-file cljs-file output-file)] (recur (rest cljs-files) (conj output-files (assoc ns-info :file-name (.getPath output-file))))) output-files))))) (comment ;; compile-root ;; If you have a standard project layout with all file in src (compile-root "src") ;; will produce a mirrored directory structure under "out" but all ;; files will be compiled to js. ) (comment ;;the new way - use the REPL!! (require '[cljs.compiler :as comp]) (def repl-env (comp/repl-env)) (comp/repl repl-env) ;having problems?, try verbose mode (comp/repl repl-env :verbose true) ;don't forget to check for uses of undeclared vars (comp/repl repl-env :warn-on-undeclared true) (test-stuff) (+ 1 2 3) ([ 1 2 3 4] 2) ({:a 1 :b 2} :a) ({1 1 2 2} 1) (#{1 2 3} 2) (:b {:a 1 :b 2}) ('b '{:a 1 b 2}) (extend-type number ISeq (-seq [x] x)) (seq 42) ;(aset cljs.core.ISeq "number" true) ;(aget cljs.core.ISeq "number") (satisfies? ISeq 42) (extend-type nil ISeq (-seq [x] x)) (satisfies? ISeq nil) (seq nil) (extend-type default ISeq (-seq [x] x)) (satisfies? ISeq true) (seq true) (test-stuff) (array-seq []) (defn f [& etc] etc) (f) (in-ns 'cljs.core) ;;hack on core (deftype Foo [a] IMeta (-meta [_] (fn [] a))) ((-meta (Foo. 42))) ;;OLD way, don't you want to use the REPL? (in-ns 'cljs.compiler) (import '[javax.script ScriptEngineManager]) (def jse (-> (ScriptEngineManager.) (.getEngineByName "JavaScript"))) (.eval jse cljs.compiler/bootjs) (def envx {:ns (@namespaces 'cljs.user) :context :expr :locals '{ethel {:name ethel__123 :init nil}}}) (analyze envx nil) (analyze envx 42) (analyze envx "foo") (analyze envx 'fred) (analyze envx 'fred.x) (analyze envx 'ethel) (analyze envx 'ethel.x) (analyze envx 'my.ns/fred) (analyze envx 'your.ns.fred) (analyze envx '(if test then else)) (analyze envx '(if test then)) (analyze envx '(and fred ethel)) (analyze (assoc envx :context :statement) '(def test "fortytwo" 42)) (analyze (assoc envx :context :expr) '(fn* ^{::fields [a b c]} [x y] a y x)) (analyze (assoc envx :context :statement) '(let* [a 1 b 2] a)) (analyze (assoc envx :context :statement) '(defprotocol P (bar [a]) (baz [b c]))) (analyze (assoc envx :context :statement) '(. x y)) (analyze envx '(fn foo [x] (let [x 42] (js* "~{x}['foobar']")))) (analyze envx '(ns fred (:require [your.ns :as yn]) (:require-macros [clojure.core :as core]))) (defmacro js [form] `(emit (ana/analyze {:ns (@ana/namespaces 'cljs.user) :context :statement :locals {}} '~form))) (defn jscapture [form] "just grabs the js, doesn't print it" (with-out-str (emit (analyze {:ns (@namespaces 'cljs.user) :context :expr :locals {}} form)))) (defn jseval [form] (let [js (jscapture form)] ;;(prn js) (.eval jse (str "print(" js ")")))) ;; from closure.clj (optimize (jscapture '(defn foo [x y] (if true 46 (recur 1 x))))) (js (if a b c)) (js (def x 42)) (js (defn foo [a b] a)) (js (do 1 2 3)) (js (let [a 1 b 2 a b] a)) (js (ns fred (:require [your.ns :as yn]) (:require-macros [cljs.core :as core]))) (js (def foo? (fn* ^{::fields [a? b c]} [x y] (if true a? (recur 1 x))))) (js (def foo (fn* ^{::fields [a b c]} [x y] (if true a (recur 1 x))))) (js (defn foo [x y] (if true x y))) (jseval '(defn foo [x y] (if true x y))) (js (defn foo [x y] (if true 46 (recur 1 x)))) (jseval '(defn foo [x y] (if true 46 (recur 1 x)))) (jseval '(foo 1 2)) (js (and fred ethel)) (jseval '(ns fred (:require [your.ns :as yn]) (:require-macros [cljs.core :as core]))) (js (def x 42)) (jseval '(def x 42)) (jseval 'x) (jseval '(if 42 1 2)) (jseval '(or 1 2)) (jseval '(fn* [x y] (if true 46 (recur 1 x)))) (.eval jse "print(test)") (.eval jse "print(cljs.user.Foo)") (.eval jse "print(cljs.user.Foo = function (){\n}\n)") (js (def fred 42)) (js (deftype* Foo [a b-foo c])) (jseval '(deftype* Foo [a b-foo c])) (jseval '(. (new Foo 1 2 3) b-foo)) (js (. (new Foo 1 2 3) b)) (.eval jse "print(new cljs.user.Foo(1, 42, 3).b)") (.eval jse "(function (x, ys){return Array.prototype.slice.call(arguments, 1);})(1,2)[0]") (macroexpand-1 '(cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] b) (ethel [x] c) Ethel (foo [] d))) (-> (macroexpand-1 '(cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] b) (ethel [x] c) Ethel (foo [] d))) last last last first meta) (macroexpand-1 '(cljs.core/extend-type Foo Fred (fred ([x] a) ([x y] b)) (ethel ([x] c)) Ethel (foo ([] d)))) (js (new foo.Bar 65)) (js (defprotocol P (bar [a]) (baz [b c]))) (js (. x y)) (js (. "fred" (y))) (js (. x y 42 43)) (js (.. a b c d)) (js (. x (y 42 43))) (js (fn [x] x)) (js (fn ([t] t) ([x y] y) ([ a b & zs] b))) (js (. (fn foo ([t] t) ([x y] y) ([a b & zs] b)) call nil 1 2)) (js (fn foo ([t] t) ([x y] y) ([ a b & zs] b))) (js ((fn foo ([t] (foo t nil)) ([x y] y) ([ a b & zs] b)) 1 2 3)) (jseval '((fn foo ([t] t) ([x y] y) ([ a b & zs] zs)) 12 13 14 15)) (js (defn foo [this] this)) (js (defn foo [a b c & ys] ys)) (js ((fn [x & ys] ys) 1 2 3 4)) (jseval '((fn [x & ys] ys) 1 2 3 4)) (js (cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] a) (ethel [x] c) Ethel (foo [] d))) (jseval '(cljs.core/deftype Foo [a b c] Fred (fred [x] a) (fred [x y] a) (ethel [x] c) Ethel (foo [] d))) (js (do (defprotocol Proto (foo [this])) (deftype Type [a] Proto (foo [this] a)) (foo (new Type 42)))) (jseval '(do (defprotocol P-roto (foo? [this])) (deftype T-ype [a] P-roto (foo? [this] a)) (foo? (new T-ype 42)))) (js (def x (fn foo [x] (let [x 42] (js* "~{x}['foobar']"))))) (js (let [a 1 b 2 a b] a)) (doseq [e '[nil true false 42 "fred" fred ethel my.ns/fred your.ns.fred (if test then "fooelse") (def x 45) (do x y y) (fn* [x y] x y x) (fn* [x y] (if true 46 (recur 1 x))) (let* [a 1 b 2 a a] a b) (do "do1") (loop* [x 1 y 2] (if true 42 (do (recur 43 44)))) (my.foo 1 2 3) (let* [a 1 b 2 c 3] (set! y.s.d b) (new fred.Ethel a b c)) (let [x (do 1 2 3)] x) ]] (->> e (analyze envx) emit) (newline)))
[ { "context": "])\n\n;; Multi-field comparators\n(def john1 {:name \"John\", :salary 35000.00, :company \"Acme\"})\n(def mary ", "end": 574, "score": 0.999723494052887, "start": 570, "tag": "NAME", "value": "John" }, { "context": "e \"John\", :salary 35000.00, :company \"Acme\"})\n(def mary {:name \"Mary\", :salary 35000.00, :company \"Mars ", "end": 622, "score": 0.7064993381500244, "start": 618, "tag": "NAME", "value": "mary" }, { "context": "ry 35000.00, :company \"Acme\"})\n(def mary {:name \"Mary\", :salary 35000.00, :company \"Mars Inc\"})\n(def jo", "end": 636, "score": 0.9996477365493774, "start": 632, "tag": "NAME", "value": "Mary" }, { "context": "5000.00, :company \"Mars Inc\"})\n(def john2 {:name \"John\", :salary 40000.00, :company \"Venus Co\"})\n(def jo", "end": 702, "score": 0.9997625946998596, "start": 698, "tag": "NAME", "value": "John" }, { "context": "0000.00, :company \"Venus Co\"})\n(def john3 {:name \"John\", :salary 30000.00, :company \"Asteroids-R-Us\"})\n(", "end": 768, "score": 0.9997506737709045, "start": 764, "tag": "NAME", "value": "John" }, { "context": "0000.00, :company \"Asteroids-R-Us\"})\n(def people [john1 mary john2 john3])\n\n(defn by-salary-name-company\n", "end": 835, "score": 0.8216462731361389, "start": 830, "tag": "USERNAME", "value": "john1" }, { "context": "00, :company \"Asteroids-R-Us\"})\n(def people [john1 mary john2 john3])\n\n(defn by-salary-name-company\n [x ", "end": 840, "score": 0.9025874733924866, "start": 836, "tag": "NAME", "value": "mary" }, { "context": "mpany \"Asteroids-R-Us\"})\n(def people [john1 mary john2 john3])\n\n(defn by-salary-name-company\n [x y]\n (", "end": 846, "score": 0.7347087860107422, "start": 842, "tag": "NAME", "value": "ohn2" }, { "context": "\"Asteroids-R-Us\"})\n(def people [john1 mary john2 john3])\n\n(defn by-salary-name-company\n [x y]\n (let [", "end": 851, "score": 0.6249674558639526, "start": 848, "tag": "NAME", "value": "ohn" } ]
language-learning/clojure/functions/comparators.clj
imteekay/programming-language-research
627
;; Resource: https://clojure.org/guides/comparators ;; compare works for many types of values, ordering them in one particular way: ;; - increasing numeric order for numbers; ;; - lexicographic order (aka dictionary order) for strings, symbols, and keywords; ;; - shortest-to-longest order by Clojure vectors, with lexicographic ordering among equal length vectors ;; reverse order (defn reverse-cmp [a b] (compare b a)) (sort reverse-cmp [1 2 3 4]) ;; using Clojure’s #() notation (sort #(compare %2 %1) [1 2 3 4]) ;; Multi-field comparators (def john1 {:name "John", :salary 35000.00, :company "Acme"}) (def mary {:name "Mary", :salary 35000.00, :company "Mars Inc"}) (def john2 {:name "John", :salary 40000.00, :company "Venus Co"}) (def john3 {:name "John", :salary 30000.00, :company "Asteroids-R-Us"}) (def people [john1 mary john2 john3]) (defn by-salary-name-company [x y] (let [c (compare (:salary y) (:salary x))] (if (not= c 0) c (let [c (compare (:name x) (:name y))] (if (not= c 0) c (compare (:company x) (:company y))))))) (sort by-salary-name-company people) ;; short verstion of by-salary-name-company (defn by-salary-name-company [x y] (compare [(:salary y) (:name x) (:company x)] [(:salary x) (:name y) (:company y)])) (sort by-salary-name-company people)
121650
;; Resource: https://clojure.org/guides/comparators ;; compare works for many types of values, ordering them in one particular way: ;; - increasing numeric order for numbers; ;; - lexicographic order (aka dictionary order) for strings, symbols, and keywords; ;; - shortest-to-longest order by Clojure vectors, with lexicographic ordering among equal length vectors ;; reverse order (defn reverse-cmp [a b] (compare b a)) (sort reverse-cmp [1 2 3 4]) ;; using Clojure’s #() notation (sort #(compare %2 %1) [1 2 3 4]) ;; Multi-field comparators (def john1 {:name "<NAME>", :salary 35000.00, :company "Acme"}) (def <NAME> {:name "<NAME>", :salary 35000.00, :company "Mars Inc"}) (def john2 {:name "<NAME>", :salary 40000.00, :company "Venus Co"}) (def john3 {:name "<NAME>", :salary 30000.00, :company "Asteroids-R-Us"}) (def people [john1 <NAME> j<NAME> j<NAME>3]) (defn by-salary-name-company [x y] (let [c (compare (:salary y) (:salary x))] (if (not= c 0) c (let [c (compare (:name x) (:name y))] (if (not= c 0) c (compare (:company x) (:company y))))))) (sort by-salary-name-company people) ;; short verstion of by-salary-name-company (defn by-salary-name-company [x y] (compare [(:salary y) (:name x) (:company x)] [(:salary x) (:name y) (:company y)])) (sort by-salary-name-company people)
true
;; Resource: https://clojure.org/guides/comparators ;; compare works for many types of values, ordering them in one particular way: ;; - increasing numeric order for numbers; ;; - lexicographic order (aka dictionary order) for strings, symbols, and keywords; ;; - shortest-to-longest order by Clojure vectors, with lexicographic ordering among equal length vectors ;; reverse order (defn reverse-cmp [a b] (compare b a)) (sort reverse-cmp [1 2 3 4]) ;; using Clojure’s #() notation (sort #(compare %2 %1) [1 2 3 4]) ;; Multi-field comparators (def john1 {:name "PI:NAME:<NAME>END_PI", :salary 35000.00, :company "Acme"}) (def PI:NAME:<NAME>END_PI {:name "PI:NAME:<NAME>END_PI", :salary 35000.00, :company "Mars Inc"}) (def john2 {:name "PI:NAME:<NAME>END_PI", :salary 40000.00, :company "Venus Co"}) (def john3 {:name "PI:NAME:<NAME>END_PI", :salary 30000.00, :company "Asteroids-R-Us"}) (def people [john1 PI:NAME:<NAME>END_PI jPI:NAME:<NAME>END_PI jPI:NAME:<NAME>END_PI3]) (defn by-salary-name-company [x y] (let [c (compare (:salary y) (:salary x))] (if (not= c 0) c (let [c (compare (:name x) (:name y))] (if (not= c 0) c (compare (:company x) (:company y))))))) (sort by-salary-name-company people) ;; short verstion of by-salary-name-company (defn by-salary-name-company [x y] (compare [(:salary y) (:name x) (:company x)] [(:salary x) (:name y) (:company y)])) (sort by-salary-name-company people)
[ { "context": " [:p {:class \"home-text\"} \n \"Hi I'm Maria, thanks for visiting my website where you can fin", "end": 1089, "score": 0.9982912540435791, "start": 1084, "tag": "NAME", "value": "Maria" }, { "context": " [:p {:class \"home-text\"} \n \"Hola soy María, gracias por visitar esta página donde puedes ver", "end": 1373, "score": 0.9982947111129761, "start": 1368, "tag": "NAME", "value": "María" } ]
src/cljs/galacart_gallery/views.cljs
lucasgut/galacart-gallery
0
(ns galacart-gallery.views (:require [re-frame.core :as re-frame] [galacart-gallery.subs :as subs] [galacart-gallery.events :as events] )) ;; Product image modal, hidden by default (defn product-image-modal [] (let [product-image-modal (re-frame/subscribe [::subs/product-image-modal])] [:div {:class "product-image-modal" :style {:display (if (:visible @product-image-modal) "block" "none")}} [:div [:span {:dangerouslySetInnerHTML {:__html "&times;"} :on-click #(re-frame/dispatch [::events/toggle-product-image-modal {:visible false}])}] ;; cross symbol to close window [:img {:src (:image-path @product-image-modal)}] ]])) ;; Home (defn home-panel [] (let [home-image (re-frame/subscribe [::subs/home-image])] [:div {:class "home-container"} [:div {:style {:float "left"}} [:img {:class "home-image" :src @home-image}] ] [:div {:style {:float "right" :max-width "40vw"}} [:h1 "Welcome! Bienvenidos!"] [:p {:class "home-text"} "Hi I'm Maria, thanks for visiting my website where you can find some of my works - paintings and sculptures."[:br][:br] "My studio is located in Santa Ponsa, Mallorca (Spain), and I can be reached via e-mail."] [:hr] [:p {:class "home-text"} "Hola soy María, gracias por visitar esta página donde puedes ver alguna de mis obras, pinturas y esculturas."[:br][:br] "Mi taller lo tengo en Santa Ponsa, Mallorca, y si quieres contactar lo puedes hacer en mi enlace."] ] ] )) ;; Paintings (defn paintings-panel [] (let [paintings (re-frame/subscribe [::subs/paintings])] [:div {:class "painting-list-container"} [product-image-modal] ;; Render product image modal, hidden by default (for [painting (seq @paintings)] ^{:key painting} ;; metadata to avoid warning with iterator requiring a key [:div {:class "painting-container"} [:img {:src (:image painting) :on-click #(re-frame/dispatch [::events/toggle-product-image-modal {:visible true :image-path (:image painting)}]) }] [:p {:dangerouslySetInnerHTML {:__html (:description painting)}}]] )] )) ;; Sculptures (defn sculptures-panel [] (let [sculptures (re-frame/subscribe [::subs/sculptures])] [:div {:class "sculpture-list-container"} [product-image-modal] ;; Render product image modal, hidden by default (for [sculpture (seq @sculptures)] ^{:key sculpture} ;; metadata to avoid warning with iterator requiring a key [:div {:class "sculpture-container"} [:img {:src (:image sculpture) :on-click #(re-frame/dispatch [::events/toggle-product-image-modal {:visible true :image-path (:image sculpture)}]) }] [:p {:dangerouslySetInnerHTML {:__html (:description sculpture)}}]] )] )) ;; About (defn about-panel [] [:div {:class "about-container; about-text"} [:div {:style {:float "center"}} [:p "El arte siempre ha estado presente en mi vida, ha sido mi guía durante los muchos años vividos en diferentes países en los que no he dejado nunca de observar y aprender."[:br] "Mi residencia ahora es la isla de Mallorca donde continúo haciendo lo que me gusta, crear, expresar a través de la escultura o la pintura."[:br] "El arte sirve de tránsito entre el sentimiento que nace del artista y el que recibe el espectador; y eso es lo que intento transmitir desde mi taller de Santa Ponsa."] [:img {:class "about-image" :src "img/about.jpg"}] [:p "Arts are my lifelong passion that have guided me to observe and learn whilst living in different countries around the world."[:br] "I live on the island of Mallorca now where I continue to create and express art through sculptures and paintings."[:br] "Art acts as a medium to convey the artists emotions to those who receive it which is what I aim to do from my workshop in Santa Ponsa."] ] ]) ;; Main (defn- panels [panel-name] [:div [:div {:class "header-banner"} [:h1 {:class "header-banner-text"} [:a {:href "#/home" :class "header-banner-text"} "Galacart Gallery"]] [:p {:class "header-banner-subtext"} "Mallorca, Santa Ponsa"]] [:div {:class "menu-and-products-container"} [:ul [:li [:a {:href "#/paintings"} "Paintings"]] [:li [:a {:href "#/sculptures"} "Sculptures"]] [:li [:a {:href "#/about"} "About"]] ] (case panel-name :home-panel [home-panel] :paintings-panel [paintings-panel] :sculptures-panel [sculptures-panel] :about-panel [about-panel] [:div]) ] ]) (defn show-panel [panel-name] [panels panel-name]) ;; Timer function called every 5 seconds to change the home page image (defn dispatch-timer-event [] (re-frame/dispatch [::events/change-home-image])) (defn main-panel [] (defonce do-timer (js/setInterval dispatch-timer-event 5000)) (let [active-panel (re-frame/subscribe [::subs/active-panel])] [show-panel @active-panel]))
99837
(ns galacart-gallery.views (:require [re-frame.core :as re-frame] [galacart-gallery.subs :as subs] [galacart-gallery.events :as events] )) ;; Product image modal, hidden by default (defn product-image-modal [] (let [product-image-modal (re-frame/subscribe [::subs/product-image-modal])] [:div {:class "product-image-modal" :style {:display (if (:visible @product-image-modal) "block" "none")}} [:div [:span {:dangerouslySetInnerHTML {:__html "&times;"} :on-click #(re-frame/dispatch [::events/toggle-product-image-modal {:visible false}])}] ;; cross symbol to close window [:img {:src (:image-path @product-image-modal)}] ]])) ;; Home (defn home-panel [] (let [home-image (re-frame/subscribe [::subs/home-image])] [:div {:class "home-container"} [:div {:style {:float "left"}} [:img {:class "home-image" :src @home-image}] ] [:div {:style {:float "right" :max-width "40vw"}} [:h1 "Welcome! Bienvenidos!"] [:p {:class "home-text"} "Hi I'm <NAME>, thanks for visiting my website where you can find some of my works - paintings and sculptures."[:br][:br] "My studio is located in Santa Ponsa, Mallorca (Spain), and I can be reached via e-mail."] [:hr] [:p {:class "home-text"} "Hola soy <NAME>, gracias por visitar esta página donde puedes ver alguna de mis obras, pinturas y esculturas."[:br][:br] "Mi taller lo tengo en Santa Ponsa, Mallorca, y si quieres contactar lo puedes hacer en mi enlace."] ] ] )) ;; Paintings (defn paintings-panel [] (let [paintings (re-frame/subscribe [::subs/paintings])] [:div {:class "painting-list-container"} [product-image-modal] ;; Render product image modal, hidden by default (for [painting (seq @paintings)] ^{:key painting} ;; metadata to avoid warning with iterator requiring a key [:div {:class "painting-container"} [:img {:src (:image painting) :on-click #(re-frame/dispatch [::events/toggle-product-image-modal {:visible true :image-path (:image painting)}]) }] [:p {:dangerouslySetInnerHTML {:__html (:description painting)}}]] )] )) ;; Sculptures (defn sculptures-panel [] (let [sculptures (re-frame/subscribe [::subs/sculptures])] [:div {:class "sculpture-list-container"} [product-image-modal] ;; Render product image modal, hidden by default (for [sculpture (seq @sculptures)] ^{:key sculpture} ;; metadata to avoid warning with iterator requiring a key [:div {:class "sculpture-container"} [:img {:src (:image sculpture) :on-click #(re-frame/dispatch [::events/toggle-product-image-modal {:visible true :image-path (:image sculpture)}]) }] [:p {:dangerouslySetInnerHTML {:__html (:description sculpture)}}]] )] )) ;; About (defn about-panel [] [:div {:class "about-container; about-text"} [:div {:style {:float "center"}} [:p "El arte siempre ha estado presente en mi vida, ha sido mi guía durante los muchos años vividos en diferentes países en los que no he dejado nunca de observar y aprender."[:br] "Mi residencia ahora es la isla de Mallorca donde continúo haciendo lo que me gusta, crear, expresar a través de la escultura o la pintura."[:br] "El arte sirve de tránsito entre el sentimiento que nace del artista y el que recibe el espectador; y eso es lo que intento transmitir desde mi taller de Santa Ponsa."] [:img {:class "about-image" :src "img/about.jpg"}] [:p "Arts are my lifelong passion that have guided me to observe and learn whilst living in different countries around the world."[:br] "I live on the island of Mallorca now where I continue to create and express art through sculptures and paintings."[:br] "Art acts as a medium to convey the artists emotions to those who receive it which is what I aim to do from my workshop in Santa Ponsa."] ] ]) ;; Main (defn- panels [panel-name] [:div [:div {:class "header-banner"} [:h1 {:class "header-banner-text"} [:a {:href "#/home" :class "header-banner-text"} "Galacart Gallery"]] [:p {:class "header-banner-subtext"} "Mallorca, Santa Ponsa"]] [:div {:class "menu-and-products-container"} [:ul [:li [:a {:href "#/paintings"} "Paintings"]] [:li [:a {:href "#/sculptures"} "Sculptures"]] [:li [:a {:href "#/about"} "About"]] ] (case panel-name :home-panel [home-panel] :paintings-panel [paintings-panel] :sculptures-panel [sculptures-panel] :about-panel [about-panel] [:div]) ] ]) (defn show-panel [panel-name] [panels panel-name]) ;; Timer function called every 5 seconds to change the home page image (defn dispatch-timer-event [] (re-frame/dispatch [::events/change-home-image])) (defn main-panel [] (defonce do-timer (js/setInterval dispatch-timer-event 5000)) (let [active-panel (re-frame/subscribe [::subs/active-panel])] [show-panel @active-panel]))
true
(ns galacart-gallery.views (:require [re-frame.core :as re-frame] [galacart-gallery.subs :as subs] [galacart-gallery.events :as events] )) ;; Product image modal, hidden by default (defn product-image-modal [] (let [product-image-modal (re-frame/subscribe [::subs/product-image-modal])] [:div {:class "product-image-modal" :style {:display (if (:visible @product-image-modal) "block" "none")}} [:div [:span {:dangerouslySetInnerHTML {:__html "&times;"} :on-click #(re-frame/dispatch [::events/toggle-product-image-modal {:visible false}])}] ;; cross symbol to close window [:img {:src (:image-path @product-image-modal)}] ]])) ;; Home (defn home-panel [] (let [home-image (re-frame/subscribe [::subs/home-image])] [:div {:class "home-container"} [:div {:style {:float "left"}} [:img {:class "home-image" :src @home-image}] ] [:div {:style {:float "right" :max-width "40vw"}} [:h1 "Welcome! Bienvenidos!"] [:p {:class "home-text"} "Hi I'm PI:NAME:<NAME>END_PI, thanks for visiting my website where you can find some of my works - paintings and sculptures."[:br][:br] "My studio is located in Santa Ponsa, Mallorca (Spain), and I can be reached via e-mail."] [:hr] [:p {:class "home-text"} "Hola soy PI:NAME:<NAME>END_PI, gracias por visitar esta página donde puedes ver alguna de mis obras, pinturas y esculturas."[:br][:br] "Mi taller lo tengo en Santa Ponsa, Mallorca, y si quieres contactar lo puedes hacer en mi enlace."] ] ] )) ;; Paintings (defn paintings-panel [] (let [paintings (re-frame/subscribe [::subs/paintings])] [:div {:class "painting-list-container"} [product-image-modal] ;; Render product image modal, hidden by default (for [painting (seq @paintings)] ^{:key painting} ;; metadata to avoid warning with iterator requiring a key [:div {:class "painting-container"} [:img {:src (:image painting) :on-click #(re-frame/dispatch [::events/toggle-product-image-modal {:visible true :image-path (:image painting)}]) }] [:p {:dangerouslySetInnerHTML {:__html (:description painting)}}]] )] )) ;; Sculptures (defn sculptures-panel [] (let [sculptures (re-frame/subscribe [::subs/sculptures])] [:div {:class "sculpture-list-container"} [product-image-modal] ;; Render product image modal, hidden by default (for [sculpture (seq @sculptures)] ^{:key sculpture} ;; metadata to avoid warning with iterator requiring a key [:div {:class "sculpture-container"} [:img {:src (:image sculpture) :on-click #(re-frame/dispatch [::events/toggle-product-image-modal {:visible true :image-path (:image sculpture)}]) }] [:p {:dangerouslySetInnerHTML {:__html (:description sculpture)}}]] )] )) ;; About (defn about-panel [] [:div {:class "about-container; about-text"} [:div {:style {:float "center"}} [:p "El arte siempre ha estado presente en mi vida, ha sido mi guía durante los muchos años vividos en diferentes países en los que no he dejado nunca de observar y aprender."[:br] "Mi residencia ahora es la isla de Mallorca donde continúo haciendo lo que me gusta, crear, expresar a través de la escultura o la pintura."[:br] "El arte sirve de tránsito entre el sentimiento que nace del artista y el que recibe el espectador; y eso es lo que intento transmitir desde mi taller de Santa Ponsa."] [:img {:class "about-image" :src "img/about.jpg"}] [:p "Arts are my lifelong passion that have guided me to observe and learn whilst living in different countries around the world."[:br] "I live on the island of Mallorca now where I continue to create and express art through sculptures and paintings."[:br] "Art acts as a medium to convey the artists emotions to those who receive it which is what I aim to do from my workshop in Santa Ponsa."] ] ]) ;; Main (defn- panels [panel-name] [:div [:div {:class "header-banner"} [:h1 {:class "header-banner-text"} [:a {:href "#/home" :class "header-banner-text"} "Galacart Gallery"]] [:p {:class "header-banner-subtext"} "Mallorca, Santa Ponsa"]] [:div {:class "menu-and-products-container"} [:ul [:li [:a {:href "#/paintings"} "Paintings"]] [:li [:a {:href "#/sculptures"} "Sculptures"]] [:li [:a {:href "#/about"} "About"]] ] (case panel-name :home-panel [home-panel] :paintings-panel [paintings-panel] :sculptures-panel [sculptures-panel] :about-panel [about-panel] [:div]) ] ]) (defn show-panel [panel-name] [panels panel-name]) ;; Timer function called every 5 seconds to change the home page image (defn dispatch-timer-event [] (re-frame/dispatch [::events/change-home-image])) (defn main-panel [] (defonce do-timer (js/setInterval dispatch-timer-event 5000)) (let [active-panel (re-frame/subscribe [::subs/active-panel])] [show-panel @active-panel]))